Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code."— Presentation transcript:

1 Style Guidelines

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

3

4 Syntax  The compiler catches syntax errors and generates error messages.  Text in comments and literal strings within double quotes are excluded from syntax checking.  Before compiling, carefully read your code a couple of times to check for syntax and logic errors.

5 Syntax (cont’d)  Pay attention to and check for: matching braces { }, parentheses ( ), and brackets [ ] matching braces { }, parentheses ( ), and brackets [ ] missing and extraneous semicolons missing and extraneous semicolons correct symbols for operators correct symbols for operators +, -, =, <, <=, ==, ++, &&, etc. correct spelling of reserved words, library names and programmer-defined names, including case correct spelling of reserved words, library names and programmer-defined names, including case

6 Syntax (cont’d)  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

7 Style  Arrange code on separate lines; insert blank lines between fragments of code.  Use comments.  Indent blocks within braces.

8 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!

9 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

10 Blocks, Indentation  Java code consists mainly of declarations and control statements.  Declarations describe objects and methods.  Control statement describe actions.  Declarations and control statements end with a semicolon.  No semicolon is used after a closing brace (except certain array declarations).

11  Braces divide code into nested blocks.  A block in braces indicates a number of statements that form one compound statement.  Statements inside a block are indented, usually by two spaces or one tab. Blocks, Indentation (cont’d)

12 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; }

13 Standard Naming Conventions TYPECONVENTION Constant class variable containing an object Modified Title Case Constant class variable containing a fundamental type ( e.g. int) Upper case (multiple words separated by underscores) Interface names Title Case Class names Title Case Temporary variables Modified Title Case Class (static) variables Modified Title Case Method names Modified Title Case Instance variables Modified Title Case

14  Title Case Starts each word in a name with a capital letter, but does not include any spaces, under bars or other characters between the elements of a multiple word name. Starts each word in a name with a capital letter, but does not include any spaces, under bars or other characters between the elements of a multiple word name. ExamplesExamples Date, DayofTheWeek, AccountManager Date, DayofTheWeek, AccountManager  Modified Title Case Similar to Title Case, except that the first character of the name is always lowe case. Similar to Title Case, except that the first character of the name is always lowe case. ExamplesExamples today(), getNextElement(), totalNumberofInstances today(), getNextElement(), totalNumberofInstances

15 Blocks  The ‘{‘ starts a block of code and should be positioned at the end of the preceding line. The block should be indented 3 or 4 spaces and closed with a ‘}’ at the same level as that starting the block. Example Example for (int i=0; i < 10; i++) { System.out.println(i); System.out.println(i); getNextStudent(); getNextStudent();} *Blocks are not required after control statements, but it is recommended as good programming style.

16 Block Comments  Used to describe a group of related code.  Should be indented to match the indention of the line of code following it.  A single blank line should precede the comment and the block of code should follow immediately after. Example Example /* ******************************************** /* ******************************************** * 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++) { …….}

17 Naming Variables  Variable names such as t1, i, j, or temp should rarely be used (acceptable for temporary variables such as counters). Variable names should be descriptive or should indicate the type of object that the variable holds.  Instance and class variables tend to have semantic names. score, currentWorkingMemory, TotalPopulation score, currentWorkingMemory, TotalPopulation  Parameter names often use a typed variable name. aStudent, anObject aStudent, anObject

18  If the variable name is made up of more than one word, the words should not be separated by “-” or “_”, but by giving the first letter of all but the first word an initial capital (title case). employeeRecord, objectInList employeeRecord, objectInList  If a variable holds a single item, then that variable has a singular name. If a variable holds an array or collection of objects then use an appropriate plural.

19 Declaring variables  You can declare class and instance variables anywhere within the body of a class, however it is good style to declare them at the beginning.  You should initialize variables when you declare them.  Inline comments should be used to describe the purpose of variables private boolean flag; // used to indicate status private boolean flag; // used to indicate status

20 Naming Classes  The naming of classes is extremely important since the class is the core element in any object oriented program.  The name is used by most programmers to indicate the purpose or intent.  Use descriptive class names such as CheckingAccount or PrintSpooler and not names like MyClass or CounterOne

21 Naming Methods  A method name should always start with a lower case letter. If the name is made up of more than one element then each element after the first, should start with a capital letter (modified title case) account deposit(100); account deposit(100); account printStatement(); account printStatement();  Select a method name to illustrate the method’s purpose.

22 The Main Method  Should not be used to define the application program.  Should only do a few things: Create an instance of the class within which it is defined. Never create an instance of another class. Create an instance of the class within which it is defined. Never create an instance of another class. Send the newly created instance a message so that it initializes itself. Send the newly created instance a message so that it initializes itself. Send the newly created instance a message that triggers off the application’s behaviour. Send the newly created instance a message that triggers off the application’s behaviour.

23 Packages  A java package relates directly to a directory.  A package name should be in all lower case  A package name should always be singular (utility not utilities)  A package should contain related classes and interfaces.  See Style Guidelines document on teachers web.

24 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()); }


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

Similar presentations


Ads by Google