Skip to main content

C# 2 - Static Members

In C# 2 there was a new addition in the functionality called static classes and members. When i say "members", i am referring to methods, properties, events and so on. I have a strong opinion about this modifier which i will share with you along the article, but let's start by looking at what "static" means. Take this code as example:

Above we can see that we define two properties and one is static. In the main method we then create an instance of Person and set the normal property (Name). Now notice the Person.NumberOfBrains assignment. This is the static property we created in the class. Notice that the access is made at class level, instead of instance level. This means that there will only be one NumberOfBrains value throughout all Person instances, but there will be a Name value per each instance of Person.

Of course, the example is not the best, but you get the idea. Static applies when all instances share the same value. There are some rules to be aware when you use static.
  • You can't access instance members in static methods. If i had a static method in the Person class, i would not be able to access the Name property. 
  • You can't have non-static members in static classes.  

  • You can't instantiate a static class. What would you instantiate anyway?
  • You loose OO concepts such as inheritance, and composition (such as implementing interfaces and deriving from classes).
This last one is one of the reasons why i don't like static code. Let's see why i think this:
  • Static code is not easily testable and mockable. Most isolation frameworks (except super-frameworks) use inheritance to create fake implementations of a class and thus provide an empty implementation for unit testing purposes. If you are using a static class, you can't use such framework and can't isolate parts of the code that use that static class. This is a big hit for me.
  • Static classes don't provide good means of allowing your code to be extensible. You can't inherit from a static class (what would you be inheriting) and you can't obviously override it's methods/properties. This completely seals the class for extension.
  • I've seen excuses like 'this way you don't have to instantiate an object'. This is non-sense to me by itself. Of course i don't have to instantiate, but what do i gain from that? Only in very simple cases i wouldn't want to use an instance of an object as this would be a good way to keep the behavior flexible.
  • Static classes and members get really messy, really fast when you contain application state (or even worse, business logic) in such places. Before you know it, you have to pass a myriad of objects or create a Data Transfer Object for the sole purpose. 
I work with a code base heavily based on static classes, so you could say that i know this facts for experience. I've seen an entire Data Access Layer based on static classes and this is not something i am proud of . Of course, testing it is a nightmare and can only be done manually, because you cannot mock static dependencies. 

Apart from this, i think there are some valid situations where static classes are actually useful.
  • To contain helper methods that don't really do much (look at .Net's Convert class, for example)
  • To maintain a list of globally accessible variables or services to the entire application. I make these static so i don't have to instantiate an object and inject it everywhere. Of course, i do this only for very, very, very simple cases. Usually, this "Global" static class only contains properties (of interface types), so i can maximize testability. 
  • As we will see, static classes have big importance in C# with the introduction of Extension Methods. More on this later.
  • To contain methods that don't really have a place in a specific class.
My take is: always try to keep actual behavior and business logic out of static members. Why are you using an OO language like C# if you are denying it's OO capabilities? Of course, there will always be a situation when using static is better or easier, so it's a welcome addition to the language! 

Comments

Popular posts from this blog

From crappy to happy - dependency what, now?

Following the introduction on this series on a previous post, we will now talk about dependency injection and how it has the effect of allowing for more testable code. Sometimes when I talk about this concept it is difficult to explain the effect that applying it might have on the tests. For that reason I think it is better to demonstrate with a near-real-world situation. Obviously, keep in mind this is not real code, so don't worry about the design or implementation details that don't contribute to the point being discussed. The code As you can see, it is simple. There's a class called ShipManager (what else?) that receives position updates for the ships. It keeps the last position reported from each ship and does some calculation to see how much the ship moved. It assigns some values to the update and finally it persists the final version of the update. How do we start testing? When you think about it, tests are dead simple. A test either passes or it doesn...

Why is the Single Responsability Principle important?

The Single Responsability Principle is one of the five S.O.L.I.D. principles in which i base my everyday programming. It tells us how a method or class should have only one responsability. Not a long time ago i was designing a reporting service with my colleague Nuno for an application module we were redoing and we had a method that was responsible for being both the factory method of a popup view and showing it to the user. You can see where this is going now... I figured out it would not be a that bad violation of the principle, so we moved on with this design. The method was called something like "ShowPrintPopup" and it took an IReport as an argument. All this was fine, but then we got to a point where we needed to have a permissions system to say if the user was able to export the report to Excel, Word, PDF, etc... The problem was the print popup would need to know beforehand if it would allow the user to export the report or not, so that it could show it's UI a...

The repository's repository

Ever since I started delving into architecture,  and specifically service oriented architecture, there has been one matter where opinions get divided. Let me state the problem first, and then take a look at both sides of the barricade. Given that your service layer needs to access persistent storage, how do you model that layer? It is almost common knowledge what to do here: use the Repository design pattern. So we look at the pattern and decide that it seems simple enough! Let's implement the shit out of it! Now, let's say that you will use an ORM - here comes trouble. Specifically we're using EF, but we could be talking about NHibernate or really any other. The real divisive theme is this question: should you be using the repository pattern at all when you use an ORM? I'll flat out say it: I don't think you should... except with good reason. So, sharpen your swords, pray to your gods and come with me to fight this war... or maybe stay in the couch? ...