How to disable warning on Sonar: Hide Utility Class Constructor? - java

I'm getting this warning on Sonar:
Hide Utility Class Constructor:
Utility classes should not have a public or default constructor
My class:
public class FilePathHelper {
private static String resourcesPath;
public static String getFilePath(HttpServletRequest request) {
if(resourcesPath == null) {
String serverpath = request.getSession()
.getServletContext()
.getRealPath("");
resourcesPath = serverpath + "/WEB-INF/classes/";
}
return resourcesPath;
}
}
I want solution to remove this warning on Sonar Qube.

If this class is only a utility class, you should make the class final and define a private constructor:
public final class FilePathHelper {
private FilePathHelper() {
//not called
}
}
This prevents the default parameter-less constructor from being used elsewhere in your code.
Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.

I don't know Sonar, but I suspect it's looking for a private constructor:
private FilePathHelper() {
// No-op; won't be called
}
Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.
(You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)

I use an enum with no instances
public enum MyUtils {
; // no instances
// class is final and the constructor is private
public static int myUtilityMethod(int x) {
return x * x;
}
}
you can call this using
int y = MyUtils.myUtilityMethod(5); // returns 25.

Best practice is to throw an error if the class is constructed.
Example:
/**
* The Class FooUtilityService.
*/
final class FooUtilityService{
/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {
// Throw an exception if this ever *is* called
throw new AssertionError("Instantiating utility class.");
}

You can just use Lombok annotation to avoid unnecessary initialization.
Using #NoArgsConstructor with AccessLevel.PRIVATE as bellow:
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FilePathHelper {
// your code
}

I recommend just disabling this rule in Sonar, there is no real benefit of introducing a private constructor, just redundant characters in your codebase other people need to read and computer needs to store and process.

Alternative using Lombok is use #UtilityClass annotation.
#UtilityClass was introduced as an experimental feature in Lombok v1.16.2:
If a class is annotated with #UtilityClass,
the following things happen to it:
It is marked final.
If any constructors are declared in it, an error is generated.
Otherwise, a private no-args constructor is generated; it throws a UnsupportedOperationException.
All methods, inner classes, and fields in the class are marked static.
Overview:
A utility class is a class that is just a namespace for functions. No instances of it can exist, and all its members are static. For example, java.lang.Math and java.util.Collections are well known utility classes.
This annotation automatically turns the annotated class into one.
A utility class cannot be instantiated.
By marking your class with #UtilityClass, lombok will automatically generate a private constructor that throws an exception, flags as error any explicit constructors you add, and marks the class final.
If the class is an inner class, the class is also marked static.
All members of a utility class are automatically marked as static. Even fields and inner classes.
Example:
import lombok.experimental.UtilityClass;
#UtilityClass
public class FilePathHelper {
private static String resourcesPath;
public static String getFilePath(HttpServletRequest request) {
if(resourcesPath == null) {
ServletContext context = request.getSession().getServletContext();
String serverpath = context.getRealPath("");
resourcesPath = serverpath + "/WEB-INF/classes/";
}
return resourcesPath;
}
}
Reference from official documentation:
https://projectlombok.org/features/experimental/UtilityClass

Although using #UtilityClass annotation will show issue on sonarCube.
So basic problem is "Java provide a default no-argument public constructor" for a class. now we have two solutions -
Remove #UtilityClass and make it static final class with private constructor.
Instead of using it as class, Use it as Enum .
but -
When the problem in sonarQube then use -
#SuppressWarnings("java:###")
"###" rule number.

Add private constructor:
private FilePathHelper(){
super();
}

public class LmsEmpWfhUtils {
private LmsEmpWfhUtils()
{
// prevents access default paramater-less constructor
}
}
This prevents the default parameter-less constructor from being used elsewhere in your code.

SonarQube documentation recommends adding static keyword to the class declaration.
That is, change public class FilePathHelper to public static class FilePathHelper.
Alternatively you can add a private or protected constructor.
public class FilePathHelper
{
// private or protected constructor
// because all public fields and methods are static
private FilePathHelper() {
}
}

make the utility class final and add a private constructor

Related

Java Final class or private constructor

When we want to close a class to inheritance we are declaring class with final,
final class Myclass {}
but when we declare the constructor private it will be the same effect,
class Myclass {
private Myclass() {}
}
But is it really the same? Is there any difference for optimization of code or readability of code? And which classes has to close to inheritance,
immutable class maybe
every method and member variable declared static of class
But for second option java.util.Arrays hasn't been declared with final even if all methods of Arrays are declared static.
but when we declare ctor private it will be the same effect
Not necessarily, consider this example using static classes:
public class SOExample {
private static class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("I have a private constructor");
}
}
private static class ClassThatExtendsClassWithPrivateConstructor extends ClassWithPrivateConstructor {
}
public static void main(String[] args) {
new ClassThatExtendsClassWithPrivateConstructor();
}
}
This will print "I have a private constructor".
but is it really same? is there any difference for optimization of code or readablity of code. and which classes has to close to inheritance,
When a developer sees that a class is final, they understand that the intention of the author was that it should not be extended.
When a developer sees that a class has a private constructor, they understand that the class can't be instantiated. This is generally because it is either a static utility class or a singleton.
But for second option java.util.Arrays hasn't declared with final even if all methods of Arrays declared static
This is a good observation. My guess is that it probably should have been but can't be changed now for backward compatibility.
What I usually do is I make the class final and the constructor private:
it removes the ambiguity about the class use (emphasising it's a utility class)
it keeps the user away from what they aren't supposed to do (to initiate, to extend).
.
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class HttpTool {}
That said, there is nothing wrong with java.util.Arrays. The designer achieves the desired effect (non-instantiability) with the necessary minimum (the private constructor).
If you want to create an immutable class or just a class that for some reason should not have childrens you should declare it as final. Private constructor should be used in utility classes, this way you block inheritance and also make sure instance of the class cannot be created.

Can Util class can be abstract or final?

public final class DateUtil{
public static void t1();
}
public abstract class DateUtil{
public static void t1();
}
abstract classes are meant to be sub-classed, and their sub-classes are meant to be instantiated, so they are not a good fit for utility classes.
If you are asking about a class that contains only static utility methods and shouldn't be instantiated, make it final and make the constructor private. That's what the JDK developers did with classes such as java.lang.Math.
Yes. Either or neither.
General opinion is that it should not be subclassable or instantiable, so add a private constructor. (Some people disagree.)
private DateUtil() {
throw new Error();
}
In general, all Util classes are final and static. It will have private constructor.
So that anyone who is calling the method ,no need to create object and can directly access with class name.

private field vs private static field in abstract class

I am confused about the scope of a private field versus a private static field of an abstract class. For example, consider the following classes and note the field validator,
abstract class ValidComponent {
private static Validator validator = ... //(statement to instantiate new Validator)
/**
* This method is to be used by subclasses in their factory-methods
* to do some validation logic after instantiation.
*/
protected void selfValidate() {
//validation logic
...
validator.validate(this); // <<< This line uses the validator
...
}
}
class ValidUsername extends ValidComponent {
private #NotEmpty String core;
private ValidUsername(String unamestr) {
this.core = unamestr;
}
/** This is the factory-method who use selfValidate() */
public static ValidUsername create(String unamestr) {
ValidUsername vuname = new ValidUsername(unamestr);
vuname.selfValidate();
return vuname;
}
}
class ValidEmail extends ValidComponent {
private #Email String core;
private ValidEmail(String emailstr) {
this.core = emailstr;
}
/** This is the factory-method who use selfValidate() */
public static ValidEmail create(String emailstr) {
ValidEmail vemail = new ValidEmail(emailstr);
vemail.selfValidate();
return vemail;
}
}
The abstract class ValidComponent prepares method selfValidate(), in which the private static field, validator, is used.
The ValidUsername and ValidEmail are subclasses that illustrate the intention of their base class: the method selfValidate() are used in their factory-methods to validate themself.
If my understanding is correct, when vuname.selfValidate() and vemail.selfValidate() are called, both use the same Validator object, i.e. ValidComponent.validator.
But what if I happen to change the modifiers of validator from private static to only private, are Validor objects used in vuname.selfValidate() and vemail.selfValidate() still the same object?
No they are not. The static keyword means the field belongs to a class. It will be a single instance across whole VM. Without the static keyword the field belongs to an object, so each instance of the ValidComponent or its subclasses will produce new Validator object.
I'm not sure but I don't think this is appropriate, to use the same Validator for different objects. Your Valid* classes don't share the same constraints therefore the same validation errors. Sharing the same object can cause inconsistency.
You can change private static to private, but your design might be problematic from the outset.
Maybe factory pattern suits you better.
To answer your question
are still the same object?
No they are not.
are Validor objects used in vuname.selfValidate() and
vemail.selfValidate() still the same object?
No, only static data member can be shared whether private or not. Here private static Validator validator = ...is a data member of class ValidComponent whereas private Validator validator = ...is a data member of object and can't share with another object.
Consider a private variable,
private String name;
and its getter/setter which are ofcourse public.
Now every class has access to getter/setter which in its implementation uses private variable. That's the purpose of private variables, not accessing it directly from other classes.
Your case is similar where in private validator is being accessed by selfValidate() method. By their signature, selfValidate() is accessible to subclasses.
To answer your question about whether validator object will be different in case of non-static or not, then every class that accesses it will create a new instance of that object.

Use of a private constructor

I'm a begginer programmer for Android and I found some code over the internet and I couldn't get what this "Class not meant to be instantiated" means?! Also what's the use of it. I would be very happy if somebody could help here.
public class Settings
{
//some code
private Settings() {} // Class not meant to be instantiated
//some code
}
The constructor is private so only the class itself can create instances. There are several reasons for doing this. A couple off the top of my head...
The class is a "utility" class that only contains static methods and so instantiating it would make no sense. As the class is commented "Class not meant to be instantiated" I guess this is the most likely reason.
The class itself controls its own lifecycle and provides methods for creating instances. For example if the class is a lazy singleton it might provide a method that creates an instance when first called and return this instance on subsequent calls.
It is a private constructor. This means that outside classes cannot create new instances using the default constructor.
A little more info
All Objects in Java have a default constructor:
public MyObject() {}
That is how you can have this class:
public class MyObject{}
and still be able to call:
MyObject mObj = new MyObject();
Private Constructors
Sometimes a developer may not want this default constructor to be visible. Adding any other constructor will nullify this constructor. This can either be a declared constructor with empty parameters (with any of the visibility modifiers) or it can be a different constructor all together.
In the case above, it is likely that one of the following models is followed:
The Settings object is instantiated within the Settings class, and is where all the code is run (a common model for Java - where such a class would also contain a static main(String[] args) method).
The Settings object has other, public constructors.
The Settings object is a Singleton, whereby one static instance of the Settings Object is provided to Objects through an accessor method. For example:
public class MyObject {
private static MyObject instance;
private MyObject(){}//overrides the default constructor
public static MyObject sharedMyObject() {
if (instance == null)
instance = new MyObject();//calls the private constructor
return instance;
}
}
This inner construct
private Settings() {}
is a constructor for Settings instances. Since it is private, nobody can access it (outside of the class itself) and therefore no instances can be created.
The constructor is private so its not meant to be called by anything outside of the class
It's not a nested class, it's a constructor. A private constructor means that you can't construct instances of this class from outside, like this:
Settings s = new Settings(); //Compilation error! :(
Now, if a class can't be instantiated, what could it be for? The most likely reason for this is that the class would return instances of itself from a static method, probably as a singleton. The settings are normally global to the program, so a singleton pattern really fits here. So there would be a static method that goes kind of like this
static private TheOnlySettings = null;
static public getSettings()
{
if(TheOnlySettings == null)
TheOnlySettings = new Settings(); //Legal, since it's inside the Settings class
return TheOnlySettings;
}
See if that's indeed the case.
As other have mentioned, a class having private constructors cannot be instantiated from outside the class. A static method can be used in this case.
class Demo
{
private Demo()
{
}
static void createObjects()
{
Demo o = new Demo();
}
}
class Test
{
public static void main (String ...ar)
{
Demo.createObjects();
}
}
We can have private constructor . Below program depicts the use of private constructor with a static function
class PrivateConstructor {
private:
PrivateConstructor(){
cout << "constructor called" << endl;
}
public:
static void display() {
PrivateConstructor();
}
};
int main() {
PrivateConstructor::display();
}

Constructor's Private scope

Given this code snippet, could you explain why it woks?
The thing is that the class constructor is marked private, so should not it prevent us to call it with new operator?
public class Alpha {
protected Alpha() {}
}
class SubAlpha extends Alpha {
private SubAlpha() {System.out.println("ok");}
public static void main(String args[]) {
new SubAlpha();
}
}
It all works because the static method is part of the class and it can see all private fields and methods, right? Outside this "new" initialization would never work?
The only private constructor in your question is SubAlpha, which SubAlpha itself is calling. There's no issue, a class can call its own private methods. The Alpha constructor is protected, so SubAlpha has access to it.
Edit: Re your edit: Yes, exactly. A separate class (whether a subclass or not) would not have access to SubAlpha's private constructor and could not successfully construct a new SubAlpha().
Example 1:
public class Beta
{
public static final void main(String[] args)
{
new SubAlpha();
// ^--- Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error
}
}
Example 2:
public class SubSubAlpha extends SubAlpha
{
private subsubAlpha()
{
// ^== Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error because of the implicit call to super()
}
}
This is, of course, constructor-specific, since scope is always member-specific. If a class has a different constructor with a different signature and a less restrictive scope, then a class using it (including a subclass) can use that other constructor signature. (In the case of a subclass, that would require an explicit call to super(args);.)
The code works as the main method is also in the same class. You may not be able to initialize SubAplha from a different class.

Categories

Resources