Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS5103 Software Engineering

Similar presentations


Presentation on theme: "CS5103 Software Engineering"— Presentation transcript:

1 CS5103 Software Engineering
Lecture 12 Coding Styles

2 Coding style 2 Why? What? Easier to read: for others and yourself
Less mistakes and misunderstandings Reduce the requirement for comments and documentation (self-documented) What? Coding style is not a very well organized topic A lot of scattered and conflicting tips given by experienced developers We organize all these tips from the smallest to the largest code elements (Identifier to File) 2

3 Coding style and programming languages
Coding style is mostly general E.g., should not use too simple variable names Coding style can be specific to programming languages in some cases Case sensitive / insensitive languages Case sensitive: C family (including Java, python) Case insensitive: Basic, Fortran, Pascal, Ada Semantics for cases: Prolog (cap for var, low for names) Indentation based compilation Python, Haskell Different code structures Classes in OO languages, recursions in functional languages 3

4 Coding style: An example
int 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; 4

5 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<100) UI.sendMessage("The diff is "+ diff); UI.sendMessage("Footer"); while(!this.comingMessage) UI.sendMessage("Waiting for next message"); this.count = this.count + 1; if(UI.success) return 0; //return 0 if UI.success is true return 1;} 5

6 Variables and Constants
Variable (function, method) Naming Do 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) 6

