Juice this "static" up a little

Juice this "static" up a little

    Static members and methods are basically the same as a non-static members and methods, but there is one difference: you don't need an instance variable to access them. For example, if you have a static class that is named HelperClass that has a public method named DoStuff, you call the method as shown in the following example:

HelperClass.DoStuff()

    For more information about statics see "Static Classes and Static Class Members (C# Programming Guide)".

    The good about statics:
  • single point data manipulation
  • less memory usage (no instances)
  • faster access/call times (the compiler generates overhead for non-static members and methods)
  • low level of code complexity
    The bad about statics:
  • statics limitations (no inheritance, no overriding, can't use non-statics, etc.)
  • code rigidity
  • harder to test
  • no control over the life cycle (remains in memory for the lifetime of the application domain)
  • no inversion of control techniques
    In the following, i will show you some tips on how to use statics more efficiently. It will not solve all of the problems statics have, but it will give you some second thoughts.

Monostate pattern

    The monostate pattern attempts to hide the fact that a class is only operating on a single instance of data trough static members by creating a non-static wrapper over the static members and methods:

public class Monstate
{
    private static bool _someFlag;
    public bool SomeFlag
    {
        get { return _someFlag; }
        set { _someFlag = value; }
    }

    private static void _DoStuff()
    {
        ...
    }

    public void DoStuff()
    {
        _DoStuff();
    }
}

    It provides an interesting way to keep single point data manipulation, while still allowing your classes to have multiple instances. By doing so the code is easier to test and it is compatible with inversion of control techniques. Monostate classes are also easier to inherit from and modify and don't have as many multi-threading issues as in the case of the Singleton pattern.

Flyweight pattern

    The flyweight pattern is used for better memory management by storing the common data used by the instance variables of a class in static members (in the same class or as an external structure). By doing so a larger number of objects should be supported more efficiently and fewer duplicate data. 

Enjoy (ง°ل͜°)ง

Comments

Popular Posts