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

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

Classes  All code in a Java program is part of a class  A class has two purposes  Provide functions to do work for the programmer  Represent data.
1 CS1001 Lecture Overview Java Programming Java Programming.
Dale Roberts Introduction to Java - First Program Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Structure of a C program
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Outline Java program structure Basic program elements
A simple C++ program /* * This program prints the phrase "Hello world!" * on the screen */ #include using namespace std; int main () { cout
Chapter 2: Introduction to C++.
The Ruby Programming Language
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Java Language and SW Dev’t
Comments are for people Header comments supply basic information about the artifact.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Classes CS 21a: Introduction to Computing I First Semester,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Chapter 2: Java Fundamentals
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Documentation and Programming Style Appendix A © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Applications Development
Introduction to Java Java Translation Program Structure
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Agenda Comments Identifiers Keywords Syntax and Symentics Indentation Variables Datatype Operator.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
1 2. Program Construction in Java. 01 Java basics.
CS100Lecture 21 Announcements For homework due Thursday, work alone -- do not work in pairs New class location: Olin 155 Office hour oops! Lyn: MW, 11:15-12:15.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Working with Java.
Java Primer 1: Types, Classes and Operators
Java Methods /** * Chapter 5 */ Java Syntax and Style
CS180 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
University of Central Florida COP 3330 Object Oriented Programming
2.1 Parts of a C++ Program.
Chapter 1: Computer Systems
Java Methods /** * Chapter 5 */ Java Syntax and Style A & AB
Documentation and Style
Anatomy of a Java Program
Focus of the Course Object-Oriented Software Development
Chapter 2: Introduction to C++.
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Style Guidelines

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

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.

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

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

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

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!

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

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).

 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)

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

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

 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

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.

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++) { …….}

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

 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.

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

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

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.

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.

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.

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