Page tree


  Wiki Navigation


 Recently Updated

 Latest Releases

 MediaPortal 1.22 
            Releasenews | Download
 MediaPortal 2 2.2.1 
            Releasenews | Download

Why avoid statics?

Statics can be very useful in programming. Simply make something static and it is available everywhere. However, the downside of them is tracing the program flow. Find where they are created (the first time they are used).

As few other problems include:

  • Exceptions in Static constructors cannot be caught by the program.
  • Hard to unit test.
  • Build a tight relationship between the classes making change more difficult.

Which statics should be avoided?

Generally static classes should be avoided. Static methods in a normal class are not a problem and a good way of providing helper functions that do not require an instance of the class. (However, a class of many unrelated static methods is also not so good, but that is another story.)

How to avoid statics?

Statics can be avoided through a method called Dependency Injection (DI), this allows an instance of an object to be injected where it is needed.

In MediaPortal we have a singleton called ServiceRegistration which enables DI. Any class can be turned into a Service by simply creating an interface for that class. An instance of the class can then be added to the ServiceRegistration and is available to all other classes.

The advantages of this method are:

  • The point where the instance is created and loaded is known
  • The service class can be more easily tested.
  • The class can be easily swapped for another class using the same interface.



This page has no comments.