SlideShare a Scribd company logo
1 of 43
Naming Standards
  CLEAN CODE



                  Belgi Özen,
 CRM & Customer Dept., IBTECH
                   Updated on 3rd Oct. 2012
Contents
1. Preface
2. Meaningful Names
3. References
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
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,.
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?? !!!!!!!!!!!!
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;
}
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!!!! ;
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;
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
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
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.
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
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?”
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;,
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.
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
Meaningful Names
 Use Each Variable For Only One Purpose
  the variable temp is used for more than one purpose!!!
                 BAD CODE                            BETTER CODE
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.
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..
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.
Meaningful Names
 Add Meaningful Context
private void printGuessStatistics(char candidate, int count) {
    String number, verb, pluralModifier;
    if (count == 0) {
        number = "no";
        verb = "are";
        pluralModifier = "s";
    } else if (count == 1) {
        number = "1";
        verb = "is";
        pluralModifier = "";
    } else {
        number = Integer.toString(count);
        verb = "are";
        pluralModifier = "s";
    }
    String guessMessage = String.format("There %s %s %s%s", verb, number, candidate, pluralModifier);
    print(guessMessage);
}
Meaningful Names
 Add Meaningful Context
public class GuessStatisticsMessage {
private String number;
private String verb;
private String pluralModifier;


public String make(char candidate, int count) {
      createPluralDependentMessageParts(count);
      return String.format("There %s %s %s%s",verb, number, candidate, pluralModifier );
}
private void createPluralDependentMessageParts(int count) {
      if (count == 0) {
           thereAreNoLetters();
      } else if (count == 1) {
           thereIsOneLetter();
      } else {
           thereAreManyLetters(count);
       }
}
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
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
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
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
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;
            }
}



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
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 );
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
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 !!
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
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.
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
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.
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())...
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.
Meaningful Names
 SAMPLE NAMING CONVENTION for JAVA
Meaningful Names
 EXAMPLES - 1
private static boolean isWeeklyAndMontlyonSameDay(CBDate today){
     if( today.getLastDayOfMonth().compareTo(today) == today.getDayOfWeek() - Calendar.SATURDAY )
            return true;
     return false;

}
private static boolean isWeeklyAndMontlyonSameDay(CBDate today){
     final int numberOfDaysInWeek = 7;
     boolean isCurDateLastDayOfWeek = today.getDayOfWeek() == numberOfDaysInWeek ? true: false;


      CBDate lastDayOfMonth = today.getLastDayOfMonth();
      boolean isCurDateLastDayOfMonth = lastDayOfMonth.compareTo(today) == 0 ? true: false;


       if( isCurDateLastDayOfWeek && isCurDateLastDayOfMonth)
          return true;
       else
          return false;
}
Meaningful Names
 EXAMPLES – 2
private static String getPeriodParameter (CBDate today)
{
    if( today.getLastDayOfMonth().compareTo(today)== 0 )
           return PacketConstants.PeriodType.MONTHLY_INFORMATION.periodCode();
    else
        return PacketConstants.PeriodType.WEEKLY_INFORMATION.periodCode();
}


Which parameter???? --> Should be getPeriodCode(CBDate today)
Meaningful Names
 EXAMPLES – 3
