Effective Code Communication Through Layout and Style Programming Techniques

communicating in code layout and style n.w
1 / 31
Embed
Share

Explore the importance of layout and style in programming for improved code readability. Learn about fundamental formatting principles, whitespace usage, line breaks, and indentation techniques. Discover how parentheses play a crucial role in clarifying code ambiguity. Enhance your understanding of code organization and structure through strategic formatting practices.

  • Code Communication
  • Programming Techniques
  • Code Readability
  • Layout and Style
  • Parentheses

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. COMMUNICATING IN CODE: LAYOUT AND STYLE PROGRAMMING STUDIO, SPRING 2019 ROBERT LIGHTFOOT Note: several examples in this lecture taken from The Practice of Programming by Kernighan and Pike

  2. LAYOUT AND STYLE Like naming, the goal is to communicate Again like naming, sometimes conventions are in place Adhering to the convention in place will usually lead to more readable code than using your own better convention Goal of layout and style is to increase clarity.

  3. FUNDAMENTAL THEOREM OF FORMATTING Good visual layout shows the logical structure of the program. Studies show that organization is as important to understanding as the details

  4. WHITE SPACE Used to indicate logical grouping Spacing between characters Indentation Blank lines

  5. LINE BREAKS Use blank lines to separate different sections of code Separate concepts should be reflected by separate blocks of code Should usually comment start of each block Put blank lines between functions/methods.

  6. INDENTATION Can clarify structure, especially in odd cases Studies show that 2-4 space indentation works best. More indentation might appear better, but is not Now, usually editors provide automatically But, variations for some statements: switch/case if/elseif Brace conventions differ, but be consistent

  7. EXAMPLE BRACE CONVENTIONS while (something) { blahblahblah } while (something) { blahblahblah } while (something) { blahblahblah } while (something) { blahblahblah }

  8. PARENTHESES Parentheses can resolve ambiguity Particularly important since order of operations can be problematic Better to use more parentheses than you think you need Coupled with white space, can more quickly highlight the grouping/ordering of operations leap_year = y % 4 == 0 && y % 100 != 0 || y % 400 == 0;

  9. PARENTHESES Parentheses can resolve ambiguity Particularly important since order of operations can be problematic Better to use more parentheses than you think you need Coupled with white space, can more quickly highlight the grouping/ordering of operations leap_year = y % 4 == 0 && y % 100 != 0 || y % 400 == 0; leap_year = ((y%4 == 0) && (y%100 != 0)) || (y%400 == 0);

  10. OPTIONAL BRACES Like parentheses, use more(??) braces than you need One-statement operation often becomes more, later if (a > b) max = a;

  11. OPTIONAL BRACES Like parentheses, use more braces than you need One-statement operation often becomes more, later if (a > b) max = a; cout << Set a new maximum. << endl;

  12. OPTIONAL BRACES Like parentheses, use more braces than you need One-statement operation often becomes more, later if (a > b) { max = a; }

  13. BRACES Like parentheses, use more braces than you need. One-statement operation often becomes more, later. if (a > b) { max = a; cout << Set a new maximum. << endl; }

  14. AVOIDING COMPLEX EXPRESSIONS Goal is not to write most concise and clever code Break up expressions to make them clearer The ? operator can be especially problematic *x += (*xp=(2*k < (n-m) ? c[k+1] : d[k--])); if (2*k < n-m) *xp = c[k+1]; else *xp = d[k--]; *x += *xp;

  15. AVOIDING COMPLEX EXPRESSIONS Goal is not to write most concise and clever code Break up expressions to make them clearer The ? operator can be especially problematic *x += (*xp=(2*k < (n-m) ? c[k+1] : d[k--])); if (2*k < n-m) { *xp = c[k+1]; } else { *xp = d[k--]; } *x += *xp;

  16. USE NATURAL FORM FOR EXPRESSIONS State conditional tests positively if (!(z>=0) && !(z<a)) if ((z<0) && (z>=a)) This can vary if the way it s expressed better matches the underlying algorithm

  17. USE IDOMATIC FORMS There are common ways of expressing certain things. e.g. Use a for loop appropriately loop control in the for statement, and other operations outside for (i=0;i<n;i++) a[i] = 0.0; for (i=0;i<n;a[i++]=0.0); for (i=0;i<n;) { a[i] = 0.0; i++ }

  18. IDIOMATIC FORMS Use if-elseif-else form whenever possible Alternatives are more difficult to understand if (cond1) { if (cond1) { dothis1(); } else { if (cond2) { dothis2(); } else { if (cond3) { dothis3(); } else { dothis4(); } } } dothis1(); } else if (cond2) { dothis2(); } else if (cond3) { dothis3(); } else { dothis4(); }

  19. IF STATEMENTS Read so that you look for the true case rather than a stack of else cases if (a > 3) { if (b < 12) { while (!EOF(f)) { dothis(); } } else { cerr << Error 2 << endl; } } else { cerr << Error 1 << endl; } if (a <= 3) { cerr << Error 1 << endl; } else if (b >= 12) { cerr << Error 2 << endl; } else { while (!EOF(f)) { dothis(); } }

  20. AVOID MAGIC NUMBERS The constant values that we use in our programs Rule of thumb: any number other than 0 or 1 is probably a magic number int a = 1 a; // alternating between 1 and 0 int a = rand ()%100 + 1; //random num. in range [1,100] No need to have variables replacing 1 Can lead to tremendous debugging problems when these numbers are changed One change is out-of-sync with others Instead, define constants, or variables, to give names to those numbers.

  21. AVOID MAGIC NUMBERS Rule of thumb: any number other than 0 or 1 is probably a magic number Can lead to tremendous debugging problems when these numbers are changed Instead, define constants, or variables, to give names to those numbers. Even better const int WINHEIGHT = 400; windowPosY = WINHEIGHT-y OR windowPosY = 400-y; OK int WINHEIGHT = 400; windowPosY = WINHEIGHT-y #define WINHEIGHT 400 windowPosY = WINHEIGHT-y

  22. LAYOUT FOR CONTROL STRUCTURES Put control in one line when possible Single indentation level for what it affects xxxxxx xxxxx xxxxx Group each part of a complicated condition on its own line Same idea as before, break-down whenever necessary

  23. LAYOUT OF INDIVIDUAL STATEMENTS White space can improve readability Spaces after commas Write it in the same way you write English EvaluateEmployee(Name.First,EmployeeID,Date.Start,Da te.End); EvaluateEmployee (Name.First, EmployeeID, Date.Start, Date.End); Spaces between parts of conditions if (((a<b)||(c>d))&&((a+b)<(c-d))&&((c-d)>2)) If ((a<b) || (c>d)) && ((a+b)<(c-d)) && ((c-d)>2))

  24. LAYOUT OF INDIVIDUAL STATEMENTS White space can improve readability Spaces after commas EvaluateEmployee(Name.First,EmployeeID,Date.Start,Date.End); EvaluateEmployee (Name.First, EmployeeID, Date.Start, Date.End); Spaces between parts of conditions if (((a<b)||(c>d))&&((a+b)<(c-d))&&((c-d)>2)) if (((a<b) || (c>d)) && ((a+b)<(c-d)) && ((c-d)>2)) if (((a<b) || (c>d)) && ((a+b) < (c-d)) && ((c-d) > 2) )

  25. LAYOUT OF INDIVIDUAL STATEMENTS Line up related definitions or assignments StudentName = ProcessInputName(); StudentID = ProcessInputID(); StudentHometown = ProcessInputName(); There is a big problem with this, though!

  26. LAYOUT OF INDIVIDUAL STATEMENTS Line up related definitions or assignments Don t use more than one statement per line. Likewise, define only one variable per line. Exception: when defining sets of variables or writing statements with same purpose x = ray.computehits(); nhits = x.size(); // unrelated x = ray.computehits(); //better nhits = x.size(); ------------------------------------------------------ int i; float[3] newpoint; //dissimilar data types int i; float[3] newpoint; ------------------------------------------------------- point vertex1, vertex2, vertex3; // variables with similar purposes a[i]=b[i]=c[i]=0.0;

  27. LAYOUT OF INDIVIDUAL STATEMENTS Line up related definitions or assignments Don t use more than one statement per line. Avoid side-effects (such as including the ++ operator when doing something else). Try to write in separate statements. x[i++] = 0; x[++i] = 0; x[i] = 0; ++i; (or i++;) i++; x[i] = 0;

  28. WHEN A LINE IS TOO LONG Make it clear that the previous line is not ending (e.g. end with an operator) Keep related parts of the line together(don t break single thought across line) Use indentationto highlight that there s a continuation Make it easy to find the end of the continued line

  29. WHEN A LINE IS TOO LONG retirementFunds=AmtAfterTax(Compound(checkingBalance,checkingRate, yearsleft)+Compound(savingsBalance,savingsRat,yearsleft)+Compound( mutualFundBalance,fundRate,yearsleft),taxRate)+Compound(rothiraBalance ,fundRate,yearsleft); Clear continuation retirementFunds = AmtAfterTax ( Compound (checkingBalance, checkingRate, yearsleft) + Compound (savingsBalance, savingsRat, yearsleft) + Compound (mutualFundBalance, fundRate, yearsleft), taxRate) + Compound(rothiraBalance, fundRate, yearsleft); Indentation

  30. LAYOUT OF ROUTINES Use standard indentation approach for arguments Use blank lines to separate parts of routines or blocks of common actions Slightly different idea/purpose Just like an essay where Paragraphs are used to separate ideas Use comments (will return to it later) to identify major breaks in conceptual flow Completely different idea

  31. LAYOUT OF FILES Clearly separate (multiple line breaks) different routines in the same file Don t want to accidentally merge or break individual routines Also helps easy navigation Sequence functions inside files in a logical manner Functions in a .cpp files are written in the same order as in the .h files Or, in alphabetical order Or, Constructor, accessor, destructor, other in this order Again, whatever you choose, be consistent

More Related Content