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
Equality of validation  18 Aug 2018
Short-circuiting validation  11 Aug 2018
Aggregation of validation  04 Aug 2018
Recovery of validation types  28 Jul 2018
Basic validation  21 Jul 2018
Why we need better validation  07 Jul 2018
A question of struct performance  30 Jun 2018
Equality has Symmetry  17 Mar 2018
Type Miscellany  05 Mar 2017
Testing Immutable Types  25 Feb 2017
More csharp posts »
October 2012