cs4723 software validation and quality assurance lecture 13 code review

Download CS4723 Software Validation and Quality Assurance Lecture 13 Code Review

Post on 02-Jan-2016

215 views

Category:

Documents

3 download

Embed Size (px)

TRANSCRIPT

  • CS4723Software Validation and Quality AssuranceLecture 13Code Review

  • *Coding styleWhy?Easier to read: for others and yourselfLess mistakes and misunderstandingsReduce the requirement for comments and documentation (self-documented)What?Coding style is not a very well organized topicA lot of scattered and conflicting tips given by experienced developersWe organize all these tips from the smallest to the largest code elements (Identifier to File)

  • *Coding style and programming languagesCoding style is mostly general E.g., should not use too simple variable namesCoding style can be specific to programming languages in some casesCase sensitive / insensitive languagesCase sensitive: C family (including Java, python)Case insensitive: Basic, Fortran, Pascal, AdaSemantics for cases: Prolog (cap for var, low for names)Indentation based compilationPython, HaskellDifferent code structuresClasses in OO languages, recursions in functional languages

  • *Coding style: An exampleint f(String str, int val1, int val2){ //calculate str1 and str2 based on the formula string str1 = str.subString(str.indexOf(str.charAt(2*val1+10-val1)), str.lastIndexOf(String.charAt(val1)) - str.lastIndexOf(String.charAt(0))); string str2 = str.subString(str.indexOf(str.charAt(2*val2+10-val2)), str.lastIndexOf(String.charAt(val2)) - str.lastIndexOf(String.charAt(0)));String resultforprint = str1 + str2; //concatenate str1 and str2 UI.initialize(); //initialized UI UI.sendMessage("Header"); //Send message "Header" to UI UI.sendMessage(resultforprint); int diff;

  • *Coding style: An example //if val1 larger than 10 and the diff of val2 and val1 is not 5, //or val2 is larger than 100, send the diff if(val1>10&&diff=(val2-val1)!=5||val2
  • *Variables and ConstantsVariable (function, method) NamingDo not use names with no meanings (e.g., a, b, ac, xyz)Do not use names with general meanings (e.g., do, run, it, value, temp)Do not differentiate variables with simple number indexes (e.g., name_1, name_2, name_3)Full words is better than abbreviations (e.g., use phone_number instead of tel)Use underscore or Capitalized letter to separate words (e.g., phone_number or phoneNumber)

  • *Variables and ConstantsHungarian NotationsEach variable has a prefix to indicate its typelAccountNum (long)arru8NumberList (array, unsigned 8 bit)Quite useful in C, and is used widely in C++ and C#MS code and Windows APIs use Hungarian Notations a lotNot very necessary in OO languages with modern IDEs, because the type of a variable is complex in itself, and easy to know

  • *Variables and ConstantsConstants Give a name to constantsPeople know what it isConsistent modificationIf global, collect all constants somewhere (e.g, Config class, or a configuration file)Conventionally, the name for a class/file-wide constant is all Capitalized words, concatenated by underscore (e.g., MAX_DAY_LIMIT), be careful of case-insensitive languagesDont use l for long integer, use L insteadConsider 10l, very confusing

  • *Variables and ConstantsString ConstantsTry to avoid string constants in your codeEspecially if they are related to UI (visible strings), system (paths), database (sql statements), or any environmentsPut them in different configuration files according to their usageSo that you can change them later to generate different releases (different OS, regions, etc.)

  • *ExpressionsAvoid Complex expressionsGive names to intermediate resultsExample: int totalAmount = (hasDiscount() && validForDiscount(user)) ? discountRate() * getPrice() * getNum() : getPrice() * getNum();-------------------------------------------------------------------boolean validDiscount = hasDiscount() && validForDiscount(user); int price = validDiscount ? getPrice() * discountRate() : getPrice();int totalAmount = price * getNum();

  • *ExpressionsAvoid corner cases (uncommon operators)Rules are complex, maybe changed (careful of updates!!)e.g. i += j; always equals to i = i + j; ?int a[] = {1, 5}; int i = 0; a[i] = i++; print (a[0]+, + a[1]);What will be printed?Add brackets even when you think it is unnecessary (except for + and * which is so well known)Conditional ExpressionsAvoid abbreviation in some languagese.g., use if (x!=0) instead of if (x)

  • *Statements/LinesOne statement per lineLine breaksSet a maximum length for linesBreak lines at binary operators, commas, etc.Put the binary operator at the beginning of the following line, why?Indent the following sub-lines to differentiate with other codee.g.,if(long condition 1 && long condition 2){ do something;}

  • *BlocksIndentationDo indentation for blocks (in method, loop, if-else conditions)Pay more intention to indentation in Python and Haskell, it is a right or wrong thing!!Try to avoid using tab, why?Tabs are translated to 2 or 4 spaces in different editors or settings, resulting in global coding style problems, and the case is even worse for Python2 (Lua, scala, ruby, ) or 4 spaces (others), usually depending on the language you use and the team convention you decided on

  • *BlocksSingle statement blocks for loop and conditionsAdd curly brackets around, why? if(a > 1)// do something; Error!! another statement;Logic blocksDivide a basic block to several logic blocks, add an empty line between themint validDiscountRate = ;int finalAmount = validDiscountRate * amount;

    print getReceiptHeader();print finalAmount;

  • *BlocksCode ClonesCopy and paste is a notorious programming habitSimple but result in code clonesInconsistent modification of different clone segmentsExample:for (int i = 0; i < 4; i++){ sum1 += array1[i];}average1 = sum1/4; for (int i = 0; i < 4; i++){ sum2 += array2[i];}average2 = sum1/4;

  • *BlocksCode Clone DetectionQuite a number of tools: CCFinder, Deckard, Conqat, mostly for C, C++ and Java. VS.net 2013 also has the feature for C#After DetectionEliminate (extract a method invoked by both places)Sometimes not easyWant to reduce dependenciesChange other peoples code20% code clones in industry / open source codeTry to keep track of themVS.net may have a feature in near future

  • *MethodsSizeSmaller, and smaller, and even smaller Usually less than 20 lines, and never exceed 100 linesWhy?easier to understandeasier to reuse: less code clones

  • *MethodsSignaturesAvoid too many parametersBut still need dependency injection? How?Group parameters to a new classExample:Use some tools to compare old and new data, match the diff to some pattern and output matching resultsdoStatistics(String newDataPath, String oldDataPath, String patternPath, String outputPath, String toolPath, )

    Generate a class called ConfigurationInfodoStatistics(ConfigurationInfo configInfo)

  • *MethodsContentsTry to not use global variables, especially writing global variablesTry to avoid unnecessary side effectsWhat are side effects?Change the state of the objectExample: public getDepth(){ int depth = 0 while(!callStack.isEmpty()){ callStack.pop(); depth = depth + 1; } return depth;}

  • *MethodsRelationsTry to avoid constraints between methodsExample: public load(File f){ this.file = f; open(this.file);}public process(){ do things with this.file;}public clean(){ close(this.file)}public load(File f){ this.file = f; open(this.file); this.content = readFrom(f); close(this.file)}public process(){ do things with this.content; open, write and close(this.file)}Put everything in one methodor

  • *File StructureFollows the common structure of the language (e.g., imports, class decl, fields, methods in Java, includes, macros, structs, functions in C)Keep it smallUsually no more than 500 linesShould break a module to multiple sub-modules (it is also a design issue)Put public methods before private methodsEasier for other people to read public methods

  • *Coding style: An exampleint f(String str, int val1, int val2){ //calculate str1 and str2 based on the formula string str1 = str.subString(str.indexOf(str.charAt(2*val1+10-val1)), str.lastIndexOf(String.charAt(val1)) - str.lastIndexOf(String.charAt(0))); string str2 = str.subString(str.indexOf(str.charAt(2*val2+10-val2)), str.lastIndexOf(String.charAt(val2)) - str.lastIndexOf(String.charAt(0)));String resultforprint = str1 + str2; //concatenate str1 and str2 UI.initialize(); //initialized UI UI.sendMessage("Header"); //Send message "Header" to UI UI.sendMessage(resultforprint); int diff;

  • *Coding style: An example //if val1 larger than 10 and the diff of val2 and val1 is not 5, //or val2 is larger than 100, send the diff if(val1>10&&diff=(val2-val1)!=5||val2
  • *Code convention for companies / organizationsMost companies / organizations have their code conventionsUsually following the general rules of coding styleMay set different line-length limits, 2 or 4 spaces, different ways to place braces, or whether to put spaces around operators or brackets, Some code convention examples:http://www.oracle.com/technetwork/java/codeconv-138413.html Java conventionshttp://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx

  • *Coding style enforcement: EclipseDemoGo to windows -> preferences -> Java (or other languages installed) -> coding styles -> formatterSelect an existing profile (e.g. eclipse built-in) or click on New to generate a new oneClick on edit to open the edit panelEdit the profile: change brace rules, tab to space, etc.Right click on your project -> preferences -> Java -> coding styles -> formatter-> check project specific -> choose a formatter and

Recommended

View more >