CSE 331 Software Design & Implementation

Similar documents
Design patterns (part 2) CSE 331 Spring 2010

Design patterns (part 2)

CSE 331 Software Design & Implementation

Design patterns (part 3)

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation

Design Patterns Maria Zontak

Outline. Design Patterns, cont. Wrappers. Adapter Pattern. Based on material by Michael Ernst, University of Washington

CSE 401/M501 Compilers

CS 4120 Introduction to Compilers

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

Design Patterns. Visitor Pattern. Hans Vangheluwe and Alexandre Denault

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 2. Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 4

CSE 431S Type Checking. Washington University Spring 2013

What are the characteristics of Object Oriented programming language?

Section 10: Design Patterns 2

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns

Semantic analysis. Compiler Construction. An expression evaluator. Examples of computations. Computations on ASTs Aspect oriented programming

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Section 9: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CS558 Programming Languages

CSE 70 Final Exam Fall 2009

David Talby March 21, 2006

THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS

Section 8: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

.jj file with actions

Design Patterns in C++

CS 520 Theory and Practice of Software Engineering Fall 2018

Visitors. Move functionality

CS 520 Theory and Practice of Software Engineering Fall 2017

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Introduction to Programming Using Java (98-388)

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Section 9: Design Patterns. Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst

Operators and Expressions

Composite Pattern. IV.4 Structural Pattern

CSE 504: Compiler Design. Runtime Environments

CSE wi Final Exam 3/12/18. Name UW ID#

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Type Analysis. Type Checking vs. Type Inference

6.170 Lecture 15 Design Patterns

Defining Classes and Methods

Design Pattern and Software Architecture: IV. Design Pattern

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Visitor Pattern CS356 Object-Oriented Design and Programming November 5, 2014 Yu Sun, Ph.D.

2. The object-oriented paradigm!

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CPS2000 Compiler Theory & Practice

Design Patterns Revisited

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

J&: Nested Intersection for Scalable Software Composition

Tecniche di Progettazione: Design Patterns

Chapter 2 A Quick Tour

Design Patterns: State, Bridge, Visitor

ITI Introduction to Computing II

The Strategy Pattern Design Principle: Design Principle: Design Principle:

Exam in TDDB84: Design Patterns,

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan

The Lorax Programming Language

The Visitor Pattern. Design Patterns In Java Bob Tarr

CSE 12 Abstract Syntax Trees

INSTITUTE OF AERONAUTICAL ENGINEERING

More On Syntax Directed Translation

Software Engineering I (02161)

Sri Vidya College of Engineering & Technology

CSE341: Programming Languages Lecture 22 OOP vs. Functional Decomposition; Adding Operators & Variants; Double-Dispatch. Dan Grossman Autumn 2018

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

ITI Introduction to Computing II

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Structured Programming

Design Patterns. Lecture 10: OOP, autumn 2003

What are patterns? Design Patterns. Design patterns. Creational patterns. The factory pattern. Factory pattern structure. Lecture 10: OOP, autumn 2003

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester

Today. Assignments. Lecture Notes CPSC 326 (Spring 2019) Operator Associativity & Precedence. AST Navigation. HW4 out (due next Thurs)

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

Compilers Project 3: Semantic Analyzer

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Types II. Hwansoo Han

Object-oriented Compiler Construction

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Liskov Substitution Principle

2.2 Syntax Definition

Object Oriented Programming and Design in Java. Session 10 Instructor: Bert Huang

Design Patterns Reid Holmes

CSE wi Final Exam 3/12/18 Sample Solution

CMSC 132: Object-Oriented Programming II

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

drawobject Circle draw

COURSE 2 DESIGN PATTERNS

Data Structures (list, dictionary, tuples, sets, strings)

Transcription:

CSE 331 Software Design & Implementation Hal Perkins Winter 2018 Design Patterns, Part 2 1

Outline ü Introduction to design patterns ü Creational patterns (constructing objects) Þ Structural patterns (controlling heap layout) Behavioral patterns (affecting object semantics) 2

Structural patterns: Wrappers A wrapper translates between incompatible interfaces Wrappers are a thin veneer over an encapsulated class Modify the interface Extend behavior Restrict access The encapsulated class does most of the work Pattern Functionality Interface Adapter same different Decorator different same Proxy same same Some wrappers have qualities of more than one of adapter, decorator, and proxy 3

Adapter Change an interface without changing functionality Rename a method Convert units Implement a method in terms of another Example: angles passed in radians vs. degrees Example: use old method names for legacy code 4

