Widely used guidance for writing better code.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Chapter 1: Computer Systems
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
1 Web Based Programming Section 6 James King 12 August 2003.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Java Language and SW Dev’t
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Writing JavaDocs Mimi Opkins CECS 274 Copyright (c) Pearson All rights reserved.
The Java Programming Language
Announcements  If you need more review of Java…  I have lots of good resources – talk to me  Use “Additional Help” link on webpage.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Java Coding Standards and Best Practices Coding Standards Introduction: After completing this chapter, you will able to keep your code up to standards.
Best Practices. Contents Bad Practices Good Practices.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC 212 – Data Structures Prof. Matthew Hertz WTC 207D /
Page 1 – Autumn 2009Steffen Vissing Andersen SDJ I1, Autumn 2009 Agenda: Java API Documentation Code Documenting (in javadoc format) Debugging.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
Sit-In Lab 2 - OOP Restaurant.  Manage a restaurant and perform these types of queries: Assign a favorite table to a specific group Assign the lexicographically-smallest.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Refactoring. DCS – SWC 2 Refactoring ”A change made to the internal structure of software to make it easier to understand and cheaper to modify without.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Programming Fundamentals. Today’s Lecture Array Fundamentals Arrays as Class Member Data Arrays of Objects C-Strings The Standard C++ string Class.
Chapter 2 Wrap Up 2/18/16 & 2/22/16. Topics Review for Exam I DecimalFormat More Style Conventions Debugging using eclipse The Java API.
Winter 2006CISC121 - Prof. McLeod1 Stuff We had better discuss a midterm date… –27 Feb. to 3 March or –6 to 10 March.
© 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.
Information and Computer Sciences University of Hawaii, Manoa
The need for Programming Languages
A variable is a name for a value stored in memory.
Working with Java.
C++ coding standard suggestion… Separate reasoning from action, in every block. Hi, this talk is to suggest a rule (or guideline) to simplify C++ code.
Variables and Arithmetic Operators in JavaScript
Exercise on Java Basics
Coding Standard & Javadoc
Exercise on Java Basics
Software Testing and Maintenance Modifying Code
Variables and Arithmetic Operators in JavaScript
Winter 2018 CISC101 11/27/2018 CISC101 Reminders
slides created by Ethan Apter
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Chapter 1: Computer Systems
slides created by Ethan Apter
Recap Week 2 and 3.
CSE 143 Lecture 4 More ArrayIntList:
Focus of the Course Object-Oriented Software Development
JAVA CLASSES.
Object Comparisons and Arrays
Final Jim Brucker.
Suggested self-checks: Section 7.11 #1-11
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Primitive Data Types and Operations
Variables in C Topics Naming Variables Declaring Variables
slides created by Ethan Apter and Marty Stepp
Presentation transcript:

Widely used guidance for writing better code. Coding Guidelines Widely used guidance for writing better code.

Guidelines 1. Code should be easy to read. 2. Be consistent in naming and formatting. 3. Use comments where helpful. Explain & document code. Write Javadoc. 4. Avoid duplicate logic and duplicate code (DRY). 5. Localize variables. 6. No magic numbers. 7. Treat warnings like errors.

Why? 1. Help write correct code. 2. Easy to modify or update. Easy to Read -> fewer bugs No duplicate code -> no inconsistencies 2. Easy to modify or update. 3. Code that others can understand. If they don't understand it, they won't use it. 4. Reusable.

Code should be easy to read 1. Use a coding standard for names and formatting. 2. Use descriptive variable & method names: Good: gameBoard, player, piece, moveTo( Piece, x, y) Bad: b, play, pc, mv( Piece, x, y) 3. Prefer simple expressions to complex ones. 4. Use space around operators (except "." and a[index]). Bad: if(x<0||x>=board.width)return false; Good: if (x < 0 || x >= board.width) return 5. Add space between methods: 1 blank line.

Do you understand this code? Write comments! Use meaningful variable names Follow a formatting convention public Coin[] withdraw(double x) { int t=Math.min(x/10,tens); x -= t*10; int f=Math.min(x/5,fives); x -= f*5; int o=Math.min(o,ones); x -= o*1; if (x==0) return getCoins(t,f,o); else return null; }