7 Variables and Constants
Hungarian Notations Each variable has a prefix to indicate its type lAccountNum (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 lot Not very necessary in OO languages with modern IDEs, because the type of a variable is complex in itself, and easy to know 7

8 Variables and Constants
Give a name to constants People know what it is Consistent modification If 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 languages Don’t use ‘l’ for long integer, use ‘L’ instead Consider 10l, very confusing 8

9 Variables and Constants
String Constants Try to avoid string constants in your code Especially if they are related to UI (visible strings), system (paths), database (sql statements), or any environments Put them in different configuration files according to their usage So that you can change them later to generate different releases (different OS, regions, etc.) 9

10 Expressions Avoid Complex expressions 10
Give names to intermediate results Example: 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(); 10

11 Expressions 11 Avoid 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 Expressions Avoid abbreviation in some languages e.g., use if (x!=0) instead of if (x) 11

12 Statements/Lines 12 One statement per line Line breaks
Set a maximum length for lines Break 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 code e.g., if(long condition 1 && long condition 2){ do something; } 12

13 Blocks Indentation Do 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 Python 2 (Lua, scala, ruby, …) or 4 spaces (others), usually depending on the language you use and the team convention you decided on 13

14 Blocks 14 Single statement blocks for loop and conditions Logic blocks
Add curly brackets around, why? if(a > 1) // do something; Error!! another statement; Logic blocks Divide a basic block to several logic blocks, add an empty line between them int validDiscountRate = …; int finalAmount = validDiscountRate * amount; print getReceiptHeader(); print finalAmount; 14

15 Blocks 15 Code Clones Example:
Copy and paste is a notorious programming habit Simple but result in code clones Inconsistent modification of different clone segments Example: for (int i = 0; i < 4; i++){ sum1 += array1[i]; } average1 = sum1/4; sum2 += array2[i]; average2 = sum1/4; 15

16 Blocks 16 Code Clone Detection After Detection
Quite a number of tools: CCFinder, Deckard, Conqat, mostly for C, C++ and Java. VS.net 2013 also has the feature for C# After Detection Eliminate (extract a method invoked by both places) Sometimes not easy Want to reduce dependencies Change other people’s code 20% code clones in industry / open source code Try to keep track of them VS.net may have a feature in near future 16

17 Methods Size 17 easier to understand easier to reuse: less code clones
Smaller, and smaller, and even smaller … Usually less than 20 lines, and never exceed 100 lines Why? easier to understand easier to reuse: less code clones 17

18 Methods 18 Signatures Contents Avoid too many parameters
But still need dependency injection? Group parameters to a new class Contents Try to avoid side effect Try to not use global variables, especially writing global variables 18

19 File Structure Follows the common structure of the language (e.g., imports, class decl, fields, methods in Java, includes, macros, structs, functions in C) Keep it small Usually no more than 500 lines Should break a module to multiple sub-modules (it is also a design issue) Put public methods before private methods Easier for other people to read public methods 19

20 Comments A way to help other people and yourself to better understand your code later Common rules No need to comment everything More important to explain variables than statements: Other developers know what the statement does, but do not know what the variable means… Try to write complete sentences Avoid code in comments, it make readers harder to read code Clean commented code ASAP, you have version control, no need to preserve anything 20

21 Comments for statements
Two types of statements especially require comments Declaration statements Statements with complex expressions No meaningless comments Example: int score = 100; // set score to 100 TERRIBLE COMMENT! int score = 100; // the full score of the final exam is 100 21

22 Coding style: An example
int f(String str, int val1, int val2){ //calculate str1 and str2 based on the formular 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; //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<100) UI.sendMessage("The diff is "+ diff); UI.sendMessage("Footer"); while(!this.comingMessage) UI.sendMessage("Waiting for next message"); this.count = this.count + 1; if(UI.success) return 0; //return 0 if UI.success is true return 1;} 22

23 Today’s class 23 Issue tracking system Coding styles Type of issues
Process of issues Resolution of issues Coding styles Code Variables and constants Expressions Statements and Lines Blocks Methods and Classes Enforcing coding styles Comments 23

24 Next class 24 API comments and Documentation Software license
Javadoc Software license Proprietary licenses Open source software licenses Software refactoring Why software refactoring? Types of refactoring Tool supports Behind refactoring tools 24

25 Mid-term 25 Time: Oct 6th 6:00pm to 7:15pm Location: In class
Form: closed book exam 100 points total Account for 20% for the course grade 7-8 multiple choice questions * 6 points each: single answer 2-3 multiple choice questions * 8 points each: multiple answers 2-3 Question & Answer, 35 points in total 25

26 Covered Course Contents
Must * It is for sure that this knowledge point will be covered in the mid-term May ? This knowledge point may be covered in the mid-term Not mentioned in this outline The mid-term will not cover this knowledge point 26

27 Software process models
Features of Waterfall model ? Features of Iterative model ? Features of Agile software development & Extreme programming * Major difference between these models * Usage Scenario of different models ? 27

28 Requirement Engineering
Find Stake Holders ? Type of Requirements * Major requirement elicitation approaches ? Natural Language Specifications and find problems in the specifications * Use case diagram ? Actors and Relationship between use cases ? 28

29 System Modeling Class Diagram* 29 Draw Class Diagrams *
Relationship between classes * Generalization, Aggregation, Composition, Association and their difference * Multiplicity and Role Names ? 29

30 Software Architecture
Major software architecture styles* Pipe and Filter ? Layered ? Repository ? There differences and usage scenarios * 30

31 Software Design Coupling and Cohesion ? Design Patterns * 31
Structure and Types ? Composite Pattern ? Factory Pattern ? Visitor Pattern ? 31

32 Versioning 32 Diff * Conflict ? Branch *
Know what a diff between two files should look like ? Know how applying a diff works ? Know what diff to apply for pull / update ? Conflict ? Know how to detect conflict ? Branch * Know how to merge branches by applying diffs ? Branch strategies and their pros / cons ? 32

33 Coding Styles Coding style rules for all levels *
Identifier / constant ? Expression ? Statements ? Blocks ? Comments ? Finding coding style errors in given code * 33

34 Thanks! 34

35 Coding style enforcement: Eclipse
Demo Go to windows -> preferences -> Java (or other languages installed) -> coding styles -> formatter Select an existing profile (e.g. eclipse built-in) or click on New… to generate a new one Click on edit to open the edit panel Edit 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 click apply To format existing code: Ctrl + Shift + F 35

36 Comments for Methods A well-structured format for each public method Explain: What the method does What does the return value mean What does the parameters represent What are restrictions on parameters What are the exceptions, and what input will result in exceptions For private method, comment may be less structured, but still need to include the information 36

37 Comments for Methods 37 Example: /**
* Fetch a sub-array from an item array. The range * is specified by the index of the first item to * fetch, and ranges to the last item in the array. * list represents the item list to fetch from * it should not be null. start represents the start index of the * fetching range it should be between * and the length of list the fetched subarray */ public List<Item> getRange(List<Item> list, int start){ 37

38 Comments for Classes/Files
A well-structured comment for each class / file Include: Author (s) Generating time and version Version of the file A description of the class/file about its main features, and usage specifications / examples 38

39 Comments for Classes/Files
Example: /** * A mutable sequence of characters. The principal operations on a StringBuilder * are the append and insert methods. The append method always adds these * characters at the end of the builder; the insert method adds the characters at * a specified point. * * For example, if z refers to a string builder object whose current contents are * "start", then the method call z.append("le") would cause the string builder to * contain "startle", whereas z.insert(4, "le") would alter the string builder to * contain "starlet". * author : John Smith * generate: Oct.1st.2013 * version : 1.0 : 2.2 */ public class StringBuilder{ 39

40 Code convention for companies / organizations
Most companies / organizations have their code conventions Usually following the general rules of coding style May 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: Java conventions 40


Download ppt "CS5103 Software Engineering"

Similar presentations


Ads by Google