protected Result validateAdd(CBBag ruleBag) throws CBException{
        String taxNumber = ruleBag.get(TAXNUMBER).toString();
        long customerOID = ruleBag.get(CUSTOMEROID).toSimpleLong();
// taxNumber CheckDigit Control
   try {
        if (controlCustomerTypeNationality(customerOID, taxNumber)) {
             CBBag taxNumberBag = CBBagFactory.createBag();
             taxNumberBag.put(VERGINO, taxNumber);
             taxNumberBag.put(OPERATIONTYPE, 1);
             taxNumberBag = CBCaller.call("VERGI_CHECKDIGITKONTROLET", taxNumberBag);
        }
   } catch (Exception e) {
            return
Result.createErrorResult(ResultType.resultType_FAILURE,            CustomerExceptions.VERGINO_HATALI,
null);
   }
………….
Meaningful Names
 EXAMPLES – 3
What does controlCustomerTypeNationality(customerOid) do???
You can’t understand what it does unless You investigate the internals of the code!!!
References
1. Clean Code A Handbook of Agile Software
   Craftsmanship
2. Code Complete 2nd edition 2004
3. Working Effectively with Legacy Code

More Related Content

What's hot (20)

Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Clean code
Clean code Clean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Clean code
Clean codeClean code
Clean code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
Clean code
Clean codeClean code
Clean code
 
JavaScript Variables
JavaScript VariablesJavaScript Variables
JavaScript Variables
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 

Viewers also liked

Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesEdorian
 
깨끗한 코드 (클린 코드, Clean Code)
깨끗한 코드 (클린 코드, Clean Code)깨끗한 코드 (클린 코드, Clean Code)
깨끗한 코드 (클린 코드, Clean Code)Jay Park
 
Clean code chapter1
Clean code chapter1Clean code chapter1
Clean code chapter1ukjinkwoun
 
How to name things: the hardest problem in programming
How to name things: the hardest problem in programmingHow to name things: the hardest problem in programming
How to name things: the hardest problem in programmingPeter Hilton
 
Clean code - Mantenha seu código limpo
Clean code - Mantenha seu código limpoClean code - Mantenha seu código limpo
Clean code - Mantenha seu código limpoTiago Bencardino
 
네이밍 관련 이것저것
네이밍 관련 이것저것네이밍 관련 이것저것
네이밍 관련 이것저것EG Lim
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)Rodrigo Kono
 
Python 오픈소스의 네이밍 특징들-파이콘격월세미나
Python 오픈소스의 네이밍 특징들-파이콘격월세미나Python 오픈소스의 네이밍 특징들-파이콘격월세미나
Python 오픈소스의 네이밍 특징들-파이콘격월세미나choi kyumin
 
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPTBài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPTMasterCode.vn
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Viewers also liked (11)

Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
깨끗한 코드 (클린 코드, Clean Code)
깨끗한 코드 (클린 코드, Clean Code)깨끗한 코드 (클린 코드, Clean Code)
깨끗한 코드 (클린 코드, Clean Code)
 
Clean code chapter1
Clean code chapter1Clean code chapter1
Clean code chapter1
 
How to name things: the hardest problem in programming
How to name things: the hardest problem in programmingHow to name things: the hardest problem in programming
How to name things: the hardest problem in programming
 
Clean code - Mantenha seu código limpo
Clean code - Mantenha seu código limpoClean code - Mantenha seu código limpo
Clean code - Mantenha seu código limpo
 
네이밍 관련 이것저것
네이밍 관련 이것저것네이밍 관련 이것저것
네이밍 관련 이것저것
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)
 
Python 오픈소스의 네이밍 특징들-파이콘격월세미나
Python 오픈소스의 네이밍 특징들-파이콘격월세미나Python 오픈소스의 네이밍 특징들-파이콘격월세미나
Python 오픈소스의 네이밍 특징들-파이콘격월세미나
 
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPTBài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to Naming Standards, Clean Code

Clean code lecture part I
Clean code lecture part IClean code lecture part I
Clean code lecture part IJun Shimizu
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practicesmh_azad
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
ADBMS ASSIGNMENT
ADBMS ASSIGNMENTADBMS ASSIGNMENT
ADBMS ASSIGNMENTLori Moore
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3Mohamed Ahmed
 
Standard coding practices
Standard coding practicesStandard coding practices
Standard coding practicesAnilkumar Patil
 
N E T Coding Best Practices
N E T  Coding  Best  PracticesN E T  Coding  Best  Practices
N E T Coding Best PracticesAbhishek Desai
 
tan-how-article-top-36-csharp-interview-questions-explanation.pdf
tan-how-article-top-36-csharp-interview-questions-explanation.pdftan-how-article-top-36-csharp-interview-questions-explanation.pdf
tan-how-article-top-36-csharp-interview-questions-explanation.pdfarifulislam946965
 

Similar to Naming Standards, Clean Code (20)

Clean code lecture part I
Clean code lecture part IClean code lecture part I
Clean code lecture part I
 
Naming Conventions
Naming ConventionsNaming Conventions
Naming Conventions
 
What's in a name
What's in a nameWhat's in a name
What's in a name
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Clean code
Clean codeClean code
Clean code
 
Coding standard
Coding standardCoding standard
Coding standard
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Clean Code
Clean CodeClean Code
Clean Code
 
Lecture No 13.ppt
Lecture No 13.pptLecture No 13.ppt
Lecture No 13.ppt
 
ADBMS ASSIGNMENT
ADBMS ASSIGNMENTADBMS ASSIGNMENT
ADBMS ASSIGNMENT
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
Simple Design
Simple DesignSimple Design
Simple Design
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
Standard coding practices
Standard coding practicesStandard coding practices
Standard coding practices
 
N E T Coding Best Practices
N E T  Coding  Best  PracticesN E T  Coding  Best  Practices
N E T Coding Best Practices
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
tan-how-article-top-36-csharp-interview-questions-explanation.pdf
tan-how-article-top-36-csharp-interview-questions-explanation.pdftan-how-article-top-36-csharp-interview-questions-explanation.pdf
tan-how-article-top-36-csharp-interview-questions-explanation.pdf
 
Refactoring
RefactoringRefactoring
Refactoring
 

Naming Standards, Clean Code

  • 1. Naming Standards CLEAN CODE Belgi Özen, CRM & Customer Dept., IBTECH Updated on 3rd Oct. 2012
  • 2. Contents 1. Preface 2. Meaningful Names 3. References
  • 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.
  • 21. Meaningful Names  Add Meaningful Context private void printGuessStatistics(char candidate, int count) { String number, verb, pluralModifier; if (count == 0) { number = "no"; verb = "are"; pluralModifier = "s"; } else if (count == 1) { number = "1"; verb = "is"; pluralModifier = ""; } else { number = Integer.toString(count); verb = "are"; pluralModifier = "s"; } String guessMessage = String.format("There %s %s %s%s", verb, number, candidate, pluralModifier); print(guessMessage); }
  • 22. Meaningful Names  Add Meaningful Context public class GuessStatisticsMessage { private String number; private String verb; private String pluralModifier; public String make(char candidate, int count) { createPluralDependentMessageParts(count); return String.format("There %s %s %s%s",verb, number, candidate, pluralModifier ); } private void createPluralDependentMessageParts(int count) { if (count == 0) { thereAreNoLetters(); } else if (count == 1) { thereIsOneLetter(); } else { thereAreManyLetters(count); } }
  • 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.
  • 38. Meaningful Names  SAMPLE NAMING CONVENTION for JAVA
  • 39. Meaningful Names  EXAMPLES - 1 private static boolean isWeeklyAndMontlyonSameDay(CBDate today){ if( today.getLastDayOfMonth().compareTo(today) == today.getDayOfWeek() - Calendar.SATURDAY ) return true; return false; } private static boolean isWeeklyAndMontlyonSameDay(CBDate today){ final int numberOfDaysInWeek = 7; boolean isCurDateLastDayOfWeek = today.getDayOfWeek() == numberOfDaysInWeek ? true: false; CBDate lastDayOfMonth = today.getLastDayOfMonth(); boolean isCurDateLastDayOfMonth = lastDayOfMonth.compareTo(today) == 0 ? true: false; if( isCurDateLastDayOfWeek && isCurDateLastDayOfMonth) return true; else return false; }
  • 40. Meaningful Names  EXAMPLES – 2 private static String getPeriodParameter (CBDate today) { if( today.getLastDayOfMonth().compareTo(today)== 0 ) return PacketConstants.PeriodType.MONTHLY_INFORMATION.periodCode(); else return PacketConstants.PeriodType.WEEKLY_INFORMATION.periodCode(); } Which parameter???? --> Should be getPeriodCode(CBDate today)
  • 41. Meaningful Names  EXAMPLES – 3 protected Result validateAdd(CBBag ruleBag) throws CBException{ String taxNumber = ruleBag.get(TAXNUMBER).toString(); long customerOID = ruleBag.get(CUSTOMEROID).toSimpleLong(); // taxNumber CheckDigit Control try { if (controlCustomerTypeNationality(customerOID, taxNumber)) { CBBag taxNumberBag = CBBagFactory.createBag(); taxNumberBag.put(VERGINO, taxNumber); taxNumberBag.put(OPERATIONTYPE, 1); taxNumberBag = CBCaller.call("VERGI_CHECKDIGITKONTROLET", taxNumberBag); } } catch (Exception e) { return Result.createErrorResult(ResultType.resultType_FAILURE, CustomerExceptions.VERGINO_HATALI, null); } ………….
  • 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