Suppose there is a class stock
class Stock
{
String id;
String name;
}
I want to create two comparators that compare by id
and name
, respectively.
Are there naming conventions or best practices for comparators in Java?
Are following names okay?
StockByIdComparator
and StockByNameComparator
SortStockById
and SortStockByName
I know that redundant names are avoided in certain areas. One would choose
List<Stock> stocks
over List<Stock> stockList
. Also types should not be encoded in variable names (maybe since the rise of IDEs?). But there is also the important dimension of clearness.
So what is a good aproach for naming comparators?
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
Interface names should be capitalized like class names. Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.
Java Comparator is an interface for sorting Java objects. Invoked by “java. util. comparator,” Java Comparator compares two Java objects in a “compare(Object 01, Object 02)” format. Using configurable methods, Java Comparator can compare objects to return an integer based on a positive, equal or negative comparison.
Personally, I would name them as StockByIdComparator
and StockByNameComparator
.
It may appear a little bit redundant but it is clear as every Java developer knows what a Comparator
is.
I like less SortStockById
and SortStockByName
as
they look like method names : start by a verb and followed by a complement.
I cannot know right know that these are Comparator
implementations.
I don't think that choosing a name coupled with the Comparator
interface be a issue or bad naming strategy.
On the contrary, it is an interface and it makes part of the Java base API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With