Classes or static methods?

261 views
Skip to first unread message

Gábor Szabó

unread,
Aug 16, 2017, 2:58:36 PM8/16/17
to Clean Code Discussion
Dear fellow Clean Coders,

I have a question about choosing between two possible designs.

There are some code katas that doesn't specify whether the expected functionality should be implemented in a separate class (requiring to create a new instance of the class to run the functionality) or in a simple function (or a static method in a language where you have to have a class).

When practicing TDD, you first think of the API, how you would like to use the code. And it is easier and more convenient to only have to call a single function, like
const wrapped = wrap(input); // or static method call like Wrapper.wrap(input)
instead of
const wrapper = new Wrapper();
const wrapped = wrapper.wrap(input); // or pass input into constructor

On the other hand, if you have a class, and an instance of it, then you can have all the input arguments and intermediate values on the 'this' context. That makes it easier to refactor, to extract functions without having to pass all the necessary arguments (however, some say accessing and manipulating 'this' makes it harder to understand for them, as the method becomes impure, having side effects).

A lot of the times I end up exposing a simple function on the API that the tests/clients can just call, and I create a class for only to instantiate and call from the exposed function. That class is for that private use only, and usually becomes a 'command-like' class, since it is instantiated and executed every time it is used.

What are your heuristics deciding whether a class or just a simple function? Are there other options? How do you choose the design? What other aspects needs to be taken into consideration? 

Cheers,
Gabor

Łukasz Duda

unread,
Aug 21, 2017, 7:38:54 AM8/21/17
to Clean Code Discussion
You can consider Open-Close Principle and Dependency-Inversion Principle. If you have static method, do you call it directly? Is there any place where you can replace one implementation with another or extend it without having to change it?

Regards
Łukasz
Message has been deleted

Chilon Sage

unread,
Oct 4, 2017, 5:53:11 PM10/4/17
to Clean Code Discussion
Hello,

Since the logic can be implemented inside a static method, I suppose there is no need for side effects/mutable state. So even if you use a regular class with a constructor, you should make sure that this class is immutable.

Then the choice between the two only becomes a matter of convenience. If you need to call the wrap method multiple times with some of the arguments remaining constant, then you could pass the contant arguments only once to the constructor. Otherwise you could stick with the static method.
Reply all
Reply to author
Forward
0 new messages