Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jordi Cortadella Department of Computer Science

Similar presentations


Presentation on theme: "Jordi Cortadella Department of Computer Science"— Presentation transcript:

1 Jordi Cortadella Department of Computer Science
Code style Jordi Cortadella Department of Computer Science

2 Why code styles? Programs are often modified because:
They are incomplete or incorrect: maintenance They are used as a starting point for another program: reuse New functionalities must be added: extension The code style has a significant impact on the effort required to understand and modify programs. Introduction to Programming © Dept. CS, UPC

3 Why code styles? “Programming is an art of telling another human what one wants the computer to do.” Donald Knuth. “Programming is 10% writing code, and 90% reading code. Reading your own code and reading other code.” “Taking that extra time to write a proper description of what you worked on will save huge amounts of time in the future.” Tomer Ben Rachel, a full stack developer. Introduction to Programming © Dept. CS, UPC

4 Introduction to Programming
© Dept. CS, UPC

5 What is a code style? A set of rules or guidelines used when writing the source code for a computer program Introduction to Programming © Dept. CS, UPC

6 Which code style There are plenty of code styles. Usually, each company or institution has its own code style. Some examples: Google: Linux kernel: GNU: Introduction to Programming © Dept. CS, UPC

7 In this course We will give few simple rules to encourage a good coding style: Format Naming conventions Specification Comments We will mostly focus on writing easy-to-read programs. We will illustrate the rules by examples. Real code styles may include hundreds of rules. Introduction to Programming © Dept. CS, UPC

8 Format: indentation and braces
int gcd(int a, int b) { while (a != b) { if (a > b) a = a – b; else b = b – a; } return a;} int gcd(int a, int b) { while (a != b) { if (a > b) a = a – b; else b = b – a; } return a; } Use 2- or 4-space indentation (be consistent). Avoid the use of Place opening/closing braces consistently (e.g., opening brace last on the line) Introduction to Programming © Dept. CS, UPC

9 A python programmer attempting Java
Is this a good style? A python programmer attempting Java Introduction to Programming © Dept. CS, UPC

10 Format: blank lines and spaces
Use blank lines to distinguish different sections of your program: Between different functions Between different sections of a function (initialization, main loop, return, …) Use spaces to make your program more readable: Within complex expressions (emphasizing operator precedences) Separating different items of a list Introduction to Programming © Dept. CS, UPC

11 Spaces: examples Bad style Good style
// Dense code int numCars=0,time=0; // Confusing expression a = b  c+d  2; // No space after if/while while(a!=0) {…} // Space after function name x = power (y,2); // Spaced declarations int numCars = 0, time = 0; // Emphasize precedences a = b*c + d*2; // Space after if/while while (a != 0) {…} // No space after function name // but space between parameters x = power(y, 2); Introduction to Programming © Dept. CS, UPC

12 Naming conventions An important decision about our programming style is how to pick appropriate names for the components of our program: Files Functions Variables etc Naming conventions can be controversial and refer to: Length of the identifiers How to mix letters (upper and lowercase) and numbers How to separate multiple-word identifiers (spaces not allowed) Introduction to Programming © Dept. CS, UPC

13 Naming conventions Files: x2.cc f.h Variables: int nl; double n, m; Functions: double f(double n); Files: gcd.cc numerical.h Variables: int numLetters; double x, y; // coordinates Functions: double sqrt(double x); Introduction to Programming © Dept. CS, UPC

14 Naming: recommendations
Use meaningful names that are self-documented and help to read the programs fluently. Short names allowed when their meaning is obvious from the context. Examples: for (int i = 0; i < n; ++i) … double d; // represents distance // this could be obvious in a program // written by Physicists Introduction to Programming © Dept. CS, UPC

15 Naming: recommendations
The names i, j, k are often used for indices. Variables starting with n usually refer to natural numbers. Variables starting with x, y, z usually refer to real numbers (e.g., coordinates). Example: names for distance. di (very bad name: difference? 𝑑 𝑖 ?...) dis (bad name: display? disjoint?...) dist (better but improvable) distance (the best) d (acceptable in a Math or Physics context where 𝑑 is always used as distance. Using a different letter might create confusion) Introduction to Programming © Dept. CS, UPC