Adapter example: scaling rectangles We have this Rectangle interface interface Rectangle { // grow or shrink this by the given factor void scale(float factor);... float getwidth(); float area(); Goal: client code wants to use this library to implement Rectangle without rewriting code that uses Rectangle: class NonScaleableRectangle { // not a Rectangle void setwidth(float width) {... void setheight(float height) {... // no scale method... 5

Adapter: Use subclassing class ScaleableRectangle1 extends NonScaleableRectangle implements Rectangle { void scale(float factor) { setwidth(factor * getwidth()); setheight(factor * getheight()); 6

Adapter: use delegation Delegation: forward requests to another object class ScaleableRectangle2 implements Rectangle { NonScaleableRectangle r; ScaleableRectangle2(float w, float h) { this.r = new NonScaleableRectangle(w,h); void scale(float factor) { r.setwidth(factor * r.getwidth()); r.setheight(factor * r.getheight()); float getwidth() { return r.getwidth(); float circumference() { return r.circumference();... 7

Subclassing vs. delegation Subclassing automatically gives access to all methods of superclass built in to the language (syntax, efficiency) Delegation permits removal of methods (compile-time checking) objects of arbitrary concrete classes can be wrapped multiple wrappers can be composed Delegation vs. composition Differences are subtle For CSE 331, consider them equivalent (?) 8

Types of adapter Goal of adapter: connect incompatible interfaces Different interfaces Adapter with delegation Client Implementation Client Adaptor Implementation Adapter with subclassing Adapter with subclassing: no extension is permitted Implementation Implementation Client Adaptor Client Adaptor Implementation Subclass 9

Decorator Add functionality without changing the interface Add to existing methods to do something additional (while still preserving the previous specification) Not all subclassing is decoration 10

Decorator example: Bordered windows interface Window { // rectangle bounding the window Rectangle bounds(); // draw this on the specified screen void draw(screen s);... class WindowImpl implements Window {... 11

Bordered window implementations Via subclasssing: class BorderedWindow1 extends WindowImpl { void draw(screen s) { super.draw(s); bounds().draw(s); Delegation permits multiple borders on a window, or a window that is both bordered and shaded Via delegation: class BorderedWindow2 implements Window { Window innerwindow; BorderedWindow2(Window innerwindow) { this.innerwindow = innerwindow; void draw(screen s) { innerwindow.draw(s); innerwindow.bounds().draw(s); 12

A decorator can remove functionality Remove functionality without changing the interface Example: UnmodifiableList What does it do about methods like add and put? Problem: UnmodifiableList is a Java subtype, but not a true subtype, of List Decoration via delegation can create a class with no Java subtyping relationship, which is often desirable 13

Proxy Same interface and functionality as the wrapped class So, uh, why wrap it?... Control access to other objects Communication: manage network details when using a remote object Locking: serialize access by multiple clients Security: permit access only if proper credentials Creation: object might not yet exist (creation is expensive) Hide latency when creating object Avoid work if object is never used 14

Composite pattern Composite permits a client to manipulate either an atomic unit or a collection of units in the same way So no need to always know if an object is a collection of smaller objects or not Good for dealing with part-whole relationships An extended example 15

Composite example: Bicycle Bicycle Wheel Skewer Lever Body Cam Rod Hub Spokes Nipples Rim Tape Tube Tire Frame Drivetrain... 16

Methods on components abstract class BicycleComponent { int weight(); float cost(); class Skewer extends BicycleComponent { float price; float cost() { return price; class Wheel extends BicycleComponent { float assemblycost; Skewer skewer; Hub hub;... float cost() { return assemblycost + skewer.cost() + hub.cost() +...; 17

Composite example: Libraries Library Section (for a given genre) Shelf Volume Page Column Word Letter interface Text { String gettext(); class Page implements Text { String gettext() {... return concatenation of column texts... 18

Outline ü Introduction to design patterns ü Creational patterns (constructing objects) ü Structural patterns (controlling heap layout) Þ Behavioral patterns (affecting object semantics) Already seen: Observer Will just do 2-3 related ones 19

Traversing composites Goal: perform operations on all parts of a composite Idea: generalize the notion of an iterator process the components of a composite in an order appropriate for the application Example: arithmetic expressions in Java How do we represent, say, x=foo*b+c/d; How do we traverse/process these expressions? 20

Representing Java code x = foo * b + c / d; = x + * / foo b c d 21

Abstract syntax tree (AST) for Java code class PlusOp extends Expression { // + operation Expression leftexp; Expression rightexp; class VarRef extends Expression { // variable use String varname; class EqualOp extends Expression { // test a==b; Expression leftexp; // left-hand side: a in a==b Expression rightexp; // right-hand side: b in a==b class CondExpr extends Expression { // a?b:c Expression testexp; Expression thenexp; Expression elseexp; 22

Object model vs. type hierarchy AST for a + b: (PlusOp) a (VarRef) b (VarRef) Class hierarchy for Expression: Expression PlusOp VarRef EqualOp CondExpr 23

Operations on abstract syntax trees Need to write code for each entry in this table Types of Objects CondExpr EqualOp Operations typecheck print Question: Should we group together the code for a particular operation or the code for a particular expression? That is, do we group the code into rows or columns? Given an operation and an expression, how do we find the proper piece of code? 24

Interpreter and procedural patterns Interpreter: collects code for similar objects, spreads apart code for similar operations Makes it easy to add types of objects, hard to add operations An instance of the Composite pattern Procedural: collects code for similar operations, spreads apart code for similar objects Makes it easy to add operations, hard to add types of objects The Visitor pattern is a variety of the procedural pattern (See also many offerings of CSE341 for an extended take on this question Statically typed functional languages help with procedural whereas statically typed object-oriented languages help with interpreter) 25

Objects Interpreter pattern typecheck print CondExpr EqualOp Add a method to each class for each supported operation abstract class Expression {... Type typecheck(); String print(); class EqualOp extends Expression {... Type typecheck() {... String print() {... class CondExpr extends Expression {... Type typecheck() {... String print() {... Dynamic dispatch chooses the right implementation, for a call like e.typecheck() Overall type-checker spread across classes 26

Objects Procedural pattern typecheck print CondExpr EqualOp Create a class per operation, with a method per operand type class Typecheck { Type typecheckcondexpr(condexpr e) { Type condtype = typecheckexpr(e.condition); Type thentype = typecheckexpr(e.thenexpr); Type elsetype = typecheckexpr(e.elseexpr); if (condtype.equals(booltype) && thentype.equals(elsetype))) return thentype; else return ErrorType; Type typecheckequalop(equalop e) {... How to invoke the right method for an expression e? 27

Definition of typecheckexpr (using procedural pattern) class Typecheck {... Type typecheckexpr(expression e) { if (e instanceof PlusOp) { return typecheckplusop((plusop)e); else if (e instanceof VarRef) { return typecheckvarref((varref)e); else if (e instanceof EqualOp) { return typecheckequalop((equalop)e); else Maintaining if (e instanceof this code is tedious CondExpr) and error-prone { return typecheckcondexpr((condexpr)e); else... No help from type-checker to get all the cases... (unlike in functional languages) Cascaded if tests are likely to run slowly (in Java) Need similar code for each operation 28

Visitor pattern: A variant of the procedural pattern Nodes (objects in the hierarchy) accept visitors for traversal Visitors visit nodes (objects) class SomeExpression extends Expression { void accept(visitor v) { for each child of this node { child.accept(v); v.visit(this); class SomeVisitor extends Visitor { void visit(someexpression n) { perform work on n n.accept(v) traverses the structure rooted at n, performing v's operation on each element of the structure 29

Example: accepting visitors class VarOp extends Expression { void accept(visitor v) { v.visit(this); class EqualsOp extends Expression { void accept(visitor v) { leftexp.accept(v); rightexp.accept(v); v.visit(this); class CondOp extends Expression { void accept(visitor v) { testexp.accept(v); thenexp.accept(v); elseexp.accept(v); v.visit(this); First visit all children Then pass self back to visitor The visitor has a visit method for each kind of expression, thus picking the right code for this kind of expression Overloading makes this look more magical than it is Lets clients provide unexpected visitors 30

Sequence of calls to accept and visit a.accept(v) b.accept(v) d.accept(v) b v.visit(d) e.accept(v) d v.visit(e) v.visit(b) c.accept(v) f.accept(v) v.visit(f) v.visit(c) v.visit(a) Sequence of calls to visit: d, e, b, f, c, a e a c f 31

Example: Implementing visitors class TypeCheckVisitor implements Visitor { void visit(varop e) { Now each operation has its cases back together void visit(equalsop e) { And type-checker should tell us if void visit(condop e) { we fail to implement an abstract method in Visitor Again: overloading just a nicety class PrintVisitor implements Visitor { Again: An OOP workaround for void visit(varop e) { procedural pattern void visit(equalsop e) { Because language/typechecker is not instance-of-test void visit(condop e) { friendly 32