Video in progress
How do you correctly write a utility class made up only of static methods?
I make the class final and add a private constructor, so you can neither create an object from it nor extend it. Making it abstract is the wrong way: it looks like an invitation to extend it and doesn't fully block creating objects.
📖 Answer
public final class PhoneNumbers {
private PhoneNumbers() {
throw new AssertionError("Obyekt yaratilmaydi");
}
public static String normalize(String raw) {
return raw.replaceAll("[^0-9+]", "");
}
}
If you don't write a constructor, the compiler adds a public default constructor, and someone will do new PhoneNumbers(). A private constructor stops that, and the AssertionError inside covers the case where it is called through reflection.
What if you make it abstract? Then someone can write a child class and create an object from it, so the goal is not achieved.
Think about one thing: a utility class is often a dumping ground for methods that "found no home". If a method works with a single object (OrderUtils.total(order)), it may belong to that class as order.total(). A real utility is made of stateless, general helpers that don't depend on the domain: formatting, parsing, math.
In Lombok, @UtilityClass does this automatically, but it is known to cause problems with static imports, so many teams prefer writing it by hand.
Sign up to mark studied questions and save your progress.