Designing and Writing a Program DESIGNING, CODING, AND DOCUMENTING. The Design-Code-Debug Cycle. Divide and Conquer! Documentation is Code



Similar documents
Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

Dinopolis Java Coding Convention

Software Engineering Techniques

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Structural Design Patterns Used in Data Structures Implementation

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

Design Patterns. Advanced Software Paradigms (A. Bellaachia) 1

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Software Construction

CS 111 Classes I 1. Software Organization View to this point:

Outline. 1 Denitions. 2 Principles. 4 Implementation and Evaluation. 5 Debugging. 6 References

ABSTRACT FACTORY AND SINGLETON DESIGN PATTERNS TO CREATE DECORATOR PATTERN OBJECTS IN WEB APPLICATION

A Meeting Room Scheduling Problem

Génie Logiciel et Gestion de Projets. Patterns

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

Web Application Development for the SOA Age Thinking in XML

Contents. Introduction and System Engineering 1. Introduction 2. Software Process and Methodology 16. System Engineering 53

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

Specialized Programme on Web Application Development using Open Source Tools

Java (12 Weeks) Introduction to Java Programming Language

Java Application Developer Certificate Program Competencies

Specialized Programme on Web Application Development using Open Source Tools

Design by Contract beyond class modelling

CS193j, Stanford Handout #10 OOP 3

MiniDraw Introducing a framework... and a few patterns

CSE 308. Coding Conventions. Reference

Computing Concepts with Java Essentials

One of the fundamental kinds of Web sites that SharePoint 2010 allows

REST Client Pattern. [Draft] Bhim P. Upadhyaya ABSTRACT

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

How To Design Your Code In Php (Php)

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Input Output. 9.1 Why an IO Module is Needed? Chapter 9

Moving from CS 61A Scheme to CS 61B Java

Stack Allocation. Run-Time Data Structures. Static Structures

Software Documentation Guidelines

Announcement. SOFT1902 Software Development Tools. Today s Lecture. Version Control. Multiple iterations. What is Version Control

Syllabus for CS 134 Java Programming

How To Write A Test Engine For A Microsoft Microsoft Web Browser (Php) For A Web Browser For A Non-Procedural Reason)

Endo-Testing: Unit Testing with Mock Objects

Computer Programming I

Adapting C++ Exception Handling to an Extended COM Exception Model

Java SE 8 Programming

Software documentation systems

Hypercosm. Studio.

Chapter 12 Programming Concepts and Languages

Java Programming Language

To Java SE 8, and Beyond (Plan B)

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

AP Computer Science Java Subset

CSCI E 98: Managed Environments for the Execution of Programs

Programming Methods & Java Examples

Making a Web Page with Microsoft Publisher 2003

Curriculum Map. Discipline: Computer Science Course: C++

Chain of Responsibility

Assignment # 2: Design Patterns and GUIs

History OOP languages Year Language 1967 Simula Smalltalk

Glossary of Object Oriented Terms

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Approach of Unit testing with the help of JUnit

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

AP Computer Science AB Syllabus 1

Programming Project 1: Lexical Analyzer (Scanner)

So we thought we knew money

Code Qualities and Coding Practices

Syntax Check of Embedded SQL in C++ with Proto

CSC408H Lecture Notes

by Jonathan Kohl and Paul Rogers 40 BETTER SOFTWARE APRIL

Software Development (CS2500)

Using Karel with Eclipse

Agile Software Development

Web Presentation Layer Architecture

Large Scale Systems Design G52LSS

ios Design Patterns Jackie Myrose CSCI 5448 Fall 2012

Web Frameworks. web development done right. Course of Web Technologies A.A. 2010/2011 Valerio Maggio, PhD Student Prof.

Microsoft Expression Web Quickstart Guide

Basic tutorial for Dreamweaver CS5

A Pattern for Designing Abstract Machines

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Reuse in Oracle SOA Suite 12c: Templates, Libraries or Services?

New Generation of Software Development

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Writing in the Computer Science Major

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

How To Write A Design Document For Anorexic Css

The first program: Little Crab

Ontological Representations of Software Patterns

Service Oriented Architectures

Transcription:

