Is this suitable for creating a class with a single method?

I am wondering if it is good practice to create code that is used as follows:

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

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

+7
java object oop static class
source share
2 answers

It makes sense to encapsulate the code in a static method, with static import it becomes very easy to use:

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

The above static method will be just a facade method that will be used for a specific use case, which your class solves is supposedly very common. This does not stop the class from developing, even adding a fortune. For more specialized use cases, consumers can still instantiate the class and use its methods as usual.

To make this separation even more pronounced, you can add a static method to the sibling class, for example TemplateProcessorFacade , which is a non-intuitive utility class:

 public final class TemplateProcessorFacade { private TemplateProcessorFacade() {} public static void processTemplate(...) { ... } } 
+2
source share

A class should be considered as an object or module that performs a key role or function in a program. A role that no class or module performs. For example, you can have an Animal class that provides sleep() , run() functions. But you may need a class for carnivores that also kill() , hunt() , etc. So, you implement the Carnivores class, expanding from Animal , which makes all variables of type Animal , but also kills hunting in addition.

If your class has only one public method, but if it is important for design to have it as a separate module, then the class is good for it. You can renew it later if necessary.

You can also keep the sleep() and run() functions static and public, all Animal do this, and so you can just do Animal.sleep() , etc., without creating a separate instance. But functions like roar() should not be.

Update: The reason I said sleep() and run() may be static, there may be a class Man , which also sleeps and runs.

Question:

Does it make sense to call sleep() and run() or any function of a class without initializing an object of this class? If so, it makes sense to make it static.

0
source share

All Articles