16 Naming: recommendations
Use multiple-word names to improve readability: numLetters, first_element, IsPrime, StartTime, … Programming with short names ends up by taking longer development time: difficult to understand and debug. Adding few more characters to a variable name may save a lot of time, e.g., int t;  int timeInSeconds; Programming with long variable names is not inefficient. Most of the programming IDEs offer auto-completion features and identify the variable names by just typing a couple of characters. Where would you prefer to spend most of your time: writing the code or debugging it? Introduction to Programming © Dept. CS, UPC

17 Combining words: case styles
Camel Case myFunctionName Pascal Case MyClassName Snake Case my_variable_name SCREAMING SNAKE CASE MY_CONSTANT_NAME Which one is better? Follow the code style rules Be consistent Introduction to Programming © Dept. CS, UPC

18 Specification My mom said: “Honey, please go to the market and buy 1 bottle of milk. If they have eggs, bring 6” I came back with 6 bottles of milk. She said: “Why the hell did you buy 6 bottles of milk?” I said: “BECAUSE THEY HAD EGGS!!!” Introduction to Programming © Dept. CS, UPC

19 Specification In this course we will focus on writing good specifications for functions. Essential ingredients: Use good names for the functions and parameters Describe the meaning and domain of the parameters. Describe what the function does and/or returns. A good function specification should enable a programmer to exactly understand what a function does without looking at the body of the function. Essential: every parameter must be mentioned in the specification of a function. Introduction to Programming © Dept. CS, UPC

20 Specification: example
// Checks whether it is a multiple bool check(int n, int m); // Questions: // What does the function name mean? // Who is multiple of whom? // Can m be zero? // Pre: m > 0. // Checks whether n is multiple of m bool isMultiple(int n, int m); Introduction to Programming © Dept. CS, UPC

21 Specification: example
// Draws a rectangle void d(int n, int m); // Questions: what is the height and width // of the rectangle? What is the output? // Better specification (notice the names): // Pre: nrows > 0, ncols > 0 // Draws a rectangle of ‘*’ in cout // consisting of nrows rows and ncols columns void drawRectangle(int nrows, int ncols); Introduction to Programming © Dept. CS, UPC

22 Comments Comments help reading and understanding the code more fluently. Comments are important not only for code readers, but also for writers. Writing comments is an art. Every programmer has her own style. Use common sense: not too many, not too few. Be informative only when necessary. Using appropriate names for variables and functions is a good starting point for documentation. Introduction to Programming © Dept. CS, UPC

23 Comments: example How long will it take to figure out what this code does? for (int i = P.size()-1; i >= 0; --i) eval = evalx + P[i]; Introduction to Programming © Dept. CS, UPC

24 Comments: example Very little, if we just add a simple comment
// Evaluates the polynomial P(x) using Horner’s scheme for (int i = P.size()-1; i >= 0; --i) eval = evalx + P[i]; Introduction to Programming © Dept. CS, UPC

25 Don’t add redundant comments
blah, blah, blah, blah, blah, blah, … // We declare the variable // and initialize to zero int n = 0; if (a%2 == 0) // If it is an even number ++i; // we increase i at each iteration // and we add the elements A[i] = B[i] + C[i]; Introduction to Programming © Dept. CS, UPC

26 If possible, get closer to natural language
Bad style Good style // What is f? while (f == false) { … } // What’s a and p? a = 2*p; // Hmmm, that long? if (a >= 0) return true; else return false; // Too verbose if nobody // else is using r double r = sqrt(x); if (r > z) { … } // Ah, yeah! while (not found) { … } // Clear enough angle = 2*Pi; // Much nicer return a >= 0; // Much simpler if (sqrt(x) > z) { … } Introduction to Programming © Dept. CS, UPC

27 You would not like your code to have a comment like this, right?
Introduction to Programming © Dept. CS, UPC

28 Some quotes on programming
“Documentation is a love letter that you write to your future self.” Damian Conway “Commenting your code is like cleaning your bathroom - you never want to do it, but it really does create a more pleasant experience for you and your guests.” Ryan Campbell “Looking at code you wrote more than two weeks ago is like looking at code you are seeing for the first time.” Dan Hurvitz “The sooner you start to code, the longer the program will take.” Roy Carlson Introduction to Programming © Dept. CS, UPC

29 Conclusion When writing code, spend as much time as possible to ease the task of the reader, even if that implies making your task more tedious (comments, long variable names, etc). When working with a programming team, a good coding style will save a huge amount of time (and time is money!). The code writer is the person who will benefit most from using a good coding style (because he/she will be the main reader). Introduction to Programming © Dept. CS, UPC


Download ppt "Jordi Cortadella Department of Computer Science"

Similar presentations


Ads by Google