Naming convention for java.util.Comparator instances

Suppose there is a class

  class Stock
  {
    String id;
    String name;
  }

I want to create two comparators that are compared by idand name, respectively. Are there naming conventions or best practices for comparators in Java?

Are the following names available?

  • StockByIdComparator and StockByNameComparator
  • SortStockById and SortStockByName

I know that redundant names are excluded in certain areas. One could choose List<Stock> stocksover List<Stock> stockList. Also, types should not be encoded in variable names (possibly since the advent of the IDE?). But there is an important dimension of clarity.

So what's good apraach to mean comparators?

+4
source share
3 answers

StockByIdComparator StockByNameComparator.
, , Java , Comparator.

SortStockById SortStockByName

  • : .

  • , , Comparator.

, Comparator .
, API Java.

+3

,

class StockByIdComparator implements Comparator<Stock> {}

,

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

:

Collections.sort(stocks, COMPARE_BY_ID);
+2

StockByIdComparatorand StockByNameComparatorin order, as they describe the purpose of these classes. But I would call them as StockComparatorByIdand StockComparatorByNameaccordingly, so they will have one common prefix. Therefore, in the future you can easily find everything StockComparator*.

Basically, there is no best practice for naming comparators or other interface implementations. A good way is to choose a descriptive and not very long name and keep this name โ€œagreementโ€ along with all the code.

0
source

Source: https://habr.com/ru/post/1689076/


All Articles