Designing and Writing a Program DESIGNING, CODING, AND DOCUMENTING Lecture 16 CS2110 Spring 2013 2 Don't sit down at the terminal immediately and start hacking Design stage THINK first about the data you are working with about the operations you will perform on it about data structures you will use to represent it about how to structure all the parts of your program so as to achieve abstraction and encapsulation Coding stage code in small bits test as you go understand preconditions and postconditions insert sanity checks (assert statements in Java are good) worry about corner cases Use Java API to advantage The Design-Code-Debug Cycle Divide and Conquer! 3 Design is faster than debugging (and more fun) extra time spent designing reduces coding and debugging Which is better? design code debug 4 Break program into manageable parts that can be implemented, tested in isolation Define interfaces for parts to talk to each other develop contracts (preconditions, postconditions) design code debug Actually, should be more like this: Make sure contracts are obeyed Clients use interfaces correctly Implementers implement interfaces correctly (test!) Key: good interface documentation Pair Programming Documentation is Code 5 Work in pairs Pilot/copilot pilot codes, copilot watches and makes suggestions pilot must convince copilot that code works take turns Or: work independently on different parts after deciding on an interface frequent design review each programmer must convince the other reduces debugging time Test everything 6 Comments (esp. specifications) are as important as the code itself determine successful use of code determine whether code can be maintained creation/maintenance = 1/10 Documentation belongs in code or as close as possible Code evolves, documentation drifts away Put specs in comments next to code when possible Separate documentation? Code should link to it. Avoid useless comments x = x + 1; //add one to x -- Yuck! Need to document algorithm? Write a paragraph at the top. Or break method into smaller, clearer pieces. 1

Javadoc 7 An important Java documentation tool Java source code (many files) javadoc Linked HTML web pages Extracts documentation from classes, interfaces Requires properly formatted comments Produces browsable, hyperlinked HTML web pages 8 How Javadoc is Produced Some Useful Javadoc Tags 9 indicates Javadoc comment /** * Constructs an empty <tt>hashmap</tt> with the specified initial * capacity and the default load factor (0.75). * Javadoc keywords * @param initialcapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ public HashMap(int initialcapacity) { this(initialcapacity, DEFAULT_LOAD_FACTOR); can include HTML /** * Constructs an empty <tt>hashmap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadfactor = DEFAULT_LOAD_FACTOR; threshold = (int)(default_initial_capacity * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); 10 @return description Use to describe the return value of the method, if any E.g., @return the sum of the two intervals @param parameter-name description Describes the parameters of the method E.g., @param i the other interval @author name @deprecated reason @see package.class#member {@code expression Puts expression in code font Developing and Documenting an ADT 1. Writing an ADT Overview 11 1. Write an overview purpose of the ADT 2. Decide on a set of supported operations 12 Example abstraction: a closed interval [a,b] on the real number line [a,b] = { x a x y Example overview: 3. Write a specification for each operation /** * An Interval represents a closed interval [a,b] * on the real number line. */ Abstract Javadoc comment description of the ADT s values 2

2. Identify the Operations 3. Writing Method Specifications 13 14 Enough operations for needed tasks Avoid unnecessary operations keep it simple! Don t include operations that client (without access to internals of class) can implement Include Signature: types of method arguments, return type Description of what the method does (abstractly) Good description (definitional) /** Add two intervals. The sum of two intervals is * a set of values containing all possible sums of * two values, one from each of the two intervals. */ public Interval plus(interval i); Bad description (operational) /** Return a new Interval with lower bound a+i.a, * upper bound b+i.b. Not abstract, */ might as well public Interval plus(interval i); read the code 3. Writing Specifications (cont d) Know Your Audience 15 Attach before methods of class or interface /** Add two intervals. The sum of two intervals is * a set of values containing all possible sums of * two values, one from each of the two intervals. * * @param i the other interval * @return the sum of the two intervals */ Method overview Method description Additional tagged clauses 16 Code and specs have a target audience the programmers who will maintain and use it Code and specs should be written With enough documented detail so they can understand it While avoiding spelling out the obvious Try it out on the audience when possible design reviews before coding code reviews Consistency Simplicity 17 A foolish consistency is the hobgoblin of little minds Emerson 18 The present letter is a very long one, simply because I had no time to make it shorter. Blaise Pascal Pick a consistent coding style, stick with it Make your code understandable by little minds Be brief. Strunk & White Teams should set common style Match style when editing someone else s code Not just syntax, also design style Applies to programming simple code is Easier and quicker to understand More likely to be correct Good code is simple, short, and clear Save complex algorithms, data structures for where they are needed Always reread code (and writing) to see if it can be made shorter, simpler, clearer 3

