Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - is it bad practice not to have a class constructor?

I want to make a helper class that deals with formatting (i.e. has methods to remove punctuation and convert between types, as well as reformatting names etc.). This doesn't seem like it will need any fields - its only purpose is to get passed things to convert and return them, reformatted. Is it bad practice to leave out a constructor? If so, what should my constructor be doing? I was looking at this link and noticed that the class it describes lacks a constructor.

like image 458
false_azure Avatar asked Apr 09 '13 06:04

false_azure


4 Answers

Is it bad practice to leave out a constructor?

Yes - because unless you specify any constructors, the Java compiler will give you a constructor with the same visibility as the class itself.

Assuming all your methods are static - which seems likely unless you want polymorphism - you should make your class final and give it a private constructor, so that other developers don't accidentally create an instance of your class, when that would be pointless. When thinking about an API, any time I can remove the ability for developers to do something stupid, I do so :)

So something like:

public final class Helpers {
    private Helpers() {
    }

    public static String formatDate(Date date) {
        // etc
    }
}

Note that by taking polymorphism out of the equation, you're also removing the possibility of changing this behaviour for tests etc. That may well be fine - I'm not a believer in "no statics, ever" - but it's worth considering.

like image 151
Jon Skeet Avatar answered Oct 21 '22 06:10

Jon Skeet


Any class that has all the methods which do not have or need any state is free to reduce the visibility of constructor by making the constructor private.

Example java.lang.Math class in Java.

As java.lang.Math has all static methods which do similar job as your class they have declared the constructor as private so that nobody can accidentally create the instance of that class.

    /**
     * Don't let anyone instantiate this class.
     */
    private Math() {}
like image 6
Narendra Pathai Avatar answered Oct 21 '22 08:10

Narendra Pathai


Not bad practice. but the example that you have given doesn't have any member variables that can be used in an Object context. In such situations, it's best to have static methods because then you don't need to allocate memory to create objects for the class before calling the methods.

like image 3
kishu27 Avatar answered Oct 21 '22 07:10

kishu27


Compiler will generate a default constructor (with no parameters) for you. If your class has not state and does not extend a class which needs initialization, you can let it without declaring explicit constructor

like image 1
Gab Avatar answered Oct 21 '22 06:10

Gab