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
Equality has Symmetry  17 Mar 2018
Type Miscellany  05 Mar 2017
Testing Immutable Types  25 Feb 2017
Factory Methods  18 Feb 2017
Queue Concatenation  11 Feb 2017
Complex Queues  04 Feb 2017
The Problem with the Simple Queue  28 Jan 2017
Enumeration of Queues  21 Jan 2017
Reversing Stacks  14 Jan 2017
Simple Queues  07 Jan 2017
More csharp posts »
Archives
October 2012
2012