Best Practices for extending utility classes in java

3.7k Views Asked by At

I've extended classes from apache-commons-3 to add my own utility functions which are unavailable in them. e.g.:

public class CollectionUtils extends org.apache.commons.collections.CollectionUtils
{
        /**
     * Similar to collection.contains(member) except just doesn't throw NPE when set is null, simply returns false
     * @param collection
     * @param member
     * @return
     */
    public static <K> boolean contains(Collection<K> collection,K member)
    {
        return collection!=null && collection.contains(member);
    }
}

This solved my purpose of using my functions & commons functions through same class CollectionUtils.

But, Apache has removed extendibility in version 4 by introducing private constructors in the utility classes. There is also a discussion on the same here.

Now, my code is breaking if I upgrade to version 4. What are the best practices to extend utility classes to add custom/specific utility methods?

1

There are 1 best solutions below

1
On

Although I voted close as "opinion based" I wanted to give you some input.

As it is already said in your linked discussion, extending utility classes is a bad practice in the first place. The change in the version 4 probably aims at that convention.

Extending utility classes (with static methods only) makes no sense, since you can't overwrite static methods anyway. You can, however, hide them. This means that this might happen accedentally with unintended behaviour. So it has a risk with no real value. It doesn't really make your code more complicated if you just use two utility classes. There even is a compiler warning for not accessing static methods directly.

What are the best practices to extend utility classes to add custom/specific utility methods?

To summarize: The best practice is not to extend them but to use a second custom utility class.