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

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? ...

Follow up: improving the Result type from feedback

This post is a follow up on the previous post. It presents an approach on how to return values from a method. I got some great feedback both good and bad from other people, and with that I will present now the updated code taking that feedback into account. Here is the original: And the modified version: Following is some of the most important feedback which led to this. Make it an immutable struct This was a useful one. I can't say that I have ever found a problem with having the Result type as a class, but that is just a matter of scale. The point of this is that now we avoid allocating memory in high usage scenarios. This was a problem of scale, easily solvable. Return a tuple instead of using a dedicated Result type The initial implementation comes from a long time ago, when C# did not have (good) support for tuples and deconstruction wasn't heard of. You would have to deal with the Tuple type, which was a bit of a hassle. I feel it would complicate the ...

C# 2.0 - Partial Types

For those of you interested, i found a very interesting list of features that were introduced in C# in  here . This is a very complete list that contains all the features, and i'm explaining them one by one in this post series. We've talked about  Generics  and  Iterators . Now it's time for some partial types . A partial type  is a type which definition is spread across one or more files. It doesn't have to be in multiple separated files, but can be. This is a very simple concept that can give us many benefits, let's see: If a type is partial, multiple developers can work on every part of it. This allows a more organized way of working and can lead to production improvement.  Winforms , for example, generates a partial class for the form so that the client can separately edit other parts it. This way, a part contains information about the design and the other contains the logic of the form. In fact, this is a very spread pattern across .Net. Ent...