Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming convention for instances of java.util.Comparator

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?

like image 399
mike Avatar asked Nov 10 '17 15:11

mike


People also ask

What is the naming convention for instance variables in Java?

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.

Which is the correct naming convention for Java method?

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.

What is Java Util Comparator?

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.


1 Answers

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.

like image 103
davidxxx Avatar answered Oct 27 '22 01:10

davidxxx