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

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
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?

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(...) {
...
}
}

A class should be seen as an object or module that performs a key role or function in the program. A role that no other class or module fulfils. For example, you can have a class Animal that provides the functions sleep(), run() . But you might want a class for carnivores which also kill() , hunt() etc. So you implement the Carnivores class by extending from Animal, which does what all variables of type Animal do, but also additionally kill and hunt.
If your class has only one public method, but if it's important for the design to have it as a separate module, then having a class for it is good. You can extend it later, if needed.
Also you can, keep the sleep() and run() functions static and public, all Animal's do that, and so you can just do Animal.sleep() and such, without creating a separate instance. But a function like roar() shouldn't be.
Update:
The reason I said, sleep() and run() can be static is, there can be a class Man who also sleeps and runs.
The question to ask:
Does it make sense to call sleep() and run() or any function of a class without initializing an object of that class? If yes, then it makes sense to make it static.

Related

Is it a good practice to declare class with only static members as abstract? [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I recently came across some code where a public static method was defined inside an abstract class. I am wondering whether this is considered good practice or an anti-pattern?
I've produced a simple example program to illustrate what I mean.
public abstract class StaticMethodsInAbstractClassesStudy {
public static int adder(int a, int b){
return a + b;
}
}
public class StaticMethodsInClassesStudy {
public static void main(String [] args){
System.out.println(StaticMethodsInAbstractClassesStudy.adder(2, 3));
}
}
When you run the code you get the result of 5 which proves that I was able to run code inside of an abstract class.
I've deliberately not added extends to StaticMethodsInClassesStudy to emphasise the point that it's perfectly possible to run code directly inside an abstract class without instantiating an extending class.
Personally I would have thought that this is bad practice since you're using an abstract class as a normal Class and thereby bypassing the intent of abstract classes. Shouldn't these kinds of methods be kept in separate "normal" java classes e.g. utility classes ?
It's not bad practice per se, unless the abstract class is actually not meant to be subclassed, and abstract is only there to prevent instantiation. The best practice for a class providing only static utilities would be to make it final, and to have a private constructor.
I agree with you that a abstract class make us think of something to not use until it will be instantiated.
It's allowed and useful to insert some support methods inside an abstract class without enforce the developer to implement that class.
Also in an Interface you can put static methods, and you can use them without implementing that interface.

Static methods in abstract class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I recently learned from a video that it's a good practice to turn a Java class into abstract if all of its methods are static for performance reasons.
Can anyone explain why this is the case?
This is likely to prevent people from creating instances of the class. Java code is expected to create lots of objects that are useful for a short time and get garbage-collected, so it is hard to say this is any kind of substantial performance win. It seems more like a way to communicate the intention behind a class.
Another alternative is, instead of making the class abstract, make the class final. This is the approach taken in JDK code, for instance, java.lang.Math:
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
With either of these approaches you should give the class a private constructor. That prevents anyone from instantiating it and makes it clear the class's purpose is to provide a home for the static methods. The downside here is code coverage tools tend to report the constructor as uncovered.
A third alternative, as of Java 8, is to put the static methods on an interface. Any methods with an implementation that aren't default get assumed to be static methods. The advantage of that approach is there is no constructor to make private, and the code coverage tools will be happy.
With an abstract class (but without the private constructor), or an interface, there is also the possibility of extending or implementing the type to make all the static methods available without static imports. See this link for an example. With the java.lang.Math approach that isn't an option.
You don't have to make it an abstract if it has static methods. if you make it an abstract class then no one can instantiate this class.
on the other hand, you can declare a class with a private constructor, so no one, not even a subclass, can instantiate an instance of your class.
public class A
{
private A()
{
throw new RuntimeException("Instantiation of MyUtility is not
allowed!");
}
public static void aMethod()
{
// Your method here.
}
}

Is using a class (not interface) as a type is a bad practice for parametrized class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have code similar to this
public class NewClass extends GenericClass<SomeClass>
but I'm not sure if it is really a bad practice, may be it should be done like this
public class NewClass extends GenericClass<SomeInterface>
or am I just making it up, and there's no such convention and my suggestion is only based on general interface good/class bad logic?
I couldn't find anything about this, only info on generics, that may be not that much true in this case.
It isn't a bad practice, for my opinion, because the generic type may be either a Class or an Interface, accordingly to the purpose it is defined to be.
public class NewClass extends GenericClass<SomeClass>
this can be interpreted as "extends a generic class that uses a specific class or subclass": so that parameter class must have some members/methods.
public class NewClass extends GenericClass<SomeInterface>
this can be interpreted as "extends a generic class that implements a specific Interface or subInterface": so that parameter class must implements methods defined in that Interface and therefore NewClass can invoke them securely assuming that those methods are available.
I do this all the time, but I make my choices pragmatically. More specifically, I might do something like this:
public FooArray extends ArrayList<Foo> {
public void loadFromFile(String filename) {
...
}
}
You quite literally can't do something like that with an interface unless you also pass in a factory. Now, are there other ways to accomplish the same thing? Certainly. But I find this code clear, useful, and very easy to maintain.

Is exposing static methods in abstract classes considered good or bad practice [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I recently came across some code where a public static method was defined inside an abstract class. I am wondering whether this is considered good practice or an anti-pattern?
I've produced a simple example program to illustrate what I mean.
public abstract class StaticMethodsInAbstractClassesStudy {
public static int adder(int a, int b){
return a + b;
}
}
public class StaticMethodsInClassesStudy {
public static void main(String [] args){
System.out.println(StaticMethodsInAbstractClassesStudy.adder(2, 3));
}
}
When you run the code you get the result of 5 which proves that I was able to run code inside of an abstract class.
I've deliberately not added extends to StaticMethodsInClassesStudy to emphasise the point that it's perfectly possible to run code directly inside an abstract class without instantiating an extending class.
Personally I would have thought that this is bad practice since you're using an abstract class as a normal Class and thereby bypassing the intent of abstract classes. Shouldn't these kinds of methods be kept in separate "normal" java classes e.g. utility classes ?
It's not bad practice per se, unless the abstract class is actually not meant to be subclassed, and abstract is only there to prevent instantiation. The best practice for a class providing only static utilities would be to make it final, and to have a private constructor.
I agree with you that a abstract class make us think of something to not use until it will be instantiated.
It's allowed and useful to insert some support methods inside an abstract class without enforce the developer to implement that class.
Also in an Interface you can put static methods, and you can use them without implementing that interface.

Which use for non-inherited abstract classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What does good practice tells us about non-inherited abstract classes ?
Is there a reason for them to exist in a program not aiming at providing an API ? Could it make sense to systematically turn such classes into non-abstract classes? If so in which cases ?
Well, abstract keyword forbids inctances creation (in order to create an instance one has to inherit from abstract class), however, abstract classes can have static methods e.g.
// abstract: there's no sence in creating an instance of this class
abstract class MathLibrary {
// private: there's no sence in inheriting from this class
private MathLibrary() {}
// Gamma function
public static double gamma(double value) { ... }
...
}
please note, that when in Java abstract final class is not allowed, in C# abstract sealed class is static class:
// C# static == abstract sealed
public static class MathLibrary {
// Gamma function
public static double Gamma(double value) { ... }
...
}
Short answer : The one and only reason for creating Abstract Classes is to inherit them.
Note : This is why we can't creat a class or method using a combinaison of the abstract and final keywords because a final class cannot be subclassed.
IMHO, they have no use, since they can only be used when inherited.
Neither would it be of use to transform them into non-abstract classes, since ... You're not using them.
An abstract class is a blueprint to build on, it shouldn't be able to be instantiated. Maybe somewhere there is an anonymous class extending it?
But being there, means they can be used in the future, so deleting them might not be the good idea you're after, either.
well, practically for me there is no reason to do so.
Any case I can imagine right now it would be better to use other ways/design-patterns like singleton, utility, etc..
Maybe you can use them as template to inherit during runtime by reflection etc... (but this would be inheritance as well).
"non-inherited abstract classes"
That completely defeats the whole point of abstract classes. The idea of abstract classes is to be a blue print for OTHER CLASSES to be build on.
For example, you can build a Car abstract class, then inherit from that class to create diffrent Car Brands classes that automatically have everything that Car has, but each Brand is different. This way you avoid writing all the instance variables and methods that you could have written in Car in each Car Brand.
Also keep in mind, that you cannot create a Car instance, because its impossible for a a car not to have a brand, so it make sense to make Car abstract.

Categories

Resources