I just saw a piece of code that had some classes with only one method. I picked an examples:
public class TempDirCleanupProcess {
public void cleanup(final File directory) {}
}
Then, later on in the code the method was called the following way:
new TempDirCleanupProcess().cleanup(tempDir);
Now I am wondering if this is a bad practice because I have seen such "behavior" only with static methods before. Any oppinions on that?
Sure, it could be refactored into a class with a static method. It would obviate the need for creating an instance every time one needs to call the method. In this particular case with no additional context given, a static method would be a nicer solution.
However, don't forget a class can hold a state and a single method may change that state and return a reference to the current object.
public class Builder {
// state
public Builder buildPart(T part) {
// update the state
return this;
}
}
It would resemble a variation of the builder pattern and make sense.
return new Builder();
return new Builder().buildPart(partA);
return new Builder().buildPart(partA).buildPart(partB);
I can also think of an extremely poor design where this
would be leaked out from cleanup
, so a reference to that new TempDirCleanupProcess()
wouldn't be lost after the line is executed.
It looks like a standard static method, but we don't see all the details
So maybe when you are creating the object you are also creating instance members that are used in the method cleanup
and you must create the object in order to make them available
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With