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.

Comments

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
Simple Queues  17 Nov 2018
Enqueuing Values  10 Nov 2018
Dequeuing Values  03 Nov 2018
Designing the External API  27 Oct 2018
Introducing the Priority Queue  20 Oct 2018
A better approach to reflection  13 Oct 2018
Avoiding Magic Strings  06 Oct 2018
Capturing Validation Metadata  29 Sep 2018
Modelling Validation Metadata  22 Sep 2018
Validation Metadata  15 Sep 2018
More csharp posts »
Archives
October 2012
2012