Naming Variables
If Coding is an art, then naming variables is the first skill to master. We give a name for everything, everything inside a program from a variable to package and everything outside a program from files to directories. If not named properly then it will make you regret, if not that very day a few days later for sure xD. How to name variables ?
- The name should tell why it exits, what it does, and how it is used.
eg:
int ca =0, cb=0;
to
int countA= 0, countB=0;
- Avoid Disinformation.
eg.
markLists -> roll no in 0th index and marks in 1st index
public int search(List<<int[]> markLists, int rollno){ for(int[] i: markLists){ if (rollno==i[0]){ return i[1]; } } }
to
public int getStudentMarks(List<int[]> rollNoAndMarks, int targetRollNo){ int ROLL_NO_VALUE = 0, MARKS_VALUE; for(int[] student: rollNoAndMarks){ if (targetRollNo == rollNoAndMarks[ROLL_NO_VALUE]){ return student[MARKS_VALUE]; } } }
-
Make Meaningful Distinction eg: getAccount() getAccountInfo() to getAccountNumber() getAccountInfo()
- Use Pronounceable Names
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 recordId = "102"; /* ... */ };
- Use Searchable Names
Variables should be easy to search.
eg: PASSING_MARKS can be easily searched and edited as compared to searching for 35 in a pile of code.
public boolean isPass(int marks){ return marks>=35; }
to
public boolean isPass(int marks){ return marks>=PASSING_MARKS; }
How to name a Class? Classes and objects 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.