Naming convention for instances of java.util.Comparator

Viewed 1958

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?

3 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.

StockByIdComparator and StockByNameComparator are ok, since they describe the purpose of these classes. But I would name them like StockComparatorById and StockComparatorByName respectively, so they will have one general prefix. So in future, you will be able to find all StockComparator* easily.

Basically, there is no any best practice for naming Comparators or other interface implementations. The good way is to choose descriptive and not very long name and keep this name "convention" along with all code.

If you create them as a class I would include Comparator there

class StockByIdComparator implements Comparator<Stock> {}

If you want to create it as a variable or constant - you can skip it

static final Comparator<Stock> COMPARE_BY_ID = new Comparator<Stock>() {}

so it would look like this

Collections.sort(stocks, COMPARE_BY_ID);
Related