Use Comments to Explain "why" Good comments help reader understand the code public void paint(Graphic g) { // create a copy of g so we can change it // this is recommended by Swing g = g.create(); Bad comments just state the obvious // if the piece is null then return if (piece == null) return; // add all the scores in list int total = scores.stream( ).sum( );

Leave Vertical Space (blank line) Blank lines help you divide a long code into its components. Compare this code with the next slide. class Banknote { private double value; private String currency; public Banknote(double value, String currency) { this.value = value; this.currency = currency; } public int compareTo(Banknote other) { if ( !other.currency.equals(this.currency)) return currency.compareTo(other.currency); return Double.compare(this.value,other.value); public String toString() { return String.format("%f %s note",value,currency); ...

Code with Vertical Space Which version is easier to understand? class Banknote { private double value; private String currency; public Banknote(double value, String currency) { this.value = value; this.currency = currency; } public int compareTo(Banknote other) { if ( !other.currency.equals(this.currency)) return currency.compareTo(other.currency); return Double.compare(this.value,other.value); public String toString() { return String.format("%f %s note",value,currency);

4. Avoid Duplicate Code & Logic Both of these constructors do nearly the same thing... /** Initialize a new Banknote with default currency. */ public Banknote(double amount) { if (amount <= 0) throw new IllegalArgumentException(); this.amount = amount; this.currency = DEFAULT_CURRENCY; this.serialNumber = getNextSerialNumber(); } /** Initialize a Banknote with given currency. */ public Banknote(double amount, String currency) { this.currency = currency;

this( ) - call another constructor Remove duplication. Let one constructor call the other constructor. /** Initialize a new Banknote with default currency. */ public Banknote(double amount) { this(amount, DEFAULT_CURRENCY); } /** Initialize a Banknote with given currency. */ public Banknote(double amount, String currency) { if (amount <= 0) throw new IllegalArgumentException(); this.amount = amount; this.currency = currency; this.serialNumber = getNextSerialNumber();

duplicate code that's hard to read /** Read words from inputStream & count words by length. */ Map<Character,Integer> map = new HashMap<Character,Integer>(); Scanner in = new Scanner(inputStream); while(in.hasNext()){ String word = in.nextLine(); if(map.containsKey(word.charAt(0))){ map.put(word.charAt(0),map.get(word.charAt(0))+1); } else{ map.put(word.charAt(0),1); What is duplicate (used many times) in this code?

use a variable to avoid redundant method call /** Read words from inputStream & count words by length. */ Map<Character,Integer> map = new HashMap<Character,Integer>(); Scanner in = new Scanner(inputStream); while (in.hasNext()) { String word = in.nextLine(); char firstChar = word.charAt(0); if ( map.containsKey(firstChar) ) { map.put(firstChar, map.get(firstChar)+1); } else { map.put(firstChar, 1); and add space for readability!

add explanatory variable (count) /** Read words from inputStream & count words by length. */ Map<Character,Integer> map = new HashMap<Character,Integer>(); Scanner in = new Scanner(inputStream); while (in.hasNext()) { String word = in.nextLine(); char firstChar = word.charAt(0); int count = 0; // number of times this char was seen if ( map.containsKey(firstChar) ) { count = map.get(firstChar); } map.put(firstChar, count+1);

Use the API: get -> getOrDefault /** Read words from inputStream & count words by length. */ Map<Character,Integer> map = new HashMap<Character,Integer>(); Scanner in = new Scanner(inputStream); while (in.hasNext()) { String word = in.nextLine(); char firstChar = word.charAt(0); // get the character count or 0 if char not seen yet int count = map.getOrDefault(firstChar, 0); // add the current word to the frequency count map.put(firstChar, count+1); }

Let Eclipse do it for you "Define a variable" is an example of refactoring. 1) select expression you want to define as variable: word.charAt(0) 2) From menubar (or right-click): Refactor -> Extract Local Variable...

Anticipate and avoid errors /** Read words from inputStream & count words by length. */ Map<Character,Integer> map = new HashMap<Character,Integer>(); Scanner in = new Scanner(inputStream); while (in.hasNext()) { String word = in.nextLine(); char firstChar = word.charAt(0); // get the character count or 0 if char not seen yet int count = map.getOrDefault(firstChar, 0); // update the frequency count for the new word map.put(firstChar, count+1); } What could go wrong here?

(1) blank line or (2) starts with space /** Read words from inputStream & count words by length. */ Map<Character,Integer> map = new HashMap<Character,Integer>(); Scanner in = new Scanner(inputStream); while (in.hasNext()) { String word = in.nextLine().trim(); if ( word.isEmpty() ) continue; // skip blank lines char firstChar = word.charAt(0); // get the character count or 0 if char not seen yet int count = map.getOrDefault(firstChar, 0); // update the frequency count for the new word map.put(firstChar, count+1); }

Avoid Duplicate Logic /** Insert money if the purse is not full. */ public boolean insert(Valuable obj) { if (money.size() == capacity) return false; return money.add(obj); } Avoid duplicate logic and make the intention clear: public boolean insert(Valuable obj) { if ( isFull() ) return false; return money.add(obj); }

Anticipate and avoid errors What if (somehow) the purse contains more than capacity? /** Test if the purse is full or not. */ public boolean isFull( ) { return (money.size() == capacity); } public boolean isFull( ) { return (money.size() >= capacity); }

Use the smallest possible scope 5. Localize variables Use the smallest possible scope use attributes only for things that are part of object's state minimize sharing of information between methods public class Purse { List<Coin> items; int balance; public int getBalance( ) { balance = 0; for(Coin c: items) balance += c.getValue(); return balance; }

Localize variables balance is only needed in getBalance, so it should be local. won't fail if 2 threads call getBalance() simultaneously public class Purse { List<Coin> items; public int getBalance( ) { int balance = 0; for(Coin c: items) balance += c.getValue(); return balance; }

Localize scope as much as possible don't define a variable until you need it. public class CoinMachine { List<Coin> items; public int getBalance( ) { int balance = 0; for(Coin c: items) balance += c.getValue(); return balance; }

Avoid Magic Numbers Use NAMED CONSTANTS for special values. public double getElapsed() { return (stopTime - startTime) * 1.0E-9; // Bad } /** conversion from nanoseconds to seconds */ static final double NANOSECONDS = 1.0E-9; // Good public double getElapsed() { return (stopTime - startTime) * NANOSECONDS; }

Avoid Magic Strings, too public class Coin { public Coin(double value) { this.valiue = value; this.currency = "Baht"; //BAD } public class Coin { public static final String DEFAULT_CURRENCY = "Baht"; //GOOD public Coin(double value) { this.valiue = value; this.currency = DEFAULT_CURRENCY; }

Treat Warnings Like Errors Try to eliminate all the warnings in Eclipse or IntelliJ. Eclipse: Close unrelated projects so you only see problems for this project.

References Steve McConnell, Code Complete, 2nd Edition. Robert Martin, Clean Code. http://www.unclebob.com - Robert Martin's blog