Item - 4 Enforce Noninstantiablity With a Private Constructor

Berat Yesbek
2 min readAug 15, 2023

--

This writing will discuss item 4 in Effective JAVA, recommended by Joshua Bloch.

As you know, sometimes we must use some util classes for configuration or fundamental business logic; I have often seen developers use utility classes with public constructors. But these classes should not have created an instance outside the class for the excellent and clean architecture context. This idea is because we want to clarify our architecture, some hierarchy, and order. [1] [2]

There is also an advantage about private constructor classes cannot be instantiated; there's no overhead associated with object creation and garbage collection for this class. [1]

Utility classes also improve the code's maintainability by allowing it to group related methods and fields in a single context.

NOTE: util classes should be final to immutable and are not extended from other classes. This help to prevent OOP design and code standards

TemperatureUtils.java

public final class TemperatureUtils {

private TemperatureUtils() {

}

public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32;
}

public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5.0 / 9.0;

}
}

Test.java

public class Test {
public static void main(String[] args) {
double fahrenheit = TemperatureUtils.celsiusToFahrenheit(43);
double celsius = TemperatureUtils.fahrenheitToCelsius(77);
System.out.println("fahrenheit is: " + fahrenheit);
System.out.println("celsius is: " + celsius);

}
}

Conclusion

Use util classes with a private constructor and final keyword. This will potentially enhance performance, maintainability, clarity, and readability. This help to prevent OOP design and code standards. And

References

Bloch, Joshua. Effective Java Programming Third Edition. [1]

Robert C. Martin, Clean Code. [2]

--

--

Berat Yesbek
Berat Yesbek

Responses (1)