3. Preface.
ï± The contents in this presentation are prepared for
educational purpose. Presentation is prepared by
using the following books; Some of the statements
are directly taken from the sources..
1. Clean Code A Handbook of Agile Software
Craftsmanship
2. Code Complete 2nd edition 2004
3. Refactoring-Improving the Design of Existing Code
4. Before we Start
ï± One difference between a smart programmer and a
professional programmer is that the professional
understands that clarity is king. Professionals use
their powers for good and write code that others can
understand.
Itâs not enough to write the code well. The code has to
be kept clean over time. If we all checked-in our code a
little cleaner than when we checked it out, the code
simply could not rot. The cleanup doesnât have to be
something big. Change one variable name for the
better, break up one function thatâs a little too large,.
5. Meaningful Names
ï± The name Should Tell Why It Exists, What it does..It should fully and accurately
describe the entity the variable represents.
ï± An effective technique for coming up with a good name is to state in words
what the variable represents
numberOfPeopleOnTheUsOlympicTeam; numberOfSeatsInTheStadium.
ï± If a name requires a comment; change the name
int days =3; //elapsed time in days..
should be ï int elapsedTimeInDays = 3;
public List<int[]> getThem()
{
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList)
if (x[0] == 4)
list1.add(x);
return list1;
}
WHAT DOES THÄ°S FUNCTION DO?? !!!!!!!!!!!!
6. Meaningful Names
ï± It seems easy (code size is small; indentation OK; no complex behaviour)
Then what??? THE CODE DOES NOT TELL EXACTLY ITSELF!!!
1. What kinds of things are in the List?
2. What is the significance of the zeroth subscript of an item in the List?
3. What is the significance of the value 4?
4. How would I use the list being returned?
//BETTER CODE mine sweeper game Cell is int[]
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
Means âflagged.â
public List<int[]> getFlaggedCells() {
List<int[]> flaggedCells = new ArrayList<int[]>();
for (int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED)
flaggedCells.add(cell);
return flaggedCells;
}
7. Meaningful Names
ï± An example from our CORE bankıng Code
i.e: checkCustomerData(MustriPOMData customerPOMData)
We can not understand what this method does unless we read the internals of the
code!!!!!
WRONG NAMING!!!! ;
8. Meaningful Names
ï± Avoid False Informations In Names
i.e : Do not refer to a accunt set as an accountList unless itâs actually a JAVA
List. Better names may be accountGroup or just accounts.
ï± Using Names which vary In small ways
i.e : We did this when renaming Database Tables for Campaign Mang. System
Java Code Completion; name variables/constants with smilar functionalities but small
differences; write a part of the variable; type CTRL + SPACE and choose appropriate
One (campaignChannel_ATM; campaignChannel_Internet)
ï± Make Meaningful Distinctions
i.e: If class variable is used inthe same procedure do not use Clazz; IF NAME
should be different ; then they should ALSO MEAN DIFFERENT!!!
i.e: String customer=ââ; when we want to use another customer do not name
it as Customer1 ; Instead name it as ReceiverCustomer for example;
9. Meaningful Names
ï± Number-series naming (a1, a2, .. aN) is the
opposite of intentional naming. Such names are
noninformative;
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
} //If you do not read the internals of the Code; you can not understand the
Source and Destination from the method signiture!!! Use SOURCE and
DESTINATION INSTEAD!!!!
ï± Do not use Noise Words;
i.e, creating ProductInfo and ProductData classes may mean the same to the
developer; then which one will the coder prefer without investigating the code??
INFO and DATA ar noise words like âaâ,âanâ.. Another example is creating
10. Meaningful Names
ï± DISTINCTION in NAMES
ProductInfo and ProductData classes; who knows what the difference is?? Info and
Data are similiar words which does not make any distinction..
Customer , CustomerObject What is the distinction??!! Likewise
customer, customerInfo; account, accountData
11. Meaningful Names
ï± In our Core Banking System; there are customer Services Named as;
getCustomerInfo();
getCustomerDetails();
getAllCustomerInfo();
getCustomerDataFast();
which one will the developer prefer to use?
Distinguish names in such a way that the reader know what the differences offer.
12. Meaningful Names
ï± If the type of the name is apperant, do not use it in
the variable name.
i.e: when we see a variable named as customerName ; almost everyone knows that
its type is String ; the do not use a variable customerNameString or
customerNameStr
Ex : moneyAmount and money varibles in the same method
13. Meaningful Names
ï± Use PRONOUNCABLE Names
i.e: class DtaRcrd102 {
private Date genymdhms; // generation
date, year, month, day, hour, //minute,and second (you can not
read this)
private Date modymdhms;
private final String pszqint = "102";
};
THE CORRECT ONE is,
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;;
private final String recordId = "102";
}; I
Intelligent conversation is now possible: âHey, Mikey, take a look at this record!
The generation timestamp is set to tomorrowâs date! How can that be?â
14. Meaningful Names
ï± Use SEARCHABLE Names
ex: if(customerType.equals(âGâ)){}
if(customerType.equals(CUSTOMERTYPE_RETAIL)){} //SEARCHABLE
EX: Using a variable named âxâ is not searchable; because most of the words in
the code may contain x..!!!!!!!!!!!!!!!!
for (int j=0; j<34; j++) {
s += (t[j]*4)/5;
} CONVERTED AS
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j=0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realTaskDays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;,
15. Meaningful Names
ï± Avoid Mental Mapping
Readers shouldnât have to mentally translate your names into other names they
already know. Do not show off by changing the name of some well-known variables(in
very small methods containg simple short loops, we may use i,j,k BUT NOT âHâ )
Do not use the variable ârâ instead od âurlâ
One difference between a smart programmer and a professional programmer is
that the professional understands that CLARÄ°TY Ä°S KÄ°NG.
Professionals use their powers for good and write code that others can
understand.
16. Meaningful Names
ï± Problem Orientation
A good mnemonic name generally speaks to the problem rather than the solution.
A good name tends to express the what more than the how. In general, if a name
refers to some aspect of computing rather than to the problem, it's a how rather than
a what. Avoid such a name in favor of a name that refers to the problem itself.
Ex: inputRec ï employeeData. (inputRec is a computer term ; use names from
problem domain employeeData is better )
To indicate printer status ; bitFlagï printerReady
17. Meaningful Names
ï± Use Each Variable For Only One Purpose
the variable temp is used for more than one purpose!!!
BAD CODE BETTER CODE
18. Meaningful Names
ï± Do Not PUN!!
Avoid using the same word for two purposes. Using the same term for two
different ideas is essentially a pun.
If you follow the âone word per conceptâ rule, you could end up with many classes
that have, for example, an add method. As long as the parameter lists and return
values of the various add methods are semantically equivalent, all is well.
Letâs say we have many classes where add will create a new value by adding or
concatenating two existing values. Now letâs say we are writing a new class that
has a method that puts its single parameter into a collection. Should we call
this method add? It might seem consistent because we have so many other add
methods,but in this case, the semantics are different, so we should use a name like
insert or append instead. To call the new method add would be a pun.
19. Meaningful Names
ï± Add Meaningful Context
Prefer placing variables in well-named classes, funtions or namespaces. When all
these fails, prefixing the name saccording to the context is better than doing
nothing..
20. Meaningful Names
ï± Add Meaningful Context
Prefer placing variables in well-named classes, funtions or namespaces. When all
these fails, prefixing the name saccording to the context is better than doing
nothing..
Imagine that you have variables named
firstName, lastName, street, houseNumber, city,state, and zipcode. Taken
together itâs pretty clear that they form an address. But what if you just saw the
state variable being used alone in a method? Would you automatically infer that it
was part of an address?
You can add context by using prefixes:
addrFirstName, addrLastName, addrState, and so on. At least readers will
understand that these variables are part of a larger structure. Of course, a better
solution is to create a class named Address. Then, even the compiler knows that
the variables belong to a bigger concept.
23. Meaningful Names
ï± Add Meaningful Context
private void thereAreManyLetters(int count) {
number = Integer.toString(count);
verb = "are";
pluralModifier = "s";
}
private void thereIsOneLetter() {
number = "1";
verb = "is";
pluralModifier = "";
}
private void thereAreNoLetters() {
number = "no";
verb = "are";
pluralModifier = " s«;
}
} // end of class
24. Meaningful Names
ï± Optimum Variable Length
ï Sould Not be Too Long (maximumNumberOfPointsInModernOlympics.) or too
Short(like x,x1)
ï Long Names are hard to type; too short names are not descritive enough..
ï Programs with names averaging 8 to 20 characters were almost as easy
to debug.
ï The guideline doesnât mean that you should try to make all of yourvariable names 9
to 15 or 10 to 16 characters long. It does mean that if you look over your code and
see many names that are shorter, you should check to be sure that the names are as
clear as they need to be.
Too long: numberOfPeopleOnTheUsOlympicTeam ; numberOfSeatsInTheStadium
maximumNumberOfPointsInModernOlympics
Too short: n, np, ntmn, ns, nsisd m, mp, max, points
Just right: numTeamMembers, teamMemberCount
25. Meaningful Names
ï± Computed Value Qualifiers
ï most Significant part of the varibale name, the part that give it most of its
meaning is at the front.
ï Use computed value qualifiers like Max, Total, Average, Pointer at the end⊠Like
salaryAverage, expenseAverageâŠ
ï Do not use mixed.. Some at the beginning ; some at the end..Be consistent!!!
ï EXCEPTIONS: Num qualifier.. When placed at the beginning it means total like
numSales. When placed at the end; it refers to an index. Like saleNum. To keep
away from the confusion use Index and Count keywords when necessary.
revenueTotal; expenseTotal, revenueAverage
26. Meaningful Names
ï± Common Opposites In Variable Names
ï increases the readability.. Easy to Understand..
begin/end
first/last
locked/unlocked
min/max
next/previous
old/new
source/target
visible/invisible
27. Meaningful Names
ï± Naming Loop Indexes
ï The names i,j,k are OK⊠they are very common⊠But what if you use z,m???
ï But if you do something very specific choose a better variable Name..
For example, if you are reading records from a file and need to remember how many records youâve read, a
more meaningful name like recordCount would be appropriate
ï If loop is very long, we may forget what i,j,k stands for. Choose better
descriptive variable names.. Especially in nested loops, if we use i,j,k
together, we may get Confused.
for ( teamIndex = 0; teamIndex < teamCount; teamIndex++ ) {
for ( eventIndex = 0; eventIndex < eventCount[ teamIndex ]; eventIndex++ ) {
score[ teamIndex ][ eventIndex ] = 0;
}
}
ï
28. Meaningful Names
ï± Naming Status Variables
ï Think of a better name than flag for status variables (What is it used for? No clue!!)
ï For clarity, flags should be assigned values and their values should be tested with
enumerated types, named constants.
ï DO NOT USE flag in the name
BAD NAMING
if ( statusFlag & 0x0F ) ...
if ( printFlag == 16 ) ...
if ( computeFlag == 0 ) ...
statusFlag = 0x80; // NO CLUE WHAT THIS CONSTANT ISâŠ
BETTER NAMING
if ( dataReady ) ...
if ( characterType & PRINTABLE_CHAR ) ...
if ( reportType == ReportType_Annual ) ...
if ( recalcNeeded == True ) ...
reportType = ReportType_Annual; // BETTER NAMING
29. Meaningful Names
ï± Naming Temporary Variables
ï DO NOT USE temp, x, or some other nondescriptive name.
ï Calling a few of them temporary may indicate that you arenât sure of their real
purposes.
AX^2 + BX+ C=0 ;
Bad Naming
temp = sqrt( b^2 - 4*a*c );
root[0] = ( -b + temp ) / ( 2 * a );
root[1] = ( -b - temp ) / ( 2 * a );
Good Naming
discriminant = sqrt( b^2 - 4*a*c );
root[0] = ( -b + discriminant ) / ( 2 * a );
root[1] = ( -b - discriminant ) / ( 2 * a );
30. Meaningful Names
ï± Naming Boolean Variables
ï Use well-known typical boolean Names like done; error; found;success;
processingComplete;
ï When you read the Code, if the variable is boolean you should be able to guess it
by looking at its name; found, error etc are good names due to this..
ï You may put is, has in front of some words to make it boolean( A drawback is that
it makes simple logical expressions less readable: if ( isFound ) is slightly less
readable than if ( found ) )
ï Do not use NEGATIVE VARIABLE NAMES.. HARD TO READ!!!!
Bad Naming
status (is it really boolean ? Or may it be an enumarted type??)..
notFound; think of if(! notFound) //means found but hard to read
sourceFile
Good Naming
error; statusOK
found
sourceFileFound , sourceFileAvailable
31. Meaningful Names
ï± Naming Enumerated Types
ï itâs clear that members of the type all belong to the same group by using a group
prefix
Vb syntax
Public Enum Color
Color_Red
Color_Green
Color_Blue
End Enum
Public Enum Planet
Planet_Earth
Planet_Mars
Planet_Venus
End Enum
ï Planet.Earth is better !!
32. Meaningful Names
ï± Naming Constants
ï Name the abstract entity which the constant represents rather than the number
the constant refers to.
ï ALL_CAPS seperated by underscores
Bad Naming
FIVE( what does the constant FIVE is used for? Is it the number of workdays in a week or what???)..
Good Naming
CYCLES_NEEDED
33. Meaningful Names
ï± Kinds Of Names To Avoid
ï Misleading Name or Abbrevations
Using a variable nmed FALSE for Fuel Action Low Sequence Enzyme
ï Names with Similar Meanings
Using fileIndex and fileNumber in the same place is a bad Idea.
ï Different meanings but Similar Names
clientRecs(client Records) and clientReps(client Reports)
ï Similar-Sounding Names
Do not use wrap, rap
ï Numerals In Name
AVOID USING file1,file2 or total1 total2; give better names to differantiate them.
34. Meaningful Names
ï± Kinds Of Names To Avoid
ï Names that are easily Misspelled
Using highlight, hilite , hilight?
ï Do not Differentiate only by Letter Capitalization
Do not use frd for fired, FRD for final review duty,
ï Avoid Using KeyWord Names
Do not use rownum as Column Name in SQL or do not use a variable named if
ï Unrelated Names
Using a variable named FALSE for Fuel Action Low Sequence Enzyme
35. Meaningful Names
ï± CLASS NAMES
ï Class names are in mixed upper and lower case with an initial capital letter
ï Classes and objects should have noun or noun phrase names like
Customer, WikiPage,Account, and AddressParserâŠ.
ï A class name should not be a verb.
36. Meaningful Names
ï± METHOD NAMES
1) The method names contains verbs..
2) Accessors ï get mutatorsï set predicatesï is
3) Overloaded Constuctors as static Factory Methods; Hide default Constructors by
making them private.
string name = employee.getName();
customer.setName("mike");
if (paycheck.isPosted())...
37. Meaningful Names
ï± Java Naming Conventions
âą i and j are integer indexes.
âą Constants are in ALL_CAPS separated by underscores.
âą Class and interface names capitalize the first letter of each word, including the
first wordâfor example, ClassOrInterfaceName.
âą Variable and method names use lowercase for the first word, with the first letter
of each following word capitalizedâfor example, variableOrRoutineName.
âą The underscore is not used as a separator within names except for names in all
caps.
âą The get and set prefixes are used for accessor methods.
42. Meaningful Names
ï± EXAMPLES â 3
What does controlCustomerTypeNationality(customerOid) do???
You canât understand what it does unless You investigate the internals of the code!!!
43. References
1. Clean Code A Handbook of Agile Software
Craftsmanship
2. Code Complete 2nd edition 2004
3. Working Effectively with Legacy Code