Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Helper/Utility Classes be abstract?

I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these?

What would the Pros and Cons be to declaring such a class as abstract.

public [abstract] class Utilities{     public static String getSomeData(){        return "someData";    }     public static void doSomethingToObject(Object arg0){    } } 
like image 926
shsteimer Avatar asked Nov 21 '08 17:11

shsteimer


People also ask

What classes should be abstract?

In general, a class should be abstract when you have absolutely no reason to create an instance of that class. For example, suppose you have a Shape class that is the superclass of Triangle, Square, Circle, etc.

What is the utility of abstract class?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

What is difference between helper and utility class?

A Utility class is understood to only have static methods and be stateless. You would not create an instance of such a class. A Helper can be a utility class or it can be stateful or require an instance be created. Create Utility class if you want to have methods that are used by several operations.

Should parent classes be abstract?

Yes, it is reasonable and beneficial to mark explicitly as abstract a base class that should not be instantiated -- even in the absence of abstract methods. It enforces the common guideline to make non-leaf classes abstract. It prevents other programmers from creating instances of the class.


2 Answers

You could just declare a private constructor that does nothing.

The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.

like image 69
Outlaw Programmer Avatar answered Sep 17 '22 21:09

Outlaw Programmer


Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated.

Point of comparison for those interested: in C# you would declare the class to be static, making it abstract and sealed (Java's final) in the compiled form, and without any instance constructor at all. That also makes it a compile-time error to declare a parameter, variable, array etc of that type. Handy.

like image 31
Jon Skeet Avatar answered Sep 19 '22 21:09

Jon Skeet