47
Coding style Software Design J. Serrat

Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Embed Size (px)

Citation preview

Page 1: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Coding style

Software Design

J. Serrat

Page 2: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Contents

1. What is and why a coding style

2. Golden rules

3. To read

4. Sample rules of a Java coding style

5. Elements of Java style : naming and comments

6. Javadoc & Eclipse

Page 3: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

What's a coding style

The syntax of a programming language tells you what code it is possible to write—what the machine will understand.

Style is a set of conventions, rules, recommenda-tions that tells you what you ought to write— what the humans reading the code will understand.

Page 4: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

What's a coding style

int i;main(){for(;i[“]<i;++i}”];read(‘-’-’-’,i++”hell\o, world!\n”,’/’/’/’));}read(j,i,p){write(j/p+p,i---j,i/i);}int i;main(){for(;i[“]<i;++i}”];read(‘-’-’-’,i++”hell\o, world!\n”,’/’/’/’));}read(j,i,p){write(j/p+p,i---j,i/i);}

Dishonorable mention, Obfuscated C Code Contest, 1984. Author requested anonymity.

Page 5: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

What's a coding style

if (a < 65) {  y = 65 ­ a; }else {  y = 0;}

if (age < RETIREMENT_AGE) {  yearsToRetirement = RETIREMENT_AGE ­ age;}else {  yearsToRetirement = 0;}

// What property does 'a' describe?// What is being calculated here?

Page 6: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

What's a coding style

Rules, conventions, recommendations on

● Files: length, organization...● Classes and Interfaces: inner organization● Comments: types, content and formatting● Declarations: variables, classes, methods● Statements: format● White spaces: while lines and indentation● Naming conventions: names of classes,

attributes, methods, constants, files● Methods

Page 7: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Why adopt an style ?

Main reason

● 80% of the lifetime cost of a piece of software goes to maintenance => reading code

● Hardly any software is maintained for its whole life by the original author.

● Improves the readability, and therefore, the main-tainability the software, because it allows engineers to understand new code more quickly and thoroughly.

Page 8: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Why adopt an style ?

Other reasons:

● If you ship your source code as a product, you need to make sure it is as well packaged and clean (professional aspect).

● Facilitates sharing of code among different programmers working on the same project.

● Saves development time by allowing programmers to focus on the semantics of the code, rather than spend time trying to determine what particular format is appropriate.

Page 9: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Problems

● For this to happen, every programmer in a team must conform to the same code conventions, and all of them

● Even if he/she does not like some rules.● There are a lot of proposed styles for widespread

languages (C, C++, Java), sometimes with contradicting rules!

● Requires learning and practice time.● Need of tools like Checkstyle to help enforce

(some of) the rules

Page 10: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Golden rules

1. When modifying existing software, follow the style of the original code.

Do not

● introduce a new coding style in your changes: a mix of styles is not an style.

● rewrite the old software just to make it match another style: it's a waste of time

Page 11: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Golden rules

2. Apply these rules to any code you write, not just code destined for production.

Even if your code never makes it into production, someone else may still have to read it.

Anyone who must look at your code will appreciate your professionalism

Page 12: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Golden rules

4. In any case, adopt some coding style, the more complete, the better.

no style << personal style < organization (documented) style < standard style

There is an standard for every programming language.

Page 13: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

To Read

Sun Java code conventionsThe one applied, in part, by Checkstyle.

The Elements of Java™ Style. Al Vermeulen, Scott W. Ambler and others. Cambridge University Press, 2000.

Helpful and detailed conventions on naming and comments, missing in the simple Sun style. Read chapters 3, 4 at least.

Page 14: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

To Read

Java coding style guide. Tech. report. Achut Reddy, 2000.19 pp but very complete

Writing robust Java code. Tech. report. Scott W. Ambler, 2000.70 pp. Predecessor of The elements... book.

How to write comments for the Javadoc tool. Sun/Oracle

Page 15: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

To know more

For C, C++ :

Industrial strength C++. M. Henricson, E. Nyquist, 2000. Freely available (html, pdf) at http://www.sannabremo.se/nyquist/industrial/index.htm

Recommended C style and coding standards. Several authors (Bell Labs, U. Toronto). 1989.

Page 16: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Java coding style

The following slides just aim to illustrate what's on a style definition. They don't replace the recommended readings.

[open Slides15.pdf]

Software Development (CS2500)Lecture 15: JavaDoc and Coding ConventionsM.R.C. van Dongen

Page 17: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

From “Elements of Java Style” : naming conventions and comments

Page 18: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions9. Use meaningful names for classes, methods,

attributes, constants (auto-documentation)

don't

do

Page 19: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

10. Use familiar names, from the problem domain.

11. Long names are ok but question too long names

12. Do not shorten names by removing vowels

Page 20: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

13. Capitalize only the first letter in acronymssetDSTOffset()  setDstOffset()loadXMLDocument()  loadXmlDocument()

but in constants

and at the beginning of method, variable and parameter and constants

static final String XML_DOCUMENT = "text/XML";

private Document xmlDocument;

Page 21: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

18. Capitalize the first letter of each word in a class or interface name.

Page 22: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

19,21,23,26 Use, if it makes sense, nouns when naming classesnouns or adjectives interfacesverbs methodsnouns variables

