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
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
October 2012
2012