Choosing Names Avoid Copy-and-Paste 19 Don t try to document with variable names Longer is not necessarily better 20 Biggest single source of program errors Bug fixes never reach all the copies Think twice before using edit copy-and-paste function int searchforelement( int[] array_of_elements_to_search, int element_to_look_for); ^V int search(int[] a, int x); Names should be short but suggestive Local variable names should be short Abstract instead of copying! Write many calls to a single function rather than copying the same block of code around But sometimes you have no choice Design vs Programming by Example 21 Example: SWING or SWT GUI code Realistically, you simply have to use cut-and-paste! In such situations, do try to understand what you copied and make it your own They wrote it first But now you ve adopted it and will love it and care for it maybe even rewrite it 22 Programming by example: copy code that does something like what you want hack it until it works Problems: inherit bugs in code don't understand code fully usually inherit unwanted functionality code is a bolted-together hodge-podge Alternative: design understand exactly why your code works reuse abstractions, not code templates Avoid Premature Optimization Avoid Duplication 23 Temptations to avoid Copying code to avoid overhead of abstraction mechanisms Using more complex algorithms & data structures unnecessarily Violating abstraction barriers Result: Less simple and clear Performance gains often negligible Avoid trying to accelerate performance until You have the program designed and working You know that simplicity needs to be sacrificed You know where simplicity needs to be sacrificed 24 Duplication in source code creates an implicit constraint to maintain, a quick path to failure Duplicating code fragments (by copying) Duplicating specs in classes and in interfaces Duplicating specifications in code and in external documents Duplicating same information on many web pages Solutions: Named abstractions (e.g., declaring functions) Indirection (linking pointers) Generate duplicate information from source (e.g., Javadoc!) If you must duplicate: Make duplicates link to each other so can find all clones 4

25 Maintain State in One Place Often state is duplicated for efficiency But difficult to maintain consistency Atomicity is the issue if the system crashes while in the middle of an update, it may be left in an inconsistent state difficult to recover 26 Error Handling It is usually an afterthought it shouldn t be User errors vs program errors there is a difference, and they should be handled differently Insert lots of sanity checks the Java assert statement is good way to do this Avoid meaningless messages 27 Avoid Meaningless Messages 28 Introduced in 1994 by Gamma, Helm, Johnson, Vlissides (the Gang of Four ) Identified 23 classic software design patterns in OO programming More than 1/2 million copies sold in 14 languages 29 30 Abstract Factory groups object factories that have a common theme. Builder constructs complex objects by separating construction and representation. Factory Method creates objects without specifying the exact class to create. Prototype creates objects by cloning an existing object. Singleton restricts object creation for a class to only one instance. Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class. Bridge decouples an abstraction from its implementation so that the two can vary independently. Composite composes one-or-more similar objects so that they can be manipulated as one object. Decorator dynamically adds/overrides behaviour in an existing method of an object. Facade provides a simplified interface to a large body of code. Flyweight reduces the cost of creating and manipulating a large number of similar objects. Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity. Chain of responsibility delegates commands to a chain of processing objects. Command creates objects which encapsulate actions and parameters. Interpreter implements a specialized language. Iterator accesses the elements of an object sequentially without exposing its underlying representation. Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods. Memento provides the ability to restore an object to its previous state (undo). Observer is a publish/subscribe pattern that allows a number of observer objects to see an event. State allows an object to alter its behavior when its internal state changes. Strategy allows one of a family of algorithms to be selected on-the-fly at runtime. Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior. Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object. 5

Observer Pattern 31 32 Chain of responsibility delegates commands to a chain of processing objects. Command creates objects which encapsulate actions and parameters. Interpreter implements a specialized language. Iterator accesses the elements of an object sequentially without exposing its underlying representation. Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods. Memento provides the ability to restore an object to its previous state (undo). Observer is a publish/subscribe pattern that allows a number of observer objects to see an event. State allows an object to alter its behavior when its internal state changes. Strategy allows one of a family of algorithms to be selected on-the-fly at runtime. Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior. Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object. Observable changes from time to time is aware of Observers, other entities that want to be informed when it changes but may not know (or care) what or how many Observers there are Observer interested in the Observable want to be informed when the Observable changes Observer Pattern Observer Pattern 33 Issues does the Observable push information, or does the Observer pull it? (e.g., email vs newsgroup) whose responsibility is it to check for changes? publish/subscribe paradigm Observable 34 public interface Observer<E> { void update(e event); public class Observable<E> { private Set<Observer<E>> observers = new HashSet<Observer<E>>(); boolean changed; void addobserver(observer<e> obs) { observers.add(obs); void removeobserver(observer<e> obs) { observers.remove(obs); Observers void notifyobservers(e event) { if (!changed) return; changed = false; for (Observer<E> obs : observers) { obs.update(event); 35 Visitor Pattern A data structure provides a generic way to iterate over the structure and do something at each element The visitor is an implementation of interface methods that are called at each element The visited data structure doesn t know (or care) what the visitor is doing There could be many visitors, all doing different things Visitor Pattern 36 public interface Visitor<T> { void visitpre(t datum); void visitin(t datum); void visitpost(t datum); public class TreeNode<T> { TreeNode<T> left; TreeNode<T> right; T datum; TreeNode(TreeNode<T> l, TreeNode<T> r, T d) { left = l; right = r; datum = d; void traverse(visitor<t> v) { v.visitpre(datum); if (left!= null) left.traverse(v); v.visitin(datum); if (right!= null) right.traverse(v); v.visitpost(datum); 6

No Silver Bullets 37 These are all rules of thumb; but there is no panacea, and every rule has its exceptions You can only learn by doing we can't do it for you Following software engineering rules only makes success more likely! 7