javaconstructorstatic-methodsobject-construction

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?


Solution

  • 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.