Naming Standards, Clean Code


Published on

Updated on 3rd of October 2012.. More examples from Real- Working Codes will be added soon..

Naming Standards, Clean Code

  1. 1. Naming Standards CLEAN CODE Belgi Özen, CRM & Customer Dept., IBTECH Updated on 3rd Oct. 2012
  2. 2. Contents1. Preface2. Meaningful Names3. References
  3. 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 Craftsmanship2. Code Complete 2nd edition 20043. Refactoring-Improving the Design of Existing Code
  4. 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 tobe kept clean over time. If we all checked-in our code alittle cleaner than when we checked it out, the codesimply could not rot. The cleanup doesn’t have to besomething big. Change one variable name for thebetter, break up one function that’s a little too large,.
  5. 5. Meaningful Names The name Should Tell Why It Exists, What it does..It should fully and accuratelydescribe the entity the variable represents. An effective technique for coming up with a good name is to state in wordswhat 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. 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 thezeroth subscript is the location of a status value and that a status value ofMeans ―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. 7. Meaningful Names An example from our CORE bankıng Codei.e: checkCustomerData(MustriPOMData customerPOMData)We can not understand what this method does unless we read the internals of thecode!!!!!WRONG NAMING!!!! ;
  8. 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. SystemJava Code Completion; name variables/constants with smilar functionalities but smalldifferences; write a part of the variable; type CTRL + SPACE and choose appropriateOne (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. 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 theSource and Destination from the method signiture!!! Use SOURCE andDESTINATION INSTEAD!!!! Do not use Noise Words;i.e, creating ProductInfo and ProductData classes may mean the same to thedeveloper; 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. 10. Meaningful Names DISTINCTION in NAMESProductInfo and ProductData classes; who knows what the difference is?? Info andData are similiar words which does not make any distinction..Customer , CustomerObject What is the distinction??!! Likewisecustomer, customerInfo; account, accountData
  11. 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. 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 thatits type is String ; the do not use a variable customerNameString orcustomerNameStrEx : moneyAmount and money varibles in the same method
  13. 13. Meaningful Names Use PRONOUNCABLE Namesi.e: class DtaRcrd102 { private Date genymdhms; // generationdate, year, month, day, hour, //minute,and second (you can notread 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"; }; IIntelligent 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. 14. Meaningful Names Use SEARCHABLE Namesex: if(customerType.equals(―G‖)){} if(customerType.equals(CUSTOMERTYPE_RETAIL)){} //SEARCHABLEEX: 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 ASint 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. 15. Meaningful Names Avoid Mental MappingReaders shouldn’t have to mentally translate your names into other names theyalready know. Do not show off by changing the name of some well-known variables(invery 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 isthat the professional understands that CLARİTY İS KİNG.Professionals use their powers for good and write code that others canunderstand.
  16. 16. Meaningful Names Problem OrientationA 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 namerefers to some aspect of computing rather than to the problem, its a how rather thana 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 fromproblem domain employeeData is better )To indicate printer status ; bitFlag printerReady
  17. 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. 18. Meaningful Names Do Not PUN!! Avoid using the same word for two purposes. Using the same term for twodifferent ideas is essentially a pun.If you follow the ―one word per concept‖ rule, you could end up with many classesthat have, for example, an add method. As long as the parameter lists and returnvalues 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 orconcatenating two existing values. Now let’s say we are writing a new class thathas a method that puts its single parameter into a collection. Should we callthis method add? It might seem consistent because we have so many other addmethods,but in this case, the semantics are different, so we should use a name likeinsert or append instead. To call the new method add would be a pun.
  19. 19. Meaningful Names Add Meaningful Context Prefer placing variables in well-named classes, funtions or namespaces. When allthese fails, prefixing the name saccording to the context is better than doingnothing..
  20. 20. Meaningful Names Add Meaningful Context Prefer placing variables in well-named classes, funtions or namespaces. When allthese fails, prefixing the name saccording to the context is better than doingnothing..Imagine that you have variables namedfirstName, lastName, street, houseNumber, city,state, and zipcode. Takentogether it’s pretty clear that they form an address. But what if you just saw thestate variable being used alone in a method? Would you automatically infer that itwas part of an address?You can add context by using prefixes:addrFirstName, addrLastName, addrState, and so on. At least readers willunderstand that these variables are part of a larger structure. Of course, a bettersolution is to create a class named Address. Then, even the compiler knows thatthe variables belong to a bigger concept.
  21. 21. Meaningful Names Add Meaningful Contextprivate 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. 22. Meaningful Names Add Meaningful Contextpublic 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. 23. Meaningful Names Add Meaningful Contextprivate 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. 24. Meaningful Names Optimum Variable LengthSould Not be Too Long (maximumNumberOfPointsInModernOlympics.) or tooShort(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 easyto debug.The guideline doesn’t mean that you should try to make all of yourvariable names 9to 15 or 10 to 16 characters long. It does mean that if you look over your code andsee many names that are shorter, you should check to be sure that the names are asclear as they need to be.Too long: numberOfPeopleOnTheUsOlympicTeam ; numberOfSeatsInTheStadiummaximumNumberOfPointsInModernOlympicsToo short: n, np, ntmn, ns, nsisd m, mp, max, pointsJust right: numTeamMembers, teamMemberCount
  25. 25. Meaningful Names Computed Value Qualifiersmost Significant part of the varibale name, the part that give it most of itsmeaning is at the front. Use computed value qualifiers like Max, Total, Average, Pointer at the end… LikesalaryAverage, 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 likenumSales. When placed at the end; it refers to an index. Like saleNum. To keepaway from the confusion use Index and Count keywords when necessary.revenueTotal; expenseTotal, revenueAverage
  26. 26. Meaningful Names Common Opposites In Variable Namesincreases the readability.. Easy to Understand..begin/endfirst/lastlocked/unlockedmin/maxnext/previousold/newsource/targetvisible/invisible
  27. 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, amore meaningful name like recordCount would be appropriateIf loop is very long, we may forget what i,j,k stands for. Choose betterdescriptive variable names.. Especially in nested loops, if we use i,j,ktogether, we may get Confused.for ( teamIndex = 0; teamIndex < teamCount; teamIndex++ ) { for ( eventIndex = 0; eventIndex < eventCount[ teamIndex ]; eventIndex++ ) { score[ teamIndex ][ eventIndex ] = 0; }}
  28. 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 withenumerated types, named constants.DO NOT USE flag in the nameBAD 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. 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 realpurposes.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. 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 itby 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 thatit makes simple logical expressions less readable: if ( isFound ) is slightly lessreadable 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 sourceFileGood Naming error; statusOK found sourceFileFound , sourceFileAvailable
  31. 31. Meaningful Names Naming Enumerated Typesit’s clear that members of the type all belong to the same group by using a groupprefixVb 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. 32. Meaningful Names Naming ConstantsName the abstract entity which the constant represents rather than the numberthe constant refers to. ALL_CAPS seperated by underscoresBad 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. 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. 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. 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 likeCustomer, WikiPage,Account, and AddressParser…. A class name should not be a verb.
  36. 36. Meaningful Names METHOD NAMES1) The method names contains verbs..2) Accessors  get mutators set predicates is3) Overloaded Constuctors as static Factory Methods; Hide default Constructors by making them private.string name = employee.getName();customer.setName("mike");if (paycheck.isPosted())...
  37. 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. 38. Meaningful Names SAMPLE NAMING CONVENTION for JAVA
  39. 39. Meaningful Names EXAMPLES - 1private 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. 40. Meaningful Names EXAMPLES – 2private 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. 41. Meaningful Names EXAMPLES – 3protected 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 ="VERGI_CHECKDIGITKONTROLET", taxNumberBag); } } catch (Exception e) { returnResult.createErrorResult(ResultType.resultType_FAILURE, CustomerExceptions.VERGINO_HATALI,null); }………….
  42. 42. Meaningful Names EXAMPLES – 3What does controlCustomerTypeNationality(customerOid) do???You can’t understand what it does unless You investigate the internals of the code!!!
  43. 43. References1. Clean Code A Handbook of Agile Software Craftsmanship2. Code Complete 2nd edition 20043. Working Effectively with Legacy Code