Naming convention for instances of java.util.Comparator

mike :

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?

davidxxx :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466957&siteId=1