24
Style Style Guidelines Guidelines

Style Guidelines. Why do we need style? Good programming style helps promote the readability, clarity and comprehensibility of your code

Embed Size (px)

Citation preview

Page 1: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Style GuidelinesStyle Guidelines

Page 2: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Why do we need style?Why do we need style?Good programming style helps Good programming style helps

promote the readability, clarity promote the readability, clarity and comprehensibility of your and comprehensibility of your code.code.

Page 3: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

5-12

Syntax vs. Style

Syntax is part of the language. The compiler checks it.

Style is a convention widely adopted by software professionals.

The main purpose of style is to improve the readability of programs.

Page 4: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

SyntaxSyntax

The compiler catches syntax errors and The compiler catches syntax errors and generates error messages.generates error messages.

Text in comments and literal strings within Text in comments and literal strings within double quotes are excluded from syntax double quotes are excluded from syntax checking.checking.

Before compiling, carefully read your code a Before compiling, carefully read your code a couple of times to check for syntax and logic couple of times to check for syntax and logic errors.errors.

Page 5: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Syntax (cont’d)Syntax (cont’d)

Pay attention to and check for:Pay attention to and check for: matching braces matching braces { }{ }, parentheses , parentheses ( )( ), and brackets , and brackets [ ][ ] missing and extraneous semicolonsmissing and extraneous semicolons correct symbols for operatorscorrect symbols for operators

++, , --, , ==, , <<, , <=<=, , ====, , ++++, , &&&&, etc., etc. correct spelling of reserved words, library names and correct spelling of reserved words, library names and

programmer-defined names, including caseprogrammer-defined names, including case

Page 6: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Syntax (cont’d)Syntax (cont’d)

Common syntax errors:Common syntax errors:

Missing closing brace

Public static int abs (int x) { if (x < 0); { x = -x } return x;

public static int sign (int x) ...

Extraneous semicolon

Spelling (p P, if If)

Missing semicolon

Page 7: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

StyleStyle

Arrange code on separate lines; Arrange code on separate lines; insert blank lines between fragments insert blank lines between fragments of code.of code.

Use comments.Use comments.

Indent blocks within braces.Indent blocks within braces.

Page 8: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Style (cont’d)Style (cont’d)

public boolean moveDown(){if (cubeY<6*cubeX) {cubeY+=yStep; return true;}else return false;}

public boolean moveDown(){ if (cubeY < 6 * cubeX) { cubeY += yStep; return true; } else { return false; }}

Before: After:

Compiles fine!

Page 9: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Style (cont’d)Style (cont’d)

public void fill (char ch){ int rows = grid.length, cols = grid[0].length; int r, c;

for (r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { grid[r][c] = ch; } }}

Add blank lines for readability

Add spaces around operators and after semicolons

Page 10: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Blocks, IndentationBlocks, Indentation

Java code consists mainly of declarations Java code consists mainly of declarations and control statements.and control statements.

Declarations describe objects and methods.Declarations describe objects and methods.

Control statement describe actions.Control statement describe actions.

Declarations and control statements end with Declarations and control statements end with a semicolon.a semicolon.

No semicolon is used after a closing brace No semicolon is used after a closing brace (except certain array declarations).(except certain array declarations).

Page 11: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Braces divide code into nested blocks.Braces divide code into nested blocks.

A block in braces indicates a number of A block in braces indicates a number of statements that form one statements that form one compoundcompound statement.statement.

Statements inside a block are indented, Statements inside a block are indented, usually by two spaces or one tab.usually by two spaces or one tab.

Blocks, Indentation (cont’d)Blocks, Indentation (cont’d)

Page 12: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Blocks, Indentation (cont’d)Blocks, Indentation (cont’d)

public void fill (char ch) { int rows = grid.length, cols = grid[0].length; int r, c;

for (r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { grid[r][c] = ch; } } }

Page 13: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Standard Naming ConventionsStandard Naming ConventionsTYPETYPE CONVENTIONCONVENTIONConstant class variable Constant class variable containing an objectcontaining an object

Modified Title CaseModified Title Case

Constant class variable Constant class variable containing a fundamental type containing a fundamental type ( e.g. int)( e.g. int)

Upper case (multiple words separated Upper case (multiple words separated by underscores)by underscores)

Interface namesInterface names Title CaseTitle Case

Class namesClass names Title CaseTitle Case

Temporary variablesTemporary variables Modified Title CaseModified Title Case

Class (static) variablesClass (static) variables Modified Title CaseModified Title Case

Method namesMethod names Modified Title CaseModified Title Case

Instance variablesInstance variables Modified Title CaseModified Title Case

Page 14: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Title CaseTitle Case Starts each word in a name with a capital Starts each word in a name with a capital

letter, but does not include any spaces, under letter, but does not include any spaces, under bars or other characters between the bars or other characters between the elements of a multiple word name.elements of a multiple word name.• ExamplesExamples

Date, DayofTheWeek, AccountManagerDate, DayofTheWeek, AccountManager

Modified Title CaseModified Title Case Similar to Title Case, except that the first Similar to Title Case, except that the first

character of the name is always lowe case.character of the name is always lowe case.• ExamplesExamples

today(), getNextElement(), totalNumberofInstancestoday(), getNextElement(), totalNumberofInstances

Page 15: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

BlocksBlocks The ‘The ‘{{‘ starts a block of code and should be ‘ starts a block of code and should be

positioned at the end of the preceding line. The positioned at the end of the preceding line. The block should be indented 3 or 4 spaces and block should be indented 3 or 4 spaces and closed with a ‘closed with a ‘}}’ at the same level as that starting ’ at the same level as that starting the block.the block. ExampleExample

for (int i=0; i < 10; i++) for (int i=0; i < 10; i++) {{ System.out.println(i);System.out.println(i);

getNextStudent();getNextStudent();}}

*Blocks are not required after control statements, *Blocks are not required after control statements, but it is recommended as good programming but it is recommended as good programming style.style.

Page 16: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Block CommentsBlock Comments Used to describe a group of related code.Used to describe a group of related code. Should be indented to match the indention of the line of Should be indented to match the indention of the line of

code following it.code following it. A single blank line should precede the comment and the A single blank line should precede the comment and the

block of code should follow immediately after.block of code should follow immediately after. ExampleExample

/* ********************************************/* ******************************************** * Parse information from config file and * Parse information from config file and * assign to program variables.* assign to program variables.***********************************************************************************************/*/for (i = 0; i< NUM_FIELDS; i++) {for (i = 0; i< NUM_FIELDS; i++) {…………..}}

Page 17: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Naming VariablesNaming Variables

Variable names such as t1, i, j, or temp should Variable names such as t1, i, j, or temp should rarely be used (acceptable for temporary rarely be used (acceptable for temporary variables such as counters). Variable names variables such as counters). Variable names should be descriptive or should indicate the type should be descriptive or should indicate the type of object that the variable holds.of object that the variable holds.

Instance and class variables tend to have Instance and class variables tend to have semantic names.semantic names. score, currentWorkingMemory, TotalPopulationscore, currentWorkingMemory, TotalPopulation

Parameter names often use a typed variable Parameter names often use a typed variable name.name. aStudent, anObjectaStudent, anObject

Page 18: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

If the variable name is made up of more If the variable name is made up of more than one word, the words should not be than one word, the words should not be separated by “-” or “_”, but by giving the separated by “-” or “_”, but by giving the first letter of all but the first word an initial first letter of all but the first word an initial capital (title case).capital (title case). employeeRecord, objectInListemployeeRecord, objectInList

If a variable holds a single item, then that If a variable holds a single item, then that variable has a singular name. If a variable variable has a singular name. If a variable holds an array or collection of objects then holds an array or collection of objects then use an appropriate plural.use an appropriate plural.

Page 19: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Declaring variablesDeclaring variables

You can declare class and instance You can declare class and instance variables anywhere within the body of a variables anywhere within the body of a class, however it is good style to declare class, however it is good style to declare them at the beginning.them at the beginning.

You should initialize variables when you You should initialize variables when you declare them.declare them.

Inline comments should be used to Inline comments should be used to describe the purpose of variablesdescribe the purpose of variables private boolean flag; // used to indicate statusprivate boolean flag; // used to indicate status

Page 20: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Naming ClassesNaming Classes

The naming of classes is extremely The naming of classes is extremely important since the class is the core important since the class is the core element in any object oriented program.element in any object oriented program.

The name is used by most programmers The name is used by most programmers to indicate the purpose or intent.to indicate the purpose or intent.

Use descriptive class names such as Use descriptive class names such as CheckingAccount or PrintSpooler and not CheckingAccount or PrintSpooler and not names like MyClass or CounterOnenames like MyClass or CounterOne

Page 21: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

Naming MethodsNaming Methods

A method name should always start with a A method name should always start with a lower case letter. If the name is made up lower case letter. If the name is made up of more than one element then each of more than one element then each element after the first, should start with a element after the first, should start with a capital letter (modified title case)capital letter (modified title case) account deposit(100);account deposit(100); account printStatement();account printStatement();

Select a method name to illustrate the Select a method name to illustrate the method’s purpose.method’s purpose.

Page 22: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

The Main MethodThe Main Method

Should not be used to define the Should not be used to define the application program.application program.

Should only do a few things:Should only do a few things: Create an instance of the class within which it Create an instance of the class within which it

is defined. Never create an instance of is defined. Never create an instance of another class.another class.

Send the newly created instance a message Send the newly created instance a message so that it initializes itself.so that it initializes itself.

Send the newly created instance a message Send the newly created instance a message that triggers off the application’s behaviour.that triggers off the application’s behaviour.

Page 23: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

PackagesPackages

A java package relates directly to a directory.A java package relates directly to a directory. A package name should be in all lower caseA package name should be in all lower case A package name should always be singular A package name should always be singular

(utility not utilities)(utility not utilities) A package should contain related classes and A package should contain related classes and

interfaces.interfaces. See Style Guidelines document on teachers See Style Guidelines document on teachers

web.web.

Page 24: Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code

package sample;import robocode.*;/** * MyFirstRobot - a sample robot by Mathew Nelson * * Moves in a seesaw motion, and spins the gun around at each end */public class MyFirstRobot extends Robot{ /** * MyFirstRobot's run method - Seesaw */ public void run() { while (true) { ahead(100); // Move ahead 100 turnGunRight(360); // Spin gun around back(100); // Move back 100 turnGunRight(360); // Spin gun around } }

/*************************************************************************************************** * Fire when we see a robot * ************************************************************************************************* */ public void onScannedRobot(ScannedRobotEvent e) { fire(1); }

/** * We were hit! Turn perpendicular to the bullet, * so our seesaw might avoid a future shot. */ public void onHitByBullet(HitByBulletEvent e) { turnLeft(90 - e.getBearing()); }}