开发者

How can I extend a static final guava utilities class?

When I've used common-collections I've done custom extensions to those utils like:

class MyCollectionUtils extends CollectionsUtils {
static myutilityMethod()
static removeDublicate(..)
static myPredicate(...)
}

In that case I have all functionality from CollectionsUtils and my extension methods with only one import!

In guava all static utilities classes 开发者_如何学运维are final.

What is the best approach to extend the guava collection API? For example, new common used predicate, collection factory etc, collection combiner.


For one why answer, readability. The reader now needs to know all about your utility class, even for methods which just forward to Guava.

ArrayList<String> myStrings = MySpecialLists.newArrayList();

Is that a standard ArrayList or a special list I've initialized with default values? Even if I know Guava inside and out, I can't know the answer until I've examined your API. And client code can't guarantee that it will remain the simple Guava version (perhaps you'll stop inheriting from Guava, and just implement all the list methods yourself).


Since all of the methods are static, extending the utility class doesn't really offer any value other than the ability to get everything with one import.

It would seem easiest to me just to create your own utility class that doesn't extend the Guava one and just import the guava one when you need it (with an extra import statement). Having multiple import statements isn't bad; with any competent IDE you hardly even have to manage them yourself.

If you really want to, the utility class that you write could wrap the guava methods, but that would just create more in the way of maintenance, since you'd have to update your methods when the guava ones change.


We designed these static utility classes specifically to prevent them from being extended.

For starters, you couldn't extend the static utility classes even if they weren't final, because they don't expose constructors. (You'd get a compiler error that the default constructor couldn't be used.)

Imports are cheap. Go ahead and use two.


I don't think you should use inheritance in your example about static utilities anyway. Extending classes should be reserved for when you actually need to model some type of parent-child relationship. The number of imports is not a good enough reason to abandon good style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