class Account implements Observable {  public Account() {  ...   }  public void withdraw(int amount) {  ...    }}

Page 23: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

24. Follow the is/set/get convention for accessors

Page 24: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

25. For variables and methods other than constructors, lowercase for the first word and capitalize first letter of each subsequent word.

Page 25: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

25. Pluralize the names of collection references.private Collection<Interval> intervals = new ArrayList<Interval>();private Collection activitats = new ArrayList();

Page 26: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

28. Set standard names for auxiliary “throwaway” variables.

character c, dstring s, strinteger counter i, j, kfloat coordinate x, y, zexception estream in, out, inOut

Page 27: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

29, 30. When a constructor or setter method assigns an input parameter to a field, give that parameter the same name as the field. Distinguish them with this.

Page 28: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Naming conventions

31. Constant names: use uppercase letters for each word and separate words with _

[A class like this can simply group related attributes, static methods and/or constants.]

Page 29: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

32. Write documentation [comments] for those who must use your code and those who must maintain it.

Always assume someone who is completely unfamiliar with your code will eventually have to read and understand it.

In fact, if enough time passes, this person may even be you!

Page 30: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

33. Keep comments and code in sync.

When the code and the comments disagree, both are probably wrong.—Norm Schryer, Bell Labs

Ok, now how (format, content) and what (program entities) to comment ?

Page 31: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

Java has 2 kinds of comments and 3 formats:

1. documentation comments● describe the specification of the code from

an implementation-free perspective, the contract

● to be read by developers who might not have the source code at hand.

● delimited by /**...*/, can be extracted to HTML files using the javadoc tool.

Page 32: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions/** * The <code>Rectangle2D</code> class describes * a rectangle defined by location (x,y) and * dimensions (w,h). */public abstract class Rectangle2Dextends RectangularShape {/** * The <code>Double</code> class defines a * rectangle specified in double coordinates... */static class Double extends Rectangle2D {...}.../** * The bitmask that indicates that a point lies * below this Rectangle2D... */static int OUT_BOTTOM;...

Page 33: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

● Javadoc only recognizes documentation comments when they appear immediately before a class, interface, constructor, method, or field declaration.

● Javadoc ignores any documentation comments that appear within the body of a method

Page 34: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

/** * Problema TimeTracker d'Enginyeria del Software 2, curs 2009­10. *  * Copyright (c) 2009­10 J. Serrat, [email protected] *  * Aquest software es confidencial i propietat dels autors. No pot ser * prestat sota cap concepte a altres estudiants de la assignatura durant * aquest curs. Posteriorment, queda lliure de qualsevol restriccio de * distribucio. */package nucli;

import java.util.Collection;

public class Projecte extends Activitat {

Ignored by javadoc

Page 35: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

Java has 2 kinds of comments and 3 formats:

2. implementation comments● are means for commenting out code ● explain the particular implementation or

implementation details● C-style format /*...*/ and one-line or end-of-

line format //

Page 36: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

36. Use C-style comments to hide code

37. Use one-line comments to explain implemen-tation details:● the purpose of variables or expressions● implementation-level design decisions● the source material for complex algorithms● defect fixes or workarounds● code that may benefit from optimization● known problems, limitations, or deficiencies.

Page 37: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

How to comment ?

Strive to minimize the need for embedded comments by writing code that documents itself.

Do not add comments that simply repeat what the code does.

Add comments only if they add useful information: Why does the code do what it does ? What does it do, if it is difficult to see ?

Page 38: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

double totalCost; // Used to total invoice....// Apply the discount to all invoices over $1000.if (totalCost > 1000.0) { // :TODO: Use constant?  // The discount is hard­coded because current  // customers all use the same discount rate.

  // We will need to replace this constant with a  // variable if we ever get a customer who needs  // a different rate, or one that wants to apply  // multiple discount rates!

  totalCost = totalCost * DISCOUNT;}

Page 39: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

64. Label closing } in highly nested loops

for (i...) {    for (j...) {        while (...) {            if (...) {                switch (...) {                ...                } // end switch            } // end if        } // end while    } // end for j} // end for i

Page 40: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

65. Label empty loops// Strip leading spaceswhile ((c = reader.read()) == SPACE);   // Empty!

Page 41: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Documentation conventions

66. Add a “fall-through” comment between two case labels if no break statement separates them

switch (command) {case FAST_FORWARD:

isFastForward = true;// Fall through!

case PLAY:case FORWARD:

isForward = true;break;...

}

Page 42: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Javadoc

● javadoc is a standard tool for creating html documentation

● documentation is generated from comments in java programs.

● comments are formatted in special style called doc comments:

/** * * */

Page 43: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Javadoc

Doc comments are subdivided into ● descriptions:overview of functionality● tags : specific fields of information: author,

version, parameter meaning, function return etc.

Page 44: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Javadoc

Page 45: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Javadoc

Page 46: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Javadoc

In eUML2, for a new class

In the main Eclipse menu, Project→ generate Javadoc...

inserts some tags

Page 47: Coding style€¦ ·  · 2013-11-05To read 4. Sample rules of a Java coding style 5. ... static final String XML_DOCUMENT = "text/XML"; ... and what (program entities) to comment

Javadoc

Go back to [Slides15], Javadoc section

These slides do not replace reading tech. reportHow to write comments for the Javadoc tool.