I've recently caught an odd behaviour in my own coding: At some point in the last year I began creating protected static
methods to implement the logic of my public
methods, ensuring that the protected static
version contains all of the logic, but is not affected by state.
e.g.
class Demo
{
string someAttribute;
public Demo(string someAttribute)
{
this.someAttribute = someAttribute;
}
// public method only calls the static method, passing all
// parameters sent to the public function as well as any
// of the object's attributes required by the function.
public string AppendSomeAttribute(string textToAppendTo) =>
AppendSomeAttribute(textToAppendTo, someAttribute);
// static method is not publicly exposed. It contains all
// of the function's logic, but is not affected by state
protected static string AppendSomeAttribute(string textToAppendTo, string someAttribute) =>
string.Concat(textToAppendTo, someAttribute);
/*
// this is what a normal person would do:
public string AppendSomeAttribute(string textToAppendTo) =>
string.Concat(textToAppendTo, someAttribute);
*/
}
I can't recall reading anything that would have triggered this change. My best guess is I read something advising it which stuck in my subconscious; but it may just be a bad habit I'd unconsciously picked up.
Trying to work out why this may be advised I came up with the following:
- All logic is handled in a single place; so where there are multiple public methods taking different parameters this helps keep all logic in one routine (definitely makes sense where the version of that routine which supplies all parameters is not supposed to be publicly exposed; otherwise I can't see a benefit).
- By removing the object's state from the equation the logic of these methods is more easily tested / proven; either by unit tests, or when copy-pasting code to LinqPad (or similar) to try it out in a sandbox.
However, those aren't great justifications for doing this as a de-facto coding style (i.e. where there isn't a specific scenario to justify this, such as the many public overloads of the same method with none taking all parameters example, as outlined above).
Question:
Is there any clear benefit to writing code in this way?