27 ms·
> Use <T> even if you only use it with strings, the extra cost while creating the class is almost nothing, but the cost of a future refactorization will surely
by usrusr 6y ago
> Use <T> even if you only use it with strings, the extra cost while creating the class is almost nothing, but the cost of a future refactorization will surely be greater.
Allow me to question the "almost" in "almost nothing". Java generics are famously unreified, at runtime it's exactly the same.
I have noticed this habit of what could be called redundant genericity in my own code as well. Sometimes the motivation seems to be hardly more than a coping strategy for the notoriously verbose class names of idiomatic java. But it can also provide self-describing value: at the use site, Bag<String> reads better than BagOfStrings and on the implemention side, class Bag<S> makes it clear that nothing in there will look at e.g. individual characters. Obviously, if you do need to consider individual characters, go with BagOfStrings - or go with class Bag<S extends CharSequence>, which would notify the reader right in the headline that somewhere in the implementing it requires access to the actual text nature of its data.
As a bonus, even if production code only ever fills the angulars with one specific type, chances are that it's a type that is painful in a unit test. If you do esoteric set operations on WhateverFactoryFactories or something like that it's super-convenient if you can just play them through with strings.
- Twisol 6y ago> Allow me to question the "almost" in "almost nothing". Java generics are famously unreified, at runtime it's exactly the same. On the other hand, decaying <T> to Object (rather than monomorphizing as C++ templates do) somewhat reduces the viable attack surface for optimizations. On the gripping hand, Java is traced/JITted, so it should pick up many of these opportunities (and more) anyway.