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