- "The name of a variable/function/class should tell you why it exists, what it does, and how it is used"
- Avoid names that are misleading or false.
- Avoid abbreviations/acronyms that aren't universally known.
- Avoid giving 2 different variables/functions/classes names that sound similar.
- Avoid prefixes/suffixes that are redundant given the context.
- Avoid Hungarian Notation in typed languages like Java.
- Avoid member prefixes like _ or m (in Java at least)
- Be consistent. Pick a name for a specific concept, and then stick to it. Conversely, avoid using the same name for distinct concepts.
Code is much easier/faster to read and understand, especially for new team members, when above guidelines are used.
Any potential bugs are also easier to spot as a result.
Clean Code - chapter 2
Bad: int d; // elapsed Time in Days
Better: int elapsedTimeInDays;
Bad: void copyChars(char[] c1, char[] c2);
Better: void copyChars(char[] source, char[] dest);
Bad: String getDisplay(); // Also changes state
Better: String updateDisplay();
Bad: dpUrl;
Better: detailPageUrl;
Bad:
String name;
String theName;
Better:
String nickname;
String legalName;
Bad:
class Product {
String _productNameString;
int _productCostInteger;
}
Better:
class Product {
String name;
int cost;
}
Bad:
String getName();
int fetchCost();
LocalDate retrieveDate();
Better:
String getName();
int getCost();
LocalDate getDate();
Bad:
List<int[]> getThem() {
List<int[]> list1 = new ArrayList<>();
for (int[] x : theList)
if (x[0] == 4)
list1.add(x);
return list1;
}
Better:
List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<>();
for (Cell cell : gameBoard) {
if (cell.isFlagged()) { flaggedCells.add(cell); }
}
return flaggedCells;
}
Too much verbosity hurts readability as well. Strike a balance between ambiguity and verbosity. The smaller the scope of a variable, the more concise its name can be.
See other recommended best practices here.