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?

The evolution of C# - Part III - C# 2.0 - Iterators

It's been a while since i wrote the last post, but i did not forget my purpose of creating a series that shows the evolution of C#. Today i came here to talk about one of the most useful features of C#, even if you dont know you're using it. Let's talk about iterators ! What is an iterator? For those of you who didn't read about the iterator pattern somewhere in the internet or in the "Gang of Four" book, you can read a description  here . The iterator is a class/object/whatever which knows how to traverse a structure. So, if you have a list or collection of objects, an iterator would have the knowledge of how to traverse that collection and access each element that it contains. The iterator is a well known design pattern and is behind many of the wonderful that we have nowadays in .NET (Linq comes to mind). Why is it a feature? Truth be told, an iterator is a concept well known way before .NET even existed. Being an OO Design Pattern, the iterator has

My simplest and most useful type

I have been doing some introspection on the way I write code to find ways that I need to improve. I consider this a task that one must do periodically so that we keep organized. There is a very, very simple problem that occurs in every application I know: How to return the results of an operation to the user? I've seen many implementations. Some return strings, some throw exceptions, some use out parameters, reuse the domain classes and have extra properties in there, etc. There is a myriad of ways of accomplishing this. This is the one I use. I don't like throwing exceptions. There are certainly cases where you have no choice, but I always avoid that. Throughout my architectures there is a single prevalent type that hasn't changed for years now, and I consider that a sign of stability. It is so simple, yet so useful everywhere. The name may shock you, take a look: Yes, this is it. Take a moment to compose yourself. Mind you, this is used everywhere , in every