Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this appropriate to create a class with one method? [closed]

I'm wondering whether it's a good practice to produce the code which being used like this:

new TemplateProcessor(inputStream).processTemplate("output-path.xhtml");

Here, TemplateProcessor contains only one public method. It seems the code above can be expressed with a static method, but I would like to avoid that. The reason is simple: object may contain encapsulated state, (maybe now, maybe in the future). Dear experts what would You prefer in this case?

like image 654
dazu Avatar asked Dec 20 '13 20:12

dazu


1 Answers

It's reasonable to encapsulate the code in a static method, with static imports it becomes very easy to use:

processTemplate(inputStream, "output-path.xhtml");

The above static method would just be a façade, a convenience method to be used for that specific use case that your class is solving, supposedly one that's very common. It does not prevent the class from evolving, even adding state. For more specialized use cases, the consumers can still create instances of the class and use its methods as usual.

To make that separation even more pronounced, you could add the static method to a sibling class, like TemplateProcessorFacade, which is a non-instantiatable utility class:

public final class TemplateProcessorFacade {
  private TemplateProcessorFacade() {}
  public static void processTemplate(...) {
    ...
  }
}
like image 98
Jordão Avatar answered Oct 21 '22 02:10

Jordão