15-Jun-15 Style Consolidated Lectures. 2 About the book This book is a team effort by many good programmers, not just one person’s opinions The rules.

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

Tutorial 8: Developing an Excel Application
1-May-15 Style. 2 About the book This book is a team effort by many good programmers, not just one person’s opinions The rules have been widely distributed.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
15-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
16-Jun-15 javadoc. 2 Javadoc placement javadoc comments begin with /** and end with */ In a javadoc comment, a * at the beginning of the line is not part.
Style Rules II: Names and Naming. Overview Today we will discuss: –Reasons for naming conventions –Rules for naming variables, classes, and methods.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
18-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Style Rules I. Style is important Everyone agrees that good style is important –Everyone agrees on most of the essentials –But some people have “religious.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
26-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
1 Doc Comment Conventions. 2 Write for your audience Rule 32: Write documentation for– those who must use your code Users should not need to care how.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Algorithm Programming Coding Advices Bar-Ilan University תשס " ו by Moshe Fresko.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
1 Web Based Programming Section 6 James King 12 August 2003.
Programming Logic and Design Sixth Edition Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs.
(1) Coding Standards Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu HI
Java Language and SW Dev’t
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
School of Computer Science & Information Technology G6DICP - Lecture 9 Software Development Techniques.
Classes CS 21a: Introduction to Computing I First Semester,
By the end of this session you should be able to...
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
CIT 590 Intro to Programming First lecture on Java.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
23-Oct-15 Style. Why style matters Good style isn’t just to make your code “look pretty” The most critical factor in style is readability If a program.
Programming Fundamentals. Today’s Lecture Why do we need Object Oriented Language C++ and C Basics of a typical C++ Environment Basic Program Construction.
Introduction to programming in the Java programming language.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
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.
Self-Documenting Code Chapter 32. Kinds of Comments  Repeat of code  Explanation of code  Marker in code  Summary of code  Description of code’s.
BMTRY 789 Lecture 11: Debugging Readings – Chapter 10 (3 rd Ed) from “The Little SAS Book” Lab Problems – None Homework Due – None Final Project Presentations.
Asking the USER for values to use in a software 1 Input.
Code Conventions Tonga Institute of Higher Education.
Even More Java. Java Packages What is a package? Definition: A package is a grouping of related types providing access protection and name space management.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
CS116 COMPILER ERRORS George Koutsogiannakis 1. How to work with compiler Errors The Compiler provide error messages to help you debug your code. The.
Copyright © Curt Hill Flow of Control A Quick Overview.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
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.
Working with Java.
Loops BIS1523 – Lecture 10.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 2 Applications and Data.
Chapter 1: Computer Systems
Style 5-Dec-18.
Style 5-Dec-18.
CISC124 Labs start this week in JEFF 155.
Style 22-Feb-19.
Beginning Style 27-Feb-19.
Style 4-Apr-19.
Style 9-Apr-19.
Style 26-Apr-19.
Classes CS 21a: Introduction to Computing I
slides created by Ethan Apter
Presentation transcript:

15-Jun-15 Style Consolidated Lectures

2 About the book This book is a team effort by many good programmers, not just one person’s opinions The rules have been widely distributed and commented upon The rules reflect widespread and accepted practices And no, I don’t agree with everything in the book!

3 Rule 1: Adhere to the style of the original Consistent style is very important Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t like them Don’t try to establish “better” style rules It won’t work anyway There may be reasons you don’t know about If a project has mixed styles with no consistency, you might try to get people to agree on one

4 Rule 3: Do it right the first time You’re working on a large project, so you use good style......but you need a tool to help you do one little job, so you slap it together quickly Guess which program will be around longer and used by more people?

5 Rule 5: Indent nested code Always indent statements that are nested inside (under the control of) another statement if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost; } while (seconds > 0) { System.out.print(seconds + "..."); seconds = seconds - 1; } Indentation should be consistent throughout the program 2 to 4 spaces is usually about right

6 Rule 6: Break up long lines Scrolling a window horizontally is a pain! When you print on standard paper, long lines are either cut off or wrap in bad places I have long used a 72 character limit Some editors will show you a limit line The book provides good advice on how to break up long lines (read it!)

7 Rule 8: Don’t use “hard” tabs Once upon a time, you could depend on tab stops every eight character positions Today, every editor has its own idea of where and how to set tab stops If you change editors, your nice indentation gets ruined It’s worse if you use both tabs and spaces I have learned this one the hard way! A hard tab is an actual tab character in your text Good editors can be set to use soft tabs (your tab characters are replaced with spaces) BlueJ uses only soft tabs

8 Rule 9:Use meaningful names Names should be chosen very carefully, to indicate the purpose of a variable or method If the purpose changes, the variable or method should be renamed It is worthwhile spending a little time choosing the best name Long, multiword names are common in Java

9 Rule 10: Use familiar names Where common terminology exists, use it; don’t make up your own Example from the book: If your users refer to “customers,” your program should use the name Customer, not Client

10 Rule 11: Question excessively long names Variables should be used for a single purpose Methods should do one simple, clearly defined thing If a descriptive name is overly long, maybe the variable or method is trying to serve too many purposes

11 Meaningful names: exceptions I It is common practice to use i as the index of a for- loop, j as the index of an inner loop, and k as the index of a third-level loop This is almost always better than trying to come up with a meaningful name Example: for (int i = 1; i <= 10; i++) { for (int j = 1, j <= 10; j++) { System.out.println(" " + (i * j)); } }

12 Meaningful names: exceptions II Method variables may be given short, simple names, if: The purpose of the variable is obvious from context, and The variable is used only briefly, in a small part of the program But never use meaningless names for class or instance variables

13 Rule 28: Use standard names for “throwaway” variables If variables have no special meaning, you can use names that reflect their types For example, if you are writing a general method to work with any strings, you might name them string1, string2, etc. Alternatively, you can use very short names s, t, u, or s1, s2, etc. are often used for Strings p, q, r, s are often used for booleans w, x, y, z are often used for real numbers

14 Rule 12: Join the vowel generation Despite the cutesy name, this rule is important In more primitive languages, names were often limited to 8 or so characters This led to names like maxVolum and lngPlyng The usual rule was to leave out vowels, starting from the right Such names are harder to read and to remember Do not leave out vowels, or otherwise use unusual abbreviations, in Java!

15 Naming classes and interfaces Rule 18: Capitalize the first letter of each word, including the first: PrintStream, Person, ExemptEmployee Rule 19: Use nouns to name classes: ExemptEmployee, CustomerAccount Classes are supposed to represent things Rule 20: Use adjectives to name interfaces: Comparable, Printable Interfaces are supposed to represent features

16 Naming variables Rule 25: Capitalize the first letter of each word except the first: total, maxValue Rule 26: Use nouns to name variables: balance, outputLine Variables are supposed to represent values

17 Naming methods Rule 22: Capitalize the first letter of each word except the first: display, displayImage Methods are capitalized the same as variables Rule 23: Use verbs when naming methods: displayImage, computeBalance Methods are supposed to do something

18 Rule 13: Capitalize only the first letter in acronyms In names, write acronyms such as GUI and API as Gui and Api Examples: setDstOffset, displayAsHtml, loadXmlDocument Since capital letters are used to separate names, this rule helps avoid confusion Sun’s APIs don’t always follow this convention

19 Naming constants A constant is an identifier whose value, once given, cannot be changed Constants are written with the keyword final, for example: final int FIVE = 5; final float AVOGADROS_NUMBER = 6.022E23; Rule 31: Constants are written in ALL_CAPITALS, with underscores between words Exception: color names, such as Color.pink Colors were defined before conventions were established However, Java 1.4 adds properly capitalized names for colors, such as Color.PINK

20 Kinds of comments “Standard” (C-style) comments: /*... */ One-line and end-line comments: // a one-line comment is on a line by itself x = 0; // an end-line comment follows code All of the above are “internal” comments, seen only by someone looking at your code Internal comments are only for maintainers But avoid things that would embarrass you to a user! Documentation (javadoc) comments: /**... */ These are meant to be seen by the entire world! Documentation comments are not covered in this series of slides

21 Which kind of internal comment? Rule 36: Use “standard” (/*...*/) comments to comment out code without removing it. This is a quick way to comment out and uncomment code This rule isn’t actually appropriate for us BlueJ’s comment and uncomment commands make it easier to use one-line ( //... ) comments Standard comments cannot be nested, so it’s tricky commenting out code with comments One-line comments don’t have this problem

22 Explaining the code I Rule 59: Add internal comments only if they will aid in understanding your code. Don’t repeat the javadoc comments Don’t put in comments to explain things that are obvious from the code Don’t put in irrelevant or useless comments // Go Cubs!!!! Always put /*... */ comments before the code they describe, never after the code

23 Explaining the code II Rule 37: Use one-line comments to explain implementation details. One-line comments are also good for writing reminders for yourself about things you still need to work on // These assertions should be replaced by Exceptions I like to use one-line comments to tell what the next several lines of code are going to do // Put this Vehicle in a random location

24 End-line comments I Rule 61: Avoid the use of end-line comments. This rule is largely to prevent overly long lines But Rule 62 says: Explain local variable declarations with an end-line comment. int edgeDistance; // distance to the nearest edge And Rule 64 says: Label closing braces in highly nested control structures. } // end switch } // end if } // end for j } // end for i Better yet, avoid highly nested control structures

25 End-line comments II I also find end-line comments useful for an else that is a long way from its if : if (distance > 5) {... a lot of code in between... } else { // distance <= 5... } But now that we have assert statements, this is even better:... else { assert distance <= 5;

26 Flagging unresolved issues Rule 63: Establish and use a set of keywords to flag unresolved issues. I personally like to use $$ // $$ the canvas isn't being redrawn properly More specific flags are likely to be used in large projects // $$ DLM: Problem #1403; Level: Urgent

27 Intentionally missing break Rule 65: Add a “fall-through” comment between two case labels of a switch statement, if no break statement separates those labels. The switch statement is so badly designed that forgetting the break is a common error To keep an intentionally missing break from being “corrected,” add a comment

28 Label empty statements Sometimes you intentionally use a loop with an empty statement body Rule 66: Label empty statements. while ((c = reader.read()) == space) ; // Empty body  This is because the semicolon is small and easy to overlook I prefer a different solution: use an empty block as the statement body while ((c = reader.read()) == space) { }

29 Don’t repeat the code Rule 60: Describe why the code is doing what it does, not what the code is doing. Another way of saying this is: Comments should not echo code. Here’s a typical example of a bad comment: count = 0; // set count to zero You should assume that anyone reading your internal comments knows some Java!

30 Use the active voice Rule 34: Use the active voice, and omit needless words // zero out the array // each of the elements of the array is set to // zero by the following loop Writing comments is still writing--all the rules for good writing apply to comments Best reference: The Elements of Style, by Strunk and White

31 Debugging statements We sometimes put in debugging statements that we plan to remove afterwards Simple trick: start these “temporary” statements in the first column, so you can find them easily boolean legalLocation(int row, int col) { System.out.println("In legalLocation: " + row + " " + col); return row >= 0 && row = 0 && column < numCols; }

32 The End

33 The End