Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bad practice doing: new... ().doSomething()?

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?

like image 743
ItFreak Avatar asked Jan 26 '23 10:01

ItFreak


2 Answers

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.

like image 102
Andrew Tobilko Avatar answered Feb 02 '23 12:02

Andrew Tobilko


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

like image 27
user7294900 Avatar answered Feb 02 '23 12:02

user7294900