On Wednesday, September 26th, the Wellington .NET User group got together for a roundtable discussion on day to day programming. Based on notes taken that night, here’s a summary of one of our discussions.

See also Of Method Naming and More.

Given a method that doesn’t need any member variables, should it be a member or should be static or something else?

Examples of when this situation arises can include:

  • Exception handling

  • Reading configuration files

Static methods (especially private ones) on a non-static class may be a code-smell - indication of another concept that may need to be broken out in line with the single responsibility principle.

A purely static class can be useful to group related methods that have no shared state. These methods should be pure functions where the result depends solely on the inputs, not on any state held elsewhere.

Each static class should have exactly one responsibility - don’t create catch-all static classes.

A useful technique for improving testability: Break complex functionality out into a static pure function, isolated from the original (potentially heavyweight) object. Back on the original object, a gateway method (non-static) can invoke the static function passing all necessary information.

If it doesn’t need state, make it static.

Shared state gets in the way of multi-threading and multi-tasking code. If your static classes have any static fields, you end up with shared state across your entire codebase. If the static class is not explicitly written to handle multiprocessing, this is a recipe for extreme pain. Best to ensure your static members are pure functions wherever possible. If you can’t achieve this, make sure you use appropriate locking techniques.

If you are unit testing - this includes TDD and BDD as well as Test Last and other approaches - then static methods can be a real pain as they promote high coupling. Avoiding this pain is usually achieved through the use of dependency injection of a configured singleton, though this adds complexity in other ways.

For a high performance situation, where you need to wring the very last bit of performance out of the code, not having to pass the hidden this parameter to a method may allow for more parameter passing by register. Only applicable for the extreme performance case, and may be rendered moot by improvements to the JITter.


blog comments powered by Disqus
Next Post
Solve the right problem  24 Nov 2012
Prior Post
Of Method Naming and more  29 Sep 2012
Related Posts
When (not) to use Var  16 Jul 2016
Semantic Types Redux  05 Jun 2016
Semantic Types in C#6  27 May 2016
Property Enhancements for C#  20 Dec 2015
Language Extensions for C#  19 May 2014
Of Method Naming and more  29 Sep 2012
Someone needs an intervention  16 Dec 2011
CallerInfo in C# 5  08 Dec 2011
Regions in C#  16 May 2011
Lambda expressions and Block syntax  15 Apr 2011
More csharp posts »
Related Pages
October 2012 archive