Naming Conventions
We say code should be expressive, and easy to understand so that the code itself expresses its purpose. Source code or program is a combination of variables, functions, classes, Interfaces, expressions, loops, conditions, etc. and the first and foremost thing in a programming language is naming them. Programmers should follow a proper naming convention for variables, methods or functions, classes, interfaces, and file names.
Use Intention-Revealing Names
The variable names should reveal their intent or purpose. The following is a bad style of naming variables.
//bad variable name
int d; // elapsed time in days
double ar; // area of the square
Instead, use complete word or group of words using various industry standards like camelCase, Pascal case, snake case etc
// good code
int elapsedTimeInDays; // Camel case
int RateOfInterest; //pascal case
int start_time, end_time; // snake case
We know writing expressive names is more prone to errors, but once you write it properly with help of IDE, it will help to understand the intent of the variable names easily.
Choosing expressive/good names takes time but saves more than it takes.
Choosing names that reveal intent can make it much easier to understand and change code later.
Look at the following code. What is the purpose of this code?
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList) {
if (x[0] == 4)
list1.add(x);
}
return list1;
}
Why is it hard to tell what this code is doing?
There are no complex expressions. Spacing and indentation are reasonable. There are only three variables and two constants mentioned. There aren’t even any fancy classes or polymorphic methods, just a list of arrays (or so it seems).
The problem isn’t the simplicity of the code but the simplicity of the code to the degree to which the context is not explicit in the code itself. The code implicitly requires that we know the answers to questions such as:
1. What kinds of things are in theList?
2. What is the significance of the zeroth subscript of an item in theList?
3. What is the significance of the value 4?
4. How would I use the list being returned?
The answers to these questions are not present in the code sample, but they could have been. Say that we’re working in a mine sweeper game. We find that the board is a list of cells called theList. Let’s rename that to gameBoard. Each cell on the board is represented by a simple array. We further find that the zeroth subscript is the location of a status value and that a status value of 4 means “flagged.” Just by giving these concepts names, we can improve the code considerably:
public List<int[ ]> getFlaggedCells() {
List<int[ ]> flaggedCells = new ArrayList<int[ ]>();
for (int[ ] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED)
flaggedCells.add(cell);
return flaggedCells;
}
Notice that the simplicity of the code has not changed. It still has the same number of operators and constants, with the same number of nesting levels. But the code has become much more explicit.
Another example
public class ArrayExample {
public static void main(String[] args) {
int arr[]= new int[10];
for(int i=0;i<10;i++)
{ int k= i+1;
arr[i]=arr[i]+(k*k);
}
System.out.println("Output");
for(int x : arr) {
System.out.println(x);
}
}
The above code is simple and works fine. But it does not have information about the integer array. What is the intent of declaring this array? What are we storing in this array?
If refactored using proper naming convention, then looks like this
public class SquareExample {
public static void main(String[] args) {
int squares[]= new int[10];
for(int i=0;i<10;i++)
{ int naturalNumber= i+1;
squares[i]=squares[i]+(naturalNumber*naturalNumber);
}
System.out.println("Output");
for(int number : squares)
System.out.println(number);
}
}
Notice that the array named squares represents an array of squares, naturalNumber represents the natural number.
Avoid Disinformation
Programmers must avoid leaving wrong clues about the meaning of the code. For example, hp, hpux, sco. Avoid using such names.
A truly awful example of disinformative names would be the use of lowercase L- l or uppercase O as variable names, especially in combination. The problem, of course, is that they look almost entirely like the constants one and zero, respectively.
int a = l;
if ( O == l ) a = O1;
else l = 01;
So avoid variable names like O, l, O1, l1, etc
Do not refer to a grouping of accounts as an accountList unless it’s a List. The word list means something specific to programmers. If the container holding the accounts is not a List, it may lead to false conclusions.1 So accountGroup or bunchOfAccounts or just plain accounts would be better.
Make Meaningful Distinctions
Number-series naming (a1, a2, .. aN) is the opposite of intentional naming. Such names are not disinformative—they are noninformative; they provide no clue to the author’s intention.
Consider:
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
}
This function reads much better when source and destination are used for the argument names.
public static void copyChars(char source[], char destination[]) {
for (int i = 0; i < source.length; i++) {
destination[i] = source[i];
}
}
Noise words are another meaningless distinction. Imagine that you have a Product class. If you have another called ProductInfo or ProductData, you have made the names different without making them mean anything different. Info and Data are indistinct noise words like a, an, and the.
Use Pronounceable Names
Programmers should use pronounceable names that make it easy to read out and discuss for further development.
Example Java code:
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* ... */
};
to
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String seatNo = "1AB22ML102";
/* ... */
};
Class Names
Classes should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class. A class name should not be a verb.
Method Names
Methods should have verb or verb phrase names like postPayment, deletePage, or printBalance. Accessors, mutators, and predicates should be named for their value and prefixed with get, set.
string name = employee.getName();
customer.setName("mike");
if (paycheck.isPosted())...
Use domain names from the context of the Problem statement
Code should have names of the variable, method, class and interface related to domain of the problem statement. Example, variables named firstName,lastName, street, houseNumber, city, state, and zipcode all represent address.
Summary - Best practices to name variables, methods and class:
- Use proper Names with intent.
- Prefer descriptive names over short form
- Avoid Similar Names
- Prefer a shorter name over a longer one if it reveals intent clearly.
- Follow Coding Convention
- Use Consistent Naming, Avoid Synonyms
- The class name should be a noun
- Avoid clutters like _l, m_, o_,O1, Ol, lO, etc
- Avoid using non-ASCII characters and words from the local language
- Make good use of common verbs e.g. is, has, can, or do
Multiple choice questions
1. Programmers employ numerous tactics to ensure readable and organized code. These include:
a) using naming conventions for variables;
b) placing whitespaces, indentations and tabs within code;
c) adding comments throughout to aid in interpretation.
Select the above statements which are correct
- a, b
- b,c
- c, a
- a,b,c
Answer: 4
2. Can programmers use multiword naming conventions?
a) Yes
b) No
Answer: a
3. Snakecase is
a) Words delimited by an underscore.
b) Words delimited by a Capital letter.
c) Words are delimited by capital letters, except the initial word.
d) None of the above
Answer: a
4. Pascalcase is
a) Words delimited by an underscore.
b) Words delimited by a Capital letter.
c) Words are delimited by capital letters, except the initial word.
d) None of the above
Answer: b
5. CamelcaseSnakecase
a) Words delimited by an underscore.
b) Words delimited by a Capital letter.
c) Words are delimited by capital letters, except the initial word.
d) None of the above
Answer: 3
References
- https://betterprogramming.pub/clean-code-naming-b90740cbae12
- https://javarevisited.blogspot.com/2014/10/10-java-best-practices-to-name-variables-methods-classes-packages.html#ixzz7cK8MNUjz
- https://www.freecodecamp.org/news/clean-coding-for-beginners/
- https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29