320
CS 4140: Software Engineering * Lecture Notes - Student Version Kyle Burke June 3, 2019 “Weeks of programming can save you hours of planning.” - unknown This work is licensed under a Creative Commons “Attribution 4.0 International” license. Abstract Lecture notes for an upper-level undergraduate software engineer- ing course, with a strong focus on software design. Students taking this course should have already completed a data structures course. These notes are designed to be used with Dale Skrien’s text Object Oriented Design using Java [4]. Contents Preface 6 Plan and Goals ......................... 6 Acknowledgements ....................... 6 Under Construction ...................... 7 * Kyle would always like to hear about how useful his notes are. If you have any comments about these, please email him at [email protected]. Created with lectureNotes.sty, which is available at: http://turing.plymouth.edu/ ~ kgb1013/lectureNotesLatexStyle.php (or, GitHub: https://github.com/paithan/ LaTeX-LectureNotes). 1

CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

CS 4140: Software Engineering∗

Lecture Notes - Student Version†

Kyle Burke

June 3, 2019

“Weeks of programming can save you hours of planning.” -unknown

This work is licensed under a Creative Commons“Attribution 4.0 International” license.

Abstract

Lecture notes for an upper-level undergraduate software engineer-ing course, with a strong focus on software design. Students takingthis course should have already completed a data structures course.These notes are designed to be used with Dale Skrien’s text ObjectOriented Design using Java [4].

Contents

Preface 6Plan and Goals . . . . . . . . . . . . . . . . . . . . . . . . . 6Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 6Under Construction . . . . . . . . . . . . . . . . . . . . . . 7

∗Kyle would always like to hear about how useful his notes are. If you have anycomments about these, please email him at [email protected].

†Created with lectureNotes.sty, which is available at: http://turing.plymouth.edu/

~kgb1013/lectureNotesLatexStyle.php (or, GitHub: https://github.com/paithan/

LaTeX-LectureNotes).

1

Page 2: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

CONTENTS CONTENTS

0 Introduction 70.0 Project Teams . . . . . . . . . . . . . . . . . . . . . . 70.1 Good code vs. Brittle Code . . . . . . . . . . . . . . . 80.2 UML: Class Diagrams . . . . . . . . . . . . . . . . . . 80.3 Bad Design: Repeated Code . . . . . . . . . . . . . . . 180.4 JavaDoc . . . . . . . . . . . . . . . . . . . . . . . . . . 230.5 Model-View-Controller Heuristic . . . . . . . . . . . . 240.6 Second Intro . . . . . . . . . . . . . . . . . . . . . . . 30

1 Basic Object-Oriented Programming 301.0 Elegance . . . . . . . . . . . . . . . . . . . . . . . . . . 301.1 Public vs Private Variables . . . . . . . . . . . . . . . 32

2 Observer Pattern 362.0 Code to Fix . . . . . . . . . . . . . . . . . . . . . . . . 372.1 Object-Oriented Design Pattern Basics . . . . . . . . . 382.2 Solution: Observer Pattern . . . . . . . . . . . . . . . 392.3 Applying the Observer Pattern . . . . . . . . . . . . . 43

3 When to Inherit? 443.0 Similar Public Interfaces . . . . . . . . . . . . . . . . . 523.1 Code Reuse . . . . . . . . . . . . . . . . . . . . . . . . 573.2 “Is-A” Perspective . . . . . . . . . . . . . . . . . . . . 583.3 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . 703.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . 71

4 State Pattern 724.0 State Pattern Basics . . . . . . . . . . . . . . . . . . . 724.1 Example: Debugging Print Modes . . . . . . . . . . . 744.2 Example: Pokedex - Caught and Unseen Pokemon . . 824.3 Example: Monopoly . . . . . . . . . . . . . . . . . . . 92

5 Singleton Pattern 975.0 Use Reluctantly! . . . . . . . . . . . . . . . . . . . . . 985.1 The Singleton Participant . . . . . . . . . . . . . . . . 985.2 Removing the Public ”Constant” . . . . . . . . . . . . 1015.3 Delaying the Construction . . . . . . . . . . . . . . . . 1035.4 Solving the Race Condition . . . . . . . . . . . . . . . 1045.5 Java’s Solution to the Bottleneck . . . . . . . . . . . . 1055.6 Example: LinkedIntList . . . . . . . . . . . . . . . . 1075.7 When to use the Singleton Pattern . . . . . . . . . . . 107

Page 2 © 2019 Kyle Burke cb

Page 3: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

CONTENTS CONTENTS

5.8 When to Use? . . . . . . . . . . . . . . . . . . . . . . . 107

6 Elegant Methods 1086.0 Public vs. Private Methods . . . . . . . . . . . . . . . 1086.1 Method Documentation . . . . . . . . . . . . . . . . . 1116.2 Pre/Post Conditions . . . . . . . . . . . . . . . . . . . 1126.3 Overriding Clone . . . . . . . . . . . . . . . . . . . . . 116

7 Elegant Classes 1197.0 Pre-Implementation Steps . . . . . . . . . . . . . . . . 1207.1 Extract Nouns and Verbs . . . . . . . . . . . . . . . . 1227.2 CRC (Class-Responsibilities-Collaborators) Cards . . . 1227.3 Cohesion . . . . . . . . . . . . . . . . . . . . . . . . . . 1227.4 Responsibilities . . . . . . . . . . . . . . . . . . . . . . 1247.5 Immutable Classes . . . . . . . . . . . . . . . . . . . . 1307.6 Coding to Interfaces . . . . . . . . . . . . . . . . . . . 1307.7 Coupling . . . . . . . . . . . . . . . . . . . . . . . . . . 1447.8 Encapsulation and Information Hiding . . . . . . . . . 1477.9 Example: Known and Unknown Prices . . . . . . . . . 151

8 OODP: Composite Pattern 1518.0 Pac Man . . . . . . . . . . . . . . . . . . . . . . . . . . 1518.1 Composite Pattern Specifics . . . . . . . . . . . . . . . 1558.2 Composite Nim . . . . . . . . . . . . . . . . . . . . . . 163

9 OODP: Factory Method Pattern 1779.0 Example: Nim . . . . . . . . . . . . . . . . . . . . . . 1779.1 Factory Method Pattern Basics . . . . . . . . . . . . . 1829.2 Factory Method with State Pattern . . . . . . . . . . . 183

10 OODP: Command Pattern 18310.0 Command Pattern Specifics . . . . . . . . . . . . . . . 18410.1 Example: Web Browsing . . . . . . . . . . . . . . . . . 187

11 Waterfall Software Development 20011.0 Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20111.1 Benefits . . . . . . . . . . . . . . . . . . . . . . . . . . 20111.2 Limitations . . . . . . . . . . . . . . . . . . . . . . . . 20111.3 Other Philosophies . . . . . . . . . . . . . . . . . . . . 202

Page 3 © 2019 Kyle Burke cb

Page 4: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

CONTENTS CONTENTS

12 Agile Software Development 20212.0 The Agile Manifesto . . . . . . . . . . . . . . . . . . . 20212.1 Agile Iterations . . . . . . . . . . . . . . . . . . . . . . 20612.2 Customer Representative . . . . . . . . . . . . . . . . 21012.3 Information Radiator . . . . . . . . . . . . . . . . . . . 21212.4 Code Quality in an Agile Team . . . . . . . . . . . . . 21412.5 Team Experience . . . . . . . . . . . . . . . . . . . . . 215

13 OODP: Visitor Pattern 21813.1 Motivation: Collectibles from the 1980’s . . . . . . . . 21813.2 Visitor Pattern Participants . . . . . . . . . . . . . . . 22813.3 Implemented Example . . . . . . . . . . . . . . . . . . 23213.4 Downsides . . . . . . . . . . . . . . . . . . . . . . . . . 235

14 Parallel OODP: Producer-Consumer 23514.0 Old stuff . . . . . . . . . . . . . . . . . . . . . . . . . . 23914.1 Motivation and the Big Problem . . . . . . . . . . . . 24014.2 Common First Code . . . . . . . . . . . . . . . . . . . 24214.3 Sleeping with Semaphores . . . . . . . . . . . . . . . . 24514.4 Instilling OO principles . . . . . . . . . . . . . . . . . 25014.5 Improvements . . . . . . . . . . . . . . . . . . . . . . . 25314.6 Shifting Responsibilities . . . . . . . . . . . . . . . . . 256

15 Parallel OODP: Master-Worker 26015.0 Motivation . . . . . . . . . . . . . . . . . . . . . . . . 26115.1 Initial OO Master-Worker . . . . . . . . . . . . . . . . 26215.2 First Improvements . . . . . . . . . . . . . . . . . . . . 26315.3 Using the Command Pattern . . . . . . . . . . . . . . 26715.4 Double-down on Command . . . . . . . . . . . . . . . 27015.5 Giving Back . . . . . . . . . . . . . . . . . . . . . . . . 27415.6 Waiting for Workers . . . . . . . . . . . . . . . . . . . 28415.7 Master-Worker: Summary . . . . . . . . . . . . . . . . 293

16 Parallel OODP: Pipeline Pattern 29516.0 Pipeline Pattern based on State Pattern Paper . . . . 29616.1 Final Code and Diagram . . . . . . . . . . . . . . . . . 297

17 Evolution of Design Patterns 29817.0 Downsides of Design Patterns . . . . . . . . . . . . . . 30017.1 OODP and PL . . . . . . . . . . . . . . . . . . . . . . 301

Page 4 © 2019 Kyle Burke cb

Page 5: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

CONTENTS CONTENTS

Appendix A Java Programming with Objects 302A.0 Downcasting . . . . . . . . . . . . . . . . . . . . . . . 303A.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . 312

Appendix B Java and XML (JAXB) 312B.1 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313B.2 JAXB . . . . . . . . . . . . . . . . . . . . . . . . . . . 314

1

When I Don’t Comment My Code

1Found on reddit: https://www.reddit.com/r/ProgrammerHumor/comments/

66xzzc/when_i_dont_comment_my_code/.

Page 5 © 2019 Kyle Burke cb

Page 6: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

CONTENTS CONTENTS

Preface

Plan and Goals

These lecture notes are designed to be used for a course in conjunctionwith Dale Skrien’s book, Object Oriented Design using Java [4]. Withthis influence, the course spends most of its time covering elements ofsoftware design.

Acknowledgements

I must thank all of my students who have taken this course2. Theyhave influenced the order of topics I cover and will continue to havean impact for as long as I teach this course. I have learned moreabout good design from teaching these students than I did while takingcourses. I am so lucky to have many students who are quick to tellme the changes I should make and what worked well for them. Thisfeedback is always helpful. I specifically want to thank:

• Dang and Amanda, the first two students who somehow surviveda course that I made far too hard. Thanks and sorry!

• Will, who introduced me to the Command Pattern.

• Ryan and Bob, who didn’t even take the course from me, butwho convinced me to introduce MVC early.

• ... I’ll add more as I remember them!

I learned to care so greatly about good design from Dale Skrien3.He showed us glimpses of design patterns in his Data Structurescourse, just enough to prime us for the ”experimental” software designcourse he was creating. Everyone who could signed up for Dale’s newcourse—offered first in 2002—and it did not disappoint. There wasso much to learn, and I didn’t get to flex that muscle during much ofgrad school. Luckily, the torch continued burning, and I got to teachan upper-level software course right after graduating in 2009. Dale’slessons lasted for seven dormant years, but armed with his excellent(and then new) text, I jumped right in as though no time had passed.Thank you, Dale!

2Wittenberg CS 253 and CS 353 in addition to Plymouth State CS 4140.3http://www.cs.colby.edu/djskrien/

Page 6 © 2019 Kyle Burke cb

Page 7: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

I just discovered the tikz-uml4 LATEXpackage and am beginningto add diagrams using that instead of LibreOffice. Thanks to NicolasKielbasiewicz and other developers of this cool package!

Thanks also to Christin Wixson for helping me make all the neces-sary changes to include this (and my other lecture notes) in PlymouthState’s institutional repository5.

Thanks to Susan Schwarz, who is helping me improve the flow ofquestions and answers. There are a lot of bumps that she has alreadyhelped me smooth out.

Under Construction

There’s still so much to do. I’m working hard to convert over myhand-written notes into this form. Here’s a list of some of the thingsI have left to do:

• Motivate every new Design Pattern by starting with code to fix.After fixing the code, show the actual design pattern.

• Convert the diagrams to TikZ-UML.

• Add tons of missing chapters/sections/etc.

• Add references to Dale’s book sections from each section in here.

• Add a little tutorial on using TikZ-UML in case students wantto use that for their class diagrams. (Who am I kidding? Theywon’t do that...)

• Add references to A2A for the Parallel/Concurrent OODP sec-tions.

• Introduce refactoring as an incremental solution for brittle codeearly on. (And use this comic when you introduce brittle code:http://lightroastcomics.com/the-ancient-code.) Then in-troduce the individual refactorings as I use them. Also includethis comic: https://www.monkeyuser.com/2018/priorities/.

0 Introduction

0.0 Project Teams

First step: choose programming teams. Considerations:

4http://perso.ensta-paristech.fr/~kielbasi/tikzuml/index.php?lang=en5http://digitalcommons.plymouth.edu

Page 7 © 2019 Kyle Burke cb

Page 8: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

• Team members need to put equal effort into working on theprojects.

• Team sizes: 2-3 people. Preference towards 2.

• Everyone must be on a team.

• Pair/Triple-Programming is most efficient. Find a team with asimilar weekly schedule to yours.

• Large experience/skill gaps are dangerous. It’s best to find team-mates at your ”level”.

We need to choose teams immediately because you’ll probably wantto begin work on your project today.

⟨ Let students discuss with each other to determineteams. We have to have teams chosen today! ⟩

0.1 Good code vs. Brittle Code

In this course, you will:

• Write lots of code.

• Learn Object-Oriented design principles to makecode less brittle.

• Make lots of design mistakes.

⟨ Story time: Show some examples of really brittlecode. (I don’t have those yet.) Talk about legacy codehere. ⟩

0.2 UML: Class Diagrams

Often, easier to communicate and organize ideas indiagrams rather than code. UML (Unified ModellingLanguage) describes often-used diagrams. One part ofUML is class diagrams. You will bring class diagramsto me each meeting.

Page 8 © 2019 Kyle Burke cb

Page 9: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Sandwich

- hasLettuce : boolean- meat : Meat- condiments : Collection<Ingredient>

+ Sandwich(Bread, Meat) : Sandwich+ cut() : void+ hasMustard() : boolean+ eat() : void+ addCondiment(Ingredient) : void

Q: Would Food be a sub- or superclass of Sandwich?

A:

⟨ Include Food in the diagram: ⟩

Sandwich

- hasLettuce : boolean- meat : Meat- condiments : Collection<Ingredient>

+ Sandwich(Bread, Meat) : Sandwich+ cut() : void+ hasMustard() : boolean+ eat() : void+ addCondiment(Ingredient) : void

Food

Page 9 © 2019 Kyle Burke cb

Page 10: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: How are inheritance connections drawn?

A:Big empty arrow pointing to the bottom of thesuperclass coming out of the top of the sub-class. Implemented interfaces are the same, ex-cept that the edge is a dashed line.

Q: Which other types of connections come out of the tops andbottoms of class boxes?

A: None!

Q: What if we want to include Meat. How can we fit Meatinto the diagram?

A:

Page 10 © 2019 Kyle Burke cb

Page 11: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Sandwich

- hasLettuce : boolean- meat : Meat- condiments : Collection<Ingredient>

+ Sandwich(Bread, Meat) : Sandwich+ cut() : void+ hasMustard() : boolean+ eat() : void+ addCondiment(Ingredient) : void

Food

Meat

Q: Is it okay to combine the subclassing arrows for Food andMeat like in the drawing?

A: Yes! In fact, you should only have one arrowcoming in to the bottom of any class!

Q: What does the arrow from Sandwich to Meat mean?

A: It means that Sandwich has a field of type Meat.

Page 11 © 2019 Kyle Burke cb

Page 12: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: What’s up with the filled diamond?

A:

”Strong aggregation”. The filled diamondmeans that Sandwich ”owns” the field. Usu-ally that means that Sandwich created it or itwill be garbage collected because Sandwich dis-appears. It’s definitely a subtle point.

Q: Wait... what’s the other option?

A:

The diamond could be open. ”Non-strong” ag-gregation. In this case, the object doesn’t ownit. I do not expect you to get all the diamondsright on your figures. In fact, you don’t have todraw diamond in your figures.

Q: What is important about the positioning of the base andtip of the arrow?

A:• Base: I like to put it at the field itself.

• Tip: I like to direct it to the head of theclass (top box).

Page 12 © 2019 Kyle Burke cb

Page 13: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

We won’t worry about drawing the fields and/ormethods of Meat at this point. If it’s a class thatyou’ve designed, then you want to list all these things.If it’s a built-in class (e.g. JPanel) then you only needto single box.

Q: What if there are multiple instances of a class in a field?What symbol should we use?

A: Use an asterisk.

Q: Which other class should we add to the diagram that willuse an asterisk?

A:

Page 13 © 2019 Kyle Burke cb

Page 14: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

*

Sandwich

- hasLettuce : boolean- meat : Meat- condiments : Collection<Ingredient>

+ Sandwich(Bread, Meat) : Sandwich+ cut() : void+ hasMustard() : boolean+ eat() : void+ addCondiment(Ingredient) : void

Food

Meat

Ingredients

For more information about Class Diagrams, hereis a good explainer at Creately: https://creately.

com/blog/diagrams/class-diagram-relationships/.(I haven’t used their diagram software, so I can’t vouchfor it.)

Here’s a little checklist of the formatting you’ll needto abide by to get your class diagrams approved inthe project meetings. This is necessary so I can get aquick idea of how your code is organized. If your classdiagram does not follow this (or isn’t close) I may askyou to fix the diagram and come back to me when it’sfixed.

• All connections (lines)

– All lines should be drawn in only the four car-dinal directions, with corners as needed.

– Lines are combined as appropriate.

Page 14 © 2019 Kyle Burke cb

Page 15: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

– The diagram is laid out so it’s easy to see wherethe lines lead. Messy or poorly-organized dia-grams will need to be redrawn.

• Built-in Classes and Interfaces: just draw the sin-gle box with the name. You do not need to includethe fields/methods. (You should always includethese for inherited/implemented classes. I’m not100% sure about this for fields.)

Application

MyApp

- x : int- y : String

+ MyApp(int, String)+ start(Stage) : void

• Classes/Interfaces you write

– Each class should have three sections: name,fields, and methods.

Monkey

- x : int- y : String

+ Monkey(int, String)+ getName() : String

– All listed members (fields and methods) shouldhave the correct capitalization.

– All fields should be included. Public and pri-vate, and with the appropriate markers.

Page 15 © 2019 Kyle Burke cb

Page 16: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Monkey

- x : int- y : String+ MONKEY FOOD : Fruit

+ Monkey(int, String)+ getName() : String

– Private methods do not need to be included(but they can be, if you wish). Public meth-ods should list the types of the parameters.(Names of the parameters do not need to beincluded.) Methods should have the appropri-ate access markers (public or private).

– Constructors should be listed with the meth-ods.

– main methods (e.g. for testing) do not need tobe listed.

– Abstract classes and interfaces should be clearlymarked as such.

�interface�Grabbable

+ grabWith(Tail) : void

• Inheritance/Implementation

– Inheritance/Implementation connections shouldonly come out of the top and bottom of classboxes, never the sides.

– Each class box should have at most one arrowcoming in on the bottom. Multiple incomingedges should be condensed into one.

Page 16 © 2019 Kyle Burke cb

Page 17: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

A

B C

– Each class box should have at most one solidline leaving the top for inheritance.

– Each class box should have at most one dashedline leaving the top for implements. This linecan split into multiple arrows if it implementsfrom multiple interfaces.

A

�interface�B

C

• Aggregation/Composition/Uses/Anything else

– These arrows should always leave and arriveon the sides of class boxes, never the top andbottom.

– Aggregation and Composition arrows shouldhave the diamond on the side of the class that

Page 17 © 2019 Kyle Burke cb

Page 18: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

contains the field and the arrow is pointing tothe class that that field is an instance of.

– It’s okay if you’re not sure whether a diamondshould be filled in.

– If there are a constant non-one number of fieldsof that type, put a number to indicate thatabove the diamond.

– If the field is a collection (or there are multiplecollections) of that type, include a * above thediamond.

*Human

- friends : ArrayList<Monkey> Monkey

– ”Uses” connections are not necessary, but youcan put them in if it helps.

0.3 Bad Design: Repeated Code

Q:

Let’s say I’m new to a software project, and I’m looking atthe code... and I see a line that could be causing an error.I fix it right then (probably not a good idea without talk-ing to someone). What might I be worried about? Whatimmediate question am I going to ask myself?

A:(You’ll get lots of answers here, but the one Icare about is:)Where else is this same error duplicated?

Page 18 © 2019 Kyle Burke cb

Page 19: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q:

Let’s say we have a class, MonkeyCoins with a field,numCoins that needs to always be positive. There are abunch of while loops in the class that decrement numCoins,e.g.while (x > 10) {

...

this.numCoins --;

...

}In order to ensure that the field is still positive after theloop, we include conditionals like this after the loops:while (x > 10) {

...

this.numCoins --;

...

}if (this.numCoins < 1) this.numCoins = 1;

The team makes some changes that allows numCoins to bepositive or zero. What do we need to do now?

A:

Q: What’s the common problem in these two situations?

A:

Page 19 © 2019 Kyle Burke cb

Page 20: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: What kind of other duplication do we need to be worriedabout throughout?

A:

Q:What if I am able to replace each of the tests on x with amethod (function) call instead? What would be the benefitthere?

A:

⟨ Check out this implementation for a Binary Tree:http://turing.plymouth.edu/~kgb1013/DB/4140/binaryTreeExample/

v0/BinaryIntTree.java ⟩

Q: Does this code compile?

A:

Q: Does the unit test run?

A:

Page 20 © 2019 Kyle Burke cb

Page 21: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: Why not?

A:

Q: What do we have to do to fix it?

A:

⟨ Here’s a version with the tests in place: http://turing.plymouth.edu/~kgb1013/DB/4140/binaryTreeExample/

v1/BinaryIntTree.java ⟩

Q: What’s a potential problem going forward with this code?

A:

This is not an immediately easy problem to solve.Notice: in each case, if the child is not null, I just callthe appropriate method on that child. I’d like to callthat method independent of whether the child is null.

Page 21 © 2019 Kyle Burke cb

Page 22: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: What happens if I call the method on a null object in Java?

A:

Q: How else could we represent not having a child? (Hard!)

A:

⟨ Check out the code here: http://turing.plymouth.edu/~kgb1013/DB/4140/binaryTreeExample/v2/BinaryIntTree.

java ⟩null is actually considered to be a mistake. Here’s

the quote from Tony Hoare, who was a developer ofALGOL back in the 1960’s:

“I call it my billion-dollar mistake. It wasthe invention of the null reference in 1965. Atthat time, I was designing the first compre-hensive type system for references in an ob-ject oriented language (ALGOL W). My goalwas to ensure that all use of references shouldbe absolutely safe, with checking performedautomatically by the compiler. But I couldn’tresist the temptation to put in a null reference,simply because it was so easy to implement.This has led to innumerable errors, vulnerabil-

Page 22 © 2019 Kyle Burke cb

Page 23: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

ities, and system crashes, which have probablycaused a billion dollars of pain and damage inthe last forty years.”6

This is an example of a programming pattern thatuses Polymorphism: the Null Object Pattern.

TODO: Should I introduce the Null Object Pat-tern in full here? (a la http://www.cs.oberlin.edu/

~jwalker/nullObjPattern/) I could talk about themhere and move all that stuff up... Better idea: put itin right after we first talk about design patterns.

⟨ Go over the syllabus! ⟩

0.4 JavaDoc

This is covered in the class book in Appendix B.⟨ Describe JavaDoc comments: class headers, in-

stance variable (constant) headers, public method head-ers, tags. ⟩

Q: Why do I want you to JavaDoc things for this class?

A:

6Source: https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare

Page 23 © 2019 Kyle Burke cb

Page 24: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

0.5 Model-View-Controller Heuristic

⟨ Talk about old students helping me fix this courseby suggesting topics. ⟩

One of these suggested topics is the Model-View-Controller paradigm. The idea to is identify and sep-arate out these three parts:

• Model: The actual data for something (X).

• View: Handles the way X is displayed.

• Controller: Handles changes/input to the system.

The more you can separate these things, the better.

Q: However, there is one automatic view that I include in everymodel. What is that?

A:

MVC is a good way to start dividing up the differ-ent parts for a project. Some development tools (e.g.Spring framework) have you start with this.

• If they’re using the game project you assignedthem: “Note, I divided up the classes using MVC.”

• TODO: add more cases here as/if you create moreprojects.

0.5.1 Example: Pokedex

In the Pokemon mythos, it is very useful to have yourPokedex while out hunting. It’s like a little PDA that

Page 24 © 2019 Kyle Burke cb

Page 25: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

tells you about the Pokemon you encounter.⟨ Draw a sketch of a Pokedex, like a game boy. ⟩

Q:

If Dexter (common Pokedex name) is currently on a screenshowing general information about Jigglypuffs, which partof MVC should be responsible for the information? (I.e.,#39, Normal Type, “When its huge eyes light up, it singsa mysteriously soothing melody that lulls its enemies tosleep.”)

A:

Q: What might we call this class?

A:

Q: What are some fields for this class?

A:

Page 25 © 2019 Kyle Burke cb

Page 26: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: What is responsible for presenting this data?

A:

Q: Why do we want the View and the Model to be disjoint?Why not use the same object?

A:

Q: What is a better term for classes being disjoint?

A:

Page 26 © 2019 Kyle Burke cb

Page 27: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: Some adversaries to MVC argue that every model shouldhave a default view. Why?

A:

Q: Why might different views be good for Pokedex software?

A:

Q: Which MVC part will get involved if I push the Right-arrow, because I want to go to pokemon #40?

A:

Page 27 © 2019 Kyle Burke cb

Page 28: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q:

Fill in the following sequence of events from the Controller’sperspective:

1. Press Right-Arrow

2. Controller “hears” the right-arrow-push

3. ?

4. ?

5. Controller tells the view to ...?

A:

Q: What are some of the fields for the Controller going to bein this instance?

A:

Remember that we want to decouple the differentparts of MVC as much as possible. (It’s very hard.)

Page 28 © 2019 Kyle Burke cb

Page 29: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

0. INTRODUCTION CONTENTS

Q: Which classes need to know about which other classes?

A:

Q: Is this how it always is? Hint: consider the project code.

A:

Q: Why doesn’t the Controller need to know about the View?

A:

We’ll see more ways of how to separate the differentparts.

Page 29 © 2019 Kyle Burke cb

Page 30: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

1. BASIC OBJECT-ORIENTED PROGRAMMING CONTENTS

0.6 Second Intro

Three Problematic Expectations. You can’t expect...

Past ...code to have been designed well.

Present ...to make the best choices the first time.

Future ...how your code will be used in the future. (Ex-ample: unsafe methods in one buried class.)

I expect you to overcome these with good design!⟨ Story time: Talk about Java decomposition code

that I rewrote. ⟩

1 Basic Object-Oriented Programming

7

1.0 Elegance

Code Elegance! “Shivers of joy” vs “Shudders of re-vulsion.”

Elegance is: (page 5) (list all out first)

• Usability: Is it easy for the client to use?

• Completeness: Does it satisfy all the client’s needs?

• Robustness: will it deal with unusual situationsgracefully and avoid crashing?

7XKCD comic 292: https://xkcd.com/292/

Page 30 © 2019 Kyle Burke cb

Page 31: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

1. BASIC OBJECT-ORIENTED PROGRAMMING CONTENTS

• Efficiency: will it perform the necessary computa-tions with reasonable resources?

• Scalability: will it still perform when the problemsgrow by a lot?

• Readability: is it easy for other programmers toread the code?

• Reusability: can the code be reused in other set-tings?

• Simplicity: is the code unnecessarily complex?

• Maintainability: can defects be fixed easily with-out adding new defects?

• Extensibility: can new features easily be added/unwantedfeatures easily be removed?

Q: Which are parts of Object-Oriented Design?

A:

Q: Which others are important for this class?

A:

Page 31 © 2019 Kyle Burke cb

Page 32: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

1. BASIC OBJECT-ORIENTED PROGRAMMING CONTENTS

Q: Improving which ones helps remove technical debt?

A:

1.1 Public vs Private Variables

Consider this Square class:

Square

Square

+ sideLength : double

+ Square(double side)

Q: Can I create an ”illegal” square?

A:

Q: How?

A:

Page 32 © 2019 Kyle Burke cb

Page 33: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

1. BASIC OBJECT-ORIENTED PROGRAMMING CONTENTS

Q: What should we do instead of making them public?

A:

Square

Square

- sideLength : double

+ Square(double side)

Q: What should I do if I want to access or change the value?

A:

Square

Square

- sideLength : double

+ Square(double side)+ getSideLength() : double+ setSideLength(double length) : void

Page 33 © 2019 Kyle Burke cb

Page 34: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

1. BASIC OBJECT-ORIENTED PROGRAMMING CONTENTS

Q: How could these setters prevent the problem with settingnegative side lengths?

A:

public class Square {private double sideLength;

public void setSideLength(double length)

{if (length > 0) {

this.sideLength = length;

}}

...

}

Q: Is there a chance something unexpected could happen here?

A:

Page 34 © 2019 Kyle Burke cb

Page 35: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

1. BASIC OBJECT-ORIENTED PROGRAMMING CONTENTS

Q: What’s a better solution?

A:

Q: Which kind of exception is most relevant here?

A:

Let’s rewrite it using an exception!

public void setSideLength(double length) {if (length > 0) {

this.sideLength = length;

} else {throw new IllegalArgumentException(

"Square.setSideLength called with a

non-positive length!");

}}

Q: Where else might we need to guard against negative values?

A:

Page 35 © 2019 Kyle Burke cb

Page 36: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Q: How should we write the constructor?

A:

Q: How could we make this better?

A:

2 Observer Pattern

⟨ Draw a gameboy-based Pokedex with Control Pad,and buttons B and A. ⟩

Page 36 © 2019 Kyle Burke cb

Page 37: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Q: Recall our Pokedex example: What happened when wepressed right on the control pad?

A:

2.0 Code to Fix

Q:

Consider the following buttons. What do they each do?(Assume we’re currently looking at a single Pokemon.)

• Control Pad ←• Control Pad ↑• Control Pad ↓• A

• B

A:

⟨ Draw this diagram:

Page 37 © 2019 Kyle Burke cb

Page 38: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Pokedex- buttons: Collection<Button>

+ wasPressedSince(Date) : Boolean+ getIdentity( ) : String

Button

- timePressed: Date- identity: String

*

Q: How does it work to determine whether a button waspressed?

A:

TODO: add some code in here?

2.1 Object-Oriented Design Pattern Basics

Each OO design pattern has some properties, includ-ing participants and roles.

Q: What are the participants in a design pattern?

A:

Page 38 © 2019 Kyle Burke cb

Page 39: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Q: What are the roles in a design pattern?

A:

TODO: add more here?

2.2 Solution: Observer Pattern

The observer pattern is (another) object-oriented De-sign Pattern.

⟨ Draw diagram:

+ add(Observer): void+ notify( ): void

Subject- observers: Collection <Observer> + update(Object info): void

<<interface>>

Observer

+ update(Object info): void

ConcreteObserver

*

Q: What are the participants?

A:

Page 39 © 2019 Kyle Burke cb

Page 40: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Q: What field does the Subject need to have?

A:

Q: What is the role of the Subject? (What does it do?)

A:

Q: The Observer’s role is to define the interface for concreteobservers. What is the role of the Concrete Observer?

A:

Q: Why is it good to have the interface?

A:

Page 40 © 2019 Kyle Burke cb

Page 41: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Q: What will the notify method of the Subject look like? (Wecan add nearly all of that code.)

A:

Q: In Java, you might not have to implement the Observerinterface yourself. Why not?

A:

Q: What’s the Object that’s sent as the parameter to Java’sActionListener?

A:

For many of the events, you can get the objectsource of the event. (E.g. ActionEvent.getSource())9

9For a full list of Built-in Java Listeners, see http://docs.oracle.com/javase/

tutorial/uiswing/events/api.html

Page 41 © 2019 Kyle Burke cb

Page 42: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

Q: How can we use generics in the Observer Pattern to makeit more reusable?

A:

⟨ Draw this diagram:

+ add(Observer<Event>): void+ notify( ): void

Subject- observers: Collection <Observer<Event>> + update(Event info): void

<<interface>>

Observer<Event>

+ update(Event info): void

ConcreteObserver

*

Eventuses

uses

Page 42 © 2019 Kyle Burke cb

Page 43: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

2. OBSERVER PATTERN CONTENTS

2.3 Applying the Observer Pattern

Q: How do we apply the pattern to our Pokedex problem? Foreach Participant, which real class fills it?

A:

Q: Draw out the class diagram.

A:

Page 43 © 2019 Kyle Burke cb

Page 44: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

3 When to Inherit?

We need to consider the question: When should youuse inheritance? When should class B extend/implement/subclassclass A?

Q: When do we consider inheritance?

A:• When B’s public method signatures (inter-

face) match A’s, and

• We want to reuse A’s functionality.

Basic Inheritance v0

?

A

+ foo(X, Y) : Z+ bar(W, X) : V+ ann(V, W) : X

B

+ foo(X, Y) : Z+ bar(W, X) : V+ ann(V, W) : X

Page 44 © 2019 Kyle Burke cb

Page 45: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Is it easy to misuse?

A: Absolutely! It turns out there’s a LOT to con-sider when deciding whether to use inheritance.

Let’s look at an example. Maybe Plymouth Stateis creating a new system to keep track of people oncampus. They divide them into two separate groups:Employees and Students, both of which are People.

⟨ Draw the following diagram: ⟩HR Database v0

Person

- name : String- address : String

Student

- grades : List<Integer>

Employee

- salary : int

Q: Is there any problem with this design?

A:

Page 45 © 2019 Kyle Burke cb

Page 46: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What happens if we have a student who is also an employee?

A:

Q: What else could go wrong here?

A:

Guideline: These are roles, and temporary rolesshould generally not be subclasses.

Q: What should we do instead of inheritance?

A: Composition. Have Student and Employee

have Person fields.

Page 46 © 2019 Kyle Burke cb

Page 47: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

HR Database v1

Person

- name : String- address : String

Student

- person : Person- grades : List<Integer>

Employee

- person : Person- salary : int

TODO: do the art museum part now, or do it later?It would be better to do it later and use examples fromall of the points we cover.

Let’s pretend the following is the design that hasbeen created for an Art Museum.

⟨ Draw this figure:

Page 47 © 2019 Kyle Burke cb

Page 48: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

WallSpace Exhibit

ArtMuseum Room*

*

ArtPiece

Page 48 © 2019 Kyle Burke cb

Page 49: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q:

What do you see that violates some of our guidelines?Hints: (reveal these one at a time)

• Are there any temporary roles here?

• Can an exhibit span multiple rooms?

• Can an art piece be in both the East Asian exhibit andthe Turbulent Water exhibit?

• Does all art exist on walls?

• Should an art piece know about its location or the otherway around?

A:

Q: Draw a new, more appropriate diagram.

Here’s a version we often come up with:

Page 49 © 2019 Kyle Burke cb

Page 50: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

DisplaySpace

Exhibit ArtMuseum Room*

ArtPiece

* **

Q: Just as with the Person-Student-Employee example, if wedecide not to subclass, what should we do instead?

A: Use References. Also known as Composition!

Subclass or Reference?

?

?

A

B

As we consider potential reasons to use inheritance,we have to decide which are actually good reasons.

Page 50 © 2019 Kyle Burke cb

Page 51: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What are four common reasons coders consider inheritance?(We already gave two.)

A:

• Matching (Public) Interfaces

• Code Reuse

• ”Is-A” perspective

• Polymorphism

Page 51 © 2019 Kyle Burke cb

Page 52: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What do each of these mean? When is this a justificationfor using inheritance?

A:

• Matching Public Interfaces : ”B’s publicmethod signatures are going to look a lotlike A’s, so I should have B inherit from A.”

• Code Reuse: ”Lots of the fields in A and/orbodies of methods in A are what I want in B.I should reuse that code by having B inheritfrom A.”

• “Is-A”: ”Every B is an A, so B should inheritfrom A.”

• Polymorphism: ”I want to decide what ac-tion to take based on the type (A or B) of theobject instead of conditionals, so B shouldinherit from A.”

Let’s talk about these things one-by-one!

3.0 Similar Public Interfaces

Q: What was the justification we gave for inheritance based onmatching public interfaces?

A: ”B’s public method signatures are going to looka lot like A’s, so I should have B inherit from A.”

Page 52 © 2019 Kyle Burke cb

Page 53: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Are there any reasons this might lead us astray?

A: Absolutely! A big one is the Principle of LeastSurprise

Guideline: Liskov Substitution Principle (LSP) -It is acceptable for B to subclass A only if for eachmethod in both A and B’s interfaces, B’s method:

• Accepts as input all the values that A’s methodaccepts (and possibly more), and

• Does everything with those values that A’s methoddoes (and possibly more).

Q: Why is this principle important?

A:

Story time! One team in my course in 2014 discov-ered the importance of Liskov right before we coveredthe material. We were still using Swing Java then, and

Page 53 © 2019 Kyle Burke cb

Page 54: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

they made a subclass of JPanel (which inherits fromJComponent) called GameTile.

GameTile v0

JPanel

GameTile

They used a GridLayout for these tiles and addedgetX() and getY() methods to determine where inthe grid the tiles were.

Page 54 © 2019 Kyle Burke cb

Page 55: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

GameTile v1

JPanel

GameTile

+ getX() : int+ getY() : int

Their code was one of the tiles, and at the veryupper left-hand corner of the window. They couldn’tfigure out why this was happening. I took a look at itand struggled to find the problem. Then I realized...getX() and getY() were already in JPanel, inheritedfrom JComponent10!

10https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html

Page 55 © 2019 Kyle Burke cb

Page 56: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

GameTile v2

JComponent

+ getX() : int+ getY() : int

JPanel

+ getX() : int+ getY() : int

GameTile

+ getX() : int+ getY() : int

Q: Why was that important?

A:

Java was trying to display their grid parts, butsince that method had been overriden by Ga-meTile, it was getting the wrong coordinates,so it was printing them all nearly right on topof each other. They had overriden methods anddidn’t follow Liskov substitution!

Page 56 © 2019 Kyle Burke cb

Page 57: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

</storyTime>

3.1 Code Reuse

Justification reminder: ”Lots of the fields in A and/orbodies of methods in A are what I want in B. I shouldreuse that code by having B inherit from A.”

Code Reuse is good!

Q: Which mammal lays eggs and has a bill like a duck?

A:

Q: Should we have Platypus extend the Duck class so we canreuse the layEgg and getBill methods?

A:

Q: What if Duck also had the molt method? What would haveto do in the Platypus class?

A:

Page 57 © 2019 Kyle Burke cb

Page 58: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What would the body of Platypus.molt look like?

A:

Guideline: Platypus Rule11: A class inheritingmethods should not nullify them or do something com-pletely different or unexpected.

Q: Should Platypus extend Duck?

A:

3.2 “Is-A” Perspective

Q: What was the justification we gave for the ”is-a” perspec-tive?

A:11As named by Amelia Rowland, ’18.

Page 58 © 2019 Kyle Burke cb

Page 59: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What kind of mammal is a platypus?

A:

Then maybe platypus should inherit from the monotreneclass? This still might not always be the case...

Let’s consider a “classic” example (Classic becauseit’s about 20 years old.) Recall our Square class.

Square

Square

- sideLength : double

+ Square(double side)+ getSideLength() : double+ setSideLength(double length) : void

Let’s add a Rectangle class now!

Q: We’ve been tasked to fix some code for Rectangles andSquares. what do we know about all Squares?

A:

Page 59 © 2019 Kyle Burke cb

Page 60: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Let’s inherit! What will our picture look like?

A:

Q: What fields should our Rectangle have? What public meth-ods will it have?

A:

Page 60 © 2019 Kyle Burke cb

Page 61: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Ehh, screw all of that. I just used public valuesinstead:

public class Rectangle {public double width;

public double height;

public Rectangle(double width, double

height) {if (width > 0 && height > 0) {

this.width = width;

this.height = height;

} else {//exception!

}}

}

Q: What’s the first thing we need to do to rewrite the Square

class to subclass Rectangle?

A:

Page 61 © 2019 Kyle Burke cb

Page 62: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Is there any data duplication?

A:

Q: How should we fix this?

A:

Q: Do we need to fix Square.setSideLength?

A: Yes!

Q: Fix it!

A:

Page 62 © 2019 Kyle Burke cb

Page 63: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Do we need to fix Square’s constructor?

A: Nope!

Q: Can the user create illegal Squares?

A:

Q: How?

A:

Q: How can we fix this?

A:

Page 63 © 2019 Kyle Burke cb

Page 64: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What is the difference?

A:

Let’s try private first and see if we can keep it thatway! (This is the best strategy.)

Q: Do we still have a problem between Square and Rectangle?

A:

Q: Is this code duplication?

A:

Q: What can we do about it?

A:

Page 64 © 2019 Kyle Burke cb

Page 65: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: What are we going to want in Rectangle now?

A:

Q: What should the setters look like?

A:

Q: Should we change the Rectangle constructor?

A:

This last step is called Refactoring, which we willdo a lot this semester.

Page 65 © 2019 Kyle Burke cb

Page 66: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Can I make the instance variables private? (If they’re notalready.)

A:

Q: Okay, so now how do we implementSquare.setSideLength?

A:

Q: Can we create illegal Squares?

A:

Page 66 © 2019 Kyle Burke cb

Page 67: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: How can we fix this?

A:

Q: What will the new Square.setWidth be?

A:

Q: Does that work?

A:

Q: How can we fix this?

A:

Page 67 © 2019 Kyle Burke cb

Page 68: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

Q: Does this code work?

A:

Q: Can I create illegal Squares?

A:

Q: Did we have to override any methods in Square?

A:

Q: Can unexpected things happen?

A:

Page 68 © 2019 Kyle Burke cb

Page 69: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

List<Rectangle> boxes = monkey.getBoxes();

//set all the boxes to have width 5.0; don’t

change height

for (Rectangle box : boxes) {box.setWidth(5.0);

}

Q: What could go wrong here?

A:

This is very dangerous!Guideline: Principle of Least Surprise - The user

should not be surprised when an object of type A hasunknown subtype B.

There are even more guidelines to help dissuade sub-classing based solely on the Is-A perspective:

Q: Sounds like we shouldn’t often have B subclass A... Whatif both A and B are immutable?

A:

Guideline: Class B, identical to A but with extra

Page 69 © 2019 Kyle Burke cb

Page 70: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

restrictions on its state, should not be a subclass of Aunless they are both immutable.

Notice that this fits the Math model. Everything inMath is immutable, thus every Square is also a Rect-angle without problem! (I don’t think Euclid was con-sidering modifier methods when writing Elements.)

It can be very easy to add lots of classes, but some-times they aren’t totally appropriate.

Q: What benefit does having a Square class have?

A:

Guideline: Remove classes with little or no uniquebehavior.

3.3 Polymorphism

Q: Do we need inheritance to use polymorphism?

A:

Page 70 © 2019 Kyle Burke cb

Page 71: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

3. WHEN TO INHERIT? CONTENTS

3.4 Summary

Q:

Let’s summarize what we’ve learned in this chapter. Whichof the following are good reasons to use inheritance vs ref-erencing?

• Code Reuse

• “Is-A”

• Matching Public Interfaces

• Polymorphism

A:

Page 71 © 2019 Kyle Burke cb

Page 72: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q:Bonus point: Which has better efficiency: Inheritance orReferencing? (Don’t ever make a programming decisionbased on this!)

A:

4 State Pattern

In our crusade to remove ugly conditionals, we enlistthe aid of the State Pattern, a more general version ofthe Null Object Pattern.

4.0 State Pattern Basics

The State Pattern is the simple paragon of polymor-phism.

⟨ Draw the following diagram: ⟩

Page 72 © 2019 Kyle Burke cb

Page 73: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

State Pattern

Context

- state : State

+ request()

in request:this.state.handle()

in request:this.state.handle()

State

+ handle()

ConcreteStateA

+ handle()

ConcreteStateB

+ handle()12

Q: What are the Participants?

A:

12From Design Patterns [2]

Page 73 © 2019 Kyle Burke cb

Page 74: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: What are the roles?

A:

• Context: Object that has a changeablestate.

• State: Abstract class for the differentstates.

• Each ConcreteStateX: One of the manystates to implement the handle method.

Q: Can we extend this pattern by adding another method toeach State class?

A:

4.1 Example: Debugging Print Modes

When coding my Google Hangouts bot, I spend a lotof time adding and removing debugging print state-ments. In the acceptNewChat method in my Hang-outsBot class, I decide to add a boolean flag field thattells me whether I want the debugging statements.

⟨ Draw the figure. ⟩

Page 74 © 2019 Kyle Burke cb

Page 75: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

HangoutsBot

- debugModeOn : boolean

+ acceptNewChat() : void

if (this.debugModeOn) {System.out.println("x=" + x);

}

Q: Problem here?

A:

Q: How might be make this more elegant?

A:

⟨ Draw this:

HangoutsBot

- debugMode : DebugState

+ acceptNewChat() : void

DebugState

- isOn : boolean

+ print(String): void

Page 75 © 2019 Kyle Burke cb

Page 76: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: How would I implement print?

A:

Q: How would I replace the code in the acceptNewChat

method?

A:

Q: Have we fixed most of the problem?

A:

Q: Have we used the State Pattern?

A:

Page 76 © 2019 Kyle Burke cb

Page 77: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: Our current state actually has two separate states. Whatare they?

A:

Q: So what should my states be?

A:

Q: What will that diagram look like?

A:

Page 77 © 2019 Kyle Burke cb

Page 78: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: Which classes here fill in for each of the State Pattern par-ticipants?

A:

Q: Now how do we implement print in the two classes?

A:

Q: Doesn’t this violate something? We’re nullifying a method!Which principle does this violate?

A:

Page 78 © 2019 Kyle Burke cb

Page 79: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: Could the situation get more complicated? If so, how?

A:

Q: How do we handle this?

A:

Page 79 © 2019 Kyle Burke cb

Page 80: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: What will that diagram look like?

A:

Page 80 © 2019 Kyle Burke cb

Page 81: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: What are the benefits of using the State Pattern?

A:

Q: What’s so cool about being able to extend by adding newState classes?

A:Can add new states even if you don’t have ac-cess to the source code for the Context class.Awesome!

Page 81 © 2019 Kyle Burke cb

Page 82: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

4.2 Example: Pokedex - Caught and UnseenPokemon

Q:

I’m out walking in the woods, hunting for Pokemon, whenI get a message from my younger sibling: “Hey! Have youseen a Bulbasaur yet? It’s Pokemon number 1!” I pull outmy Pokedex to see what it has to say about this species. IfI’ve never seen one, what does it tell me?

A:

Page 82 © 2019 Kyle Burke cb

Page 83: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q:I’m wondering how to explain to my younger sib that I’ma failure, but then I see a Bulbasaur! I throw a Pokeball atit and catch it! What does my Pokedex say now? (Note:saving the seen-not-caught state for later.)

A:

The implementation of this might be something like:

Pre-State-Pattern Pokedex

uses

Pokemon

+ getName(): String+ getImage(): Image+ getAvgHeight(): double+ getAvgWeight(): double+ getTypes(): List<PokeType>

Pokedex

- captured : List<Boolean>

+ viewPokemon(Pokemon) : Pane

Page 83 © 2019 Kyle Burke cb

Page 84: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: What might the implementation of viewPokemon look like?

A:

public Pane viewPokemon(Pokemon

pokemon) {int index = pokemon.getNumber();

boolean caught =

this.captured.get(index);

String name;

if (caught) {name = pokemon.getName();

} else {name = "???";

}Image image;

if (caught) {image = pokemon.getModel();

} else {image = this.getBlankImage();

}double height;

...

//the code that actually creates

the view

...

}

Page 84 © 2019 Kyle Burke cb

Page 85: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: What’s wrong with this?

A:

Q: There’s a simple fix to just have one conditional. What’sthat?

A:

Q: Why is this not a perfect fix?

A:

Page 85 © 2019 Kyle Burke cb

Page 86: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: Let’s employ the State Pattern. What are my participantsgoing to be?

A:

Q: Okay, now draw the new Class Diagram. (Hint: youshouldn’t modify the Pokemon class.)

A:

Page 86 © 2019 Kyle Burke cb

Page 87: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

State-Pattern Pokedex v0

*

Pokedex

- encounters : List<EncounteredState>

+ viewPokemon(Pokemon): Pane

EncounteredState

+ getName(Pokemon) : String+ getImage(Pokemon) : Image+ getAvgHeight(Pokemon) : double+ getAvgWeight(Pokemon) : double+ getTypes(Pokemon)

: List <Poketype>...

UnseenState

+ getName(Pokemon) : String+ getImage(Pokemon) : Image+ getAvgHeight(Pokemon) : double+ getAvgWeight(Pokemon) : double+ getTypes(Pokemon)

: List <Poketype>...

CaughtState

+ getName(Pokemon) : String+ getImage(Pokemon) : Image+ getAvgHeight(Pokemon) : double+ getAvgWeight(Pokemon) : double+ getTypes(Pokemon)

: List <Poketype>...

Page 87 © 2019 Kyle Burke cb

Page 88: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

+ viewPokemon(Pokemon): JPanel

Pokedex- encounteredStates: ArrayList<EncounteredStates>

<<abstract>>

EncounteredState

UnseenState

*

CaughtState

Q: What are some of the methods we want in theEncounteredStates?

A:

Q: Okay, let’s update the class diagram again!

Page 88 © 2019 Kyle Burke cb

Page 89: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

+ viewPokemon(Pokemon): JPanel

Pokedex- encounteredStates: ArrayList<EncounteredStates> + getName(Pokemon) : String

+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

<<abstract>>

EncounteredState

+ getName(Pokemon) : String+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

UnseenState

*

+ getName(Pokemon) : String+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

CaughtState

Page 89 © 2019 Kyle Burke cb

Page 90: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: How could we rewrite the viewPokemon method now?

A:

Q: Have we covered all the different states?

A:

Let’s add a new state: SeenUncaughtState⟨ Update the diagram!

Page 90 © 2019 Kyle Burke cb

Page 91: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

+ viewPokemon(Pokemon): JPanel

Pokedex- encounteredStates: ArrayList<EncounteredStates> + getName(Pokemon) : String

+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

<<abstract>>

EncounteredState

+ getName(Pokemon) : String+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

UnseenState

*

+ getName(Pokemon) : String+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

CaughtState

+ getName(Pokemon) : String+ getFigure(Pokemon) : Figure+ getHeight(Pokemon) : float

SeenUncaughtState

Q: How much code do we have to write in the Pokedex classto implement this change?

A:

Q: Why is this so awesome?

A:

Page 91 © 2019 Kyle Burke cb

Page 92: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

4.3 Example: Monopoly

Q: When rolling dice in Monopoly, what does getting ”dou-bles” allow you to do?

A:

Consider the case where there isn’t a maximum num-ber of turns you can stay in jail. (Normally, you mustbe released after three turns.)

⟨ Draw Class diagram for Monopoly Player. At-tributes:

• - currentLocation: MonopolySpace

• - inJail: boolean

• - doublesSoFar: int

And methods:

• + moveDistance(numberOfSpaces: int): void

• + moveToSpace(space: MonopolySpace): void

• + isInJail(): boolean

Page 92 © 2019 Kyle Burke cb

Page 93: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: What can we make more elegant using the State Pattern?

A:

Q: Which State Pattern participant role will the Monopoly-Player take?

A:

Q: Which fields should we be able to replace?

A:

Q: What shall we call this new state?

A:

⟨ Draw DoublesAndJailState:

• abstract!

• methods:

Page 93 © 2019 Kyle Burke cb

Page 94: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

– + processDiceRoll(die0:int, die1:int, player:MonopolyPlayer):

void

– + isInJail(): boolean

Q: In Groups: come up with a Class Diagram of your solution.Hint: my solution has no fields.

A:

Q: What does the isInJail method do in each?

A:

Page 94 © 2019 Kyle Burke cb

Page 95: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q:What would the processDiceRoll method look like inInJail? Hint: I added a setDoublesAndJailState to theplayer class.

A:

Page 95 © 2019 Kyle Burke cb

Page 96: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

4. STATE PATTERN CONTENTS

Q: Write processDiceRoll for the other three!

A:

Page 96 © 2019 Kyle Burke cb

Page 97: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

TODO: add more here. Find my notes; we did lots!

5 Singleton Pattern

TODO: add a class diagrams to the end of this section!Sometimes you only want to have a single instance

of an object. The Singleton Pattern is a means toenforce this.

Q:

Consider a room-scheduling object, RoomScheduler, whichkeeps track of when rooms on campus are scheduled. It hasmethods such as:

• isFree(Room, Date start, Date end)

• scheduleRoom(Room, Date start, Date end)

What is the problem with having multiple instances ofRoomScheduler?

A:

Page 97 © 2019 Kyle Burke cb

Page 98: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

5.0 Use Reluctantly!

Q:In order to implement the Singleton pattern, we need asingle “point of entry” to prevent people from creating newinstances of our object. What’s already a huge red flagabout this?

A:

Often, inexperienced programmers will think it’sokay to introduce a Singleton because they need toaccess some variable from anywhere. Don’t do this!Using an OO Design Pattern does not automaticallymean you’re using good design!

5.1 The Singleton Participant

Q:Goal: have a class where the constructor can’t be invokedby outside code. What’s wrong with just removing theconstructor?

A:

Page 98 © 2019 Kyle Burke cb

Page 99: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

Q: What can we do to make the constructor inaccessible byoutside classes?

A:

Common for other code to access the instance bydoing something like the following:

RoomScheduler scheduler =

RoomScheduler.instance;

scheduler.isFree(...);

Q: What does that mean must be in our code?

A:

Q: Where then are we going to call the constructor?

A:

Page 99 © 2019 Kyle Burke cb

Page 100: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

Q: Shivers of Joy or Shudders of Revulsion?

A:

Example: Here’s the code so far for a general Singleton:

public class Singleton {public static Singleton instance = new

Singleton();

private Singleton() {//constructor code goes here

}}

Q: When can the constructor be executed?

A:

Page 100 © 2019 Kyle Burke cb

Page 101: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

Q: Does that solve the problem this pattern sets out to solve?

A:

Q: Great! Is it well-designed?

A:

Q: Reasons for shudders?

A:

5.2 Removing the Public ”Constant”

Q: Let’s try to solve these design issues! How can we make thefield private?

A:

In the RoomScheduler case, here’s how we would

Page 101 © 2019 Kyle Burke cb

Page 102: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

get and use our singleton.

RoomScheduler scheduler =

RoomScheduler.getInstance();

scheduler.isFree(...);

Q: How can we implement the getInstance method? (In gen-eral or specifically for RoomScheduler.)

A:

There is a bit of an efficiency problem here. Some-times a Singleton can be a very heavy class, becauseit’s doing lots of concurrency-management stuff. Theconstructor may take a lot of time to execute. We maynot want the Singleton constructor to execute imme-diately upon execution of the code. This is especiallya problem if we’re testing the code; each time we testwe have to first wait for the constructor to execute!

Page 102 © 2019 Kyle Burke cb

Page 103: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

5.3 Delaying the Construction

Q: How can we use a Just-in-Time approach and not executethe constructor until we first access the instance?

A:

Q: Does this solve the problem?

A:

Q: Does it solve it well?

A:

Q: Why not? What design “red flags” do we have?

A:

Page 103 © 2019 Kyle Burke cb

Page 104: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

Q: Are there any practical problems remaining?

A:

Q: How could we have multiple threads doing lots of unneces-sary work? (And possibly cause big problems.)

A:

5.4 Solving the Race Condition

Q: We want Java to enforce that only one thread can executethe first branch of getInstance at a time. Can we do this?

A:

Page 104 © 2019 Kyle Burke cb

Page 105: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

Q:We can enforce that only one thread can invokegetInstance at a time. How does that work? Hint: it’s aJava keyword.

A:

Q: Sweet! No problems, right? Hint: think parallel efficiency.

A:

5.5 Java’s Solution to the Bottleneck

Q: Java has a special way to solve this problem: Lazy ClassLoading. What does that mean?

A:

Q: Does this work for inner classes?

A:

Page 105 © 2019 Kyle Burke cb

Page 106: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

Q: How can we use it to solve our problem?

A:

public class Singleton {private static class SingletonHolder {

public static Singleton instance =

new Singleton();

}private Singleton() {

//constructor code goes here

}public static getInstance() {

return SingletonHolder.instance;

}}

This solution lazy loading of inner classes was pro-posed by Bill Pugh13 as a new implementation of Java.See http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples#bill-pugh-singleton for more information.

13http://www.cs.umd.edu/~pugh/

Page 106 © 2019 Kyle Burke cb

Page 107: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

5. SINGLETON PATTERN CONTENTS

5.6 Example: LinkedIntList

TODO: Tree or Linked List? I should probably do aLinkedList here and have the Tree as an exercise.

5.7 When to use the Singleton Pattern

5.8 When to Use?

Q:

Which of the following are good reasons to use the SingletonPattern? Which are terrible reasons?

1. Want to be able to access fields/methods from any-where.

2. Want to enforce there is only one copy of an object.

3. Want a class that doesn’t require any state (no fields).

4. Want to force client code to be unable to call construc-tors.

A:

Page 107 © 2019 Kyle Burke cb

Page 108: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Some slam dunks with Singleton:

• Something that can only have one instance.

• States from State Pattern with no fields. (Youcan save on memory by only having one instanceof them.)

If you are ever in doubt, you should probably not beusing the Singleton Pattern.

6 Elegant Methods

Q: Recall the Query-Command Separation Principle. Whatdoes that say?

6.0 Public vs. Private Methods

An invariant is a statement about the state of an ob-ject that must be true. Examples:

• The size of a stack is equal to the number of stackframes.

• A balanced tree should have all leaves with depthequal to the height of the tree or one less.

• A max heap should have the greatest element atthe root.

Page 108 © 2019 Kyle Burke cb

Page 109: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q: If we had a Rodent class, what could an invariant of anobject in that class?

A:

One good way to debug is to write private methodsthat check the invariants. Then write a satisfiesInvariantsmethod to check all of them. The following examplecould be from a sorted Tree Set class:

private boolean satisfiesInvariants() {return (this.isBalanced()

&& this.satisfiesOrder() &&

this.hasNoDuplicates());

}

Q: What is the difference between public and private methods?

Q: When should you make a method private vs. public?

Consider the following methods inside the Rodent

class:

Page 109 © 2019 Kyle Burke cb

Page 110: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

• Public: mouse()

• Private:devilMouse() and angelMouse()

⟨ Write the code for mouse on the board:public void mouse() {

(Leave space here)

this.devilMouse();

(Leave space here)

this.angelMouse();

(leave space here)

} ⟩⟨ Let’s add some calls to satisfiesInvariants in here:

public void mouse() {System.out.println(this.satisfiesInvariants());

this.devilMouse();

System.out.println(this.satisfiesInvariants());

this.angelMouse();

System.out.println(this.satisfiesInvariants());

} ⟩

Q: For which of those statements is it okay to print false?

A:

Page 110 © 2019 Kyle Burke cb

Page 111: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q: Why?

A:

Let’s restate that as a guideline:Guideline: Invariants need to be satisfied between

any public method calls.TODO: more here? Check with written notes.

6.1 Method Documentation

Q: What is the difference between internal documentation andexternal documentation?

A:

Q: How is this specifically relevant to compiled languages?

A:

Page 111 © 2019 Kyle Burke cb

Page 112: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q: What’s the problem? Hint: similar to code and data dupli-cation...

A:

TODO: add more in here from the written notes(And in the Javadoc stuff that starts on page 16.)

6.2 Pre/Post Conditions

Q: Documentation should always state the pre- and post-conditions for a method. What are pre-conditions?

Q: What are post-conditions?

Consider the following implementation of Double:

Double

+ squareRoot() : Double+ getRoot(root) : Double

Page 112 © 2019 Kyle Burke cb

Page 113: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q: What are the pre- and post-conditions of squareRoot?

A:

Q: What are the pre- and post-conditions of getRoot?

A:

Page 113 © 2019 Kyle Burke cb

Page 114: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q:

Recall the Liskov Substitution Principle (Section 3.0): ”Itis okay for B to subclass A only if for each method in bothA and B: B’s method takes all the inputs that A’s takes(and possibly more) and does everything that A’s does (andpossibly more).”Does it seem like we can rephrase this using pre- and post-conditions?

A:

Q:

Let’s use < to mean ”less strict than”. Fill in the boxesusing either ≤ or ≥:It is okay for B to subclass A if, for all methods M in bothA and B (MA and MB):

• preconditions(MA) � preconditions(MB), and

• postconditions(MA) � postconditions(MB)

A:

Let’s do an example! Go back to our square rootexample. Let’s assume there’s a Double.getRoot(int

degree) method. This could be used in the followingway:

Page 114 © 2019 Kyle Burke cb

Page 115: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Double double = new Double(125.0);

double cubedRoot = double.getRoot(3);

System.out.println(cubedRoot); //should be 5.0

Consider subclassing Double in the following way:

Double

+ Double(double)+ squareRoot() : Double+ getRoot(root) : Double

Complex

+ Complex(double real, double imag)

Q: Is there any benefit to this?

A:

Yes, because we can now return complex num-bers if we take the square root of an imaginarynumber. Example:Complex c = new Complex(-1, 0);

TODO: give an example, e.g.√

4− 4i

Page 115 © 2019 Kyle Burke cb

Page 116: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q: What will the pre and post conditions be?

A:

6.3 Overriding Clone

Q: Let’s do an example. What’s the Cloneable interface?(Which method does it enforce?)

A:

Page 116 © 2019 Kyle Burke cb

Page 117: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Q: In intro programming, we learned about two types of clones.What were they?

A:

Q:

Which type of clone is this (in the Triangle class, whereeach field is a Point object.)? (Note: you should alwaysstart with a call to the super class’s clone method, as wewill see.)public Object clone() {

Triangle copy = (Triangle)

this.super.clone();

copy.p0 = this.p0;

copy.p1 = this.p1;

copy.p2 = this.p2;

}

A:

⟨ Draw this code, then the resulting object diagram:Point origin = new Point(0,0);

Point right = new Point(3,0);

Point up = new Point(0, 4);

Page 117 © 2019 Kyle Burke cb

Page 118: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

6. ELEGANT METHODS CONTENTS

Triangle rightTriangle = new Triangle(origin,

right, up);

Triangle rightClone = (Triangle) rightTriangle.clone();

Q: Why is the shallow clone dangerous?

A:

Q:

There’s another problem here. What if we clone in thefollowing code:Collection<Triangle> triangles =

landscape.getTriangulation();

Collection<Triangle> copies = new

ArrayList<Triangle>();

for (Triangle triangle : triangles) {Triangle copy = (Triangle) triangle.clone();

copies.add(copy);

}What could be a problem here? Hint: what’s the

type of triangle?

A:

Page 118 © 2019 Kyle Burke cb

Page 119: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What do we need to do to get clone to return aColorTriangle?

A:

Q: Okay, let’s fix the shallow problem first. How can we rewritethe clone method to deepen itd?

A:

7 Elegant Classes

Yet another big section of information I could give youbefore you start work on even your first project...

Q: When you are first given a new Project, should you startoff by implementing the project?

A:

Page 119 © 2019 Kyle Burke cb

Page 120: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

7.0 Pre-Implementation Steps

7.0.0 Read the Project Spec(ification).

7.0.1 Ask Questions!

Usually the spec will not be fully clear. Now is a greattime to clarify anything you’re not certain about. (Intrue Agile Development, this should be easy becauseyou have access to the Customer Representative14 atall time. Questions can be asked at any point in theprocess!)

7.0.2 Come up with Use Cases.

Q: What is a use case?

A:

For example, when I took this course in 2002, wehad to create a program for playing sounds. Here’s anexample use case for an early version of the program:

• User starts running the program. A window ap-pears with a large empty box. Next to the emptybox are two columns of buttons with one simple

14See section 12.2 for more information about the role of the Customer Representative

Page 120 © 2019 Kyle Burke cb

Page 121: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

image on each. One has a cat, another a car. Thebutton with a dog is selected already. Below theempty box is a button with the Play symbol on it.

• The user clicks in the empty box. A rectangle withthe dog image appears at the mouse click. (We’llrefer to this box as the Sound Panel from here on.)

• The user clicks the play button and a red line ap-pears at the left-hand side of the Sound Panel,and moves from left-to-right. When it reaches theDog-rectangle, it continues to move while a bark-ing noise is heard. The sound ends exactly as thered line reached the right-hand side of the dog-box.The red line continues to the right until it reachesthe end of the Sound Panel and disappears. Theplay button remains disabled while the red line ismoving.

• The user clicks on the car button on the buttonpanel. It becomes selected and the dog buttonbecomes unselected.

• The user clicks on the sound panel again and arectangle of different width than the dog rectanglewith the cat image appears where the mouse wasclicked.

• The user clicks again and another cat rectangleappears.

• The user clicks the play button and the red linemoves across the sound panel again. It plays thesound of each rectangle while it’s touching thatbox. The height of the box in the sound panel

Page 121 © 2019 Kyle Burke cb

Page 122: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

does not change the sound produced by each box.

7.1 Extract Nouns and Verbs

7.2 CRC (Class-Responsibilities-Collaborators)Cards

TODO: way more to put here!2016: skipped to Cohesion

7.3 Cohesion

Guideline: Cohesion: Every class should model ex-actly one concept and model it well.

Q: What are some the benefits of following this guideline?

A:

Q: What are some good examples of classes?

A:

Page 122 © 2019 Kyle Burke cb

Page 123: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Often times, you’ll see a name that looks like this:BigFiletOMacFish. Red flag!

Q:

What’s wrong with this class?

- name : String- age : int- address : String- make : String- model : String- mileage : int

CarOwner

A:

Q: What’s a better solution?

A:

Page 123 © 2019 Kyle Burke cb

Page 124: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: How can we measure cohesion?

A:

Guideline: Give classes a complete interface.

7.4 Responsibilities

Sometimes we have some functionality that we want towrite, but it’s not clear which object should implementthe method. This is often a very difficult decision.Let’s talk about how to make this choice.

Guideline: Different kinds of responsibilities shouldbe delegated to different classes.

Q: What are common types of responsibilities?

A:• Knowing

• Doing

• Controlling/deciding

Page 124 © 2019 Kyle Burke cb

Page 125: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What does each of these mean?

A:

Another useful rule is the Expert PatternGuideline: Expert Pattern: The object that con-

tains the necessary data to perform a task should bethe object that performs the task.

Q: How could I rephrase this as a fake JFK quote?

A:With a JFK accent: ”Think not what you cando for an object, but what that object can dofor itself.”

Page 125 © 2019 Kyle Burke cb

Page 126: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: Is the Expert Pattern an Object-Oriented Design Pattern?

A:No! In your projects, when I ask you to listthe design patterns used, please please pleasedo not list this!

Q: Does the Expert Pattern get violated?

A:

All the time, and for good reason. For example,if you have a graph object, it is often better tobuild a separate traversing object for specifictasks than to expect the graph class to do it foryou.

Q: Which guideline is often in conflict with the Expert Pat-tern?

A: Cohesion.

Page 126 © 2019 Kyle Burke cb

Page 127: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: Why?

A:

Q: Example: what methods does the String class have?

A:

Page 127 © 2019 Kyle Burke cb

Page 128: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What are some methods the String class does not have,despite having all (or most) the necessary data?

A:

Q: Since it’s not in there, does that mean it violates the ExpertPattern?

A:

Not really. Technically yes, but the Expert Pat-tern always needs to be tempered by consider-ing ”What is actually appropriate for the re-sponsibilities for this class?” Only appropriateoperations should be included. isPalindrome

might not be appropriate because it’s not some-thing commonly executed on strings.

For more on what’s appropriate, we have the fol-lowing Guideline:

Guideline: Give each class a complete interface.

Q: What does this mean?

A:Each class should have the full set of appropri-ate behavior to perform all actions reasonablefor their role.

Page 128 © 2019 Kyle Burke cb

Page 129: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

This is a good intersection between the Expert Pat-tern and Cohesion.

Here’s another related guideline:Guideline: Give each class a consistent interface.

Q: What does this mean?

A: Simply that methods that do similar thingsshould be laid out similarly.

Q: What are some places that are often inconsistent?

A:

• Different methods that do similar thingswith arguments out of order. E.g.

– printRepeatedString(String, int)

: void

– multiplyString(int, String) :

String

Avoid this!

• Sometimes similar methods can havedifferent names across classes. E.g.String.length() and ArrayList.size() (or anyCollection.size()).

Page 129 © 2019 Kyle Burke cb

Page 130: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

15

7.5 Immutable Classes

Skipped in 2017!

7.6 Coding to Interfaces

Guideline: Code to interfaces, not classes.

Q: What does this mean?

A:

Whenever possible, write code that referencesother types as abstractly as possible. Thismeans two things:

• Use Interfaces instead of classes.

• If you can’t use an interface, go as high upthe directory tree as possible.

Consider the following classes:

15The inconsistency with length and size probably occurred before ArrayList wasaround. Prior to that, programmers were using the Vector class as an array-based wrapper.The Vector class models mathematical vectors, so it was designed with size() instead oflength(), since vector length means something other than the number of elements.

Page 130 © 2019 Kyle Burke cb

Page 131: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Wolverine Handling v0

uses

Wolverine

+ getAngerLevel() : int

AnimalHandler

+ getAngries(Iterable<Wolverine>) :ArrayList<Wolverine>

... and this implementation of getAngries:public ArrayList<Wolverine> getAngries(ArrayList<Wolverine>

wolverines) {ArrayList<Wolverine> angries = new ArrayList<Wolverine>();

for (Wolverine : wolverines) {if (wolverine.getAngerLevel() > 10) {

angries.add(wolverine);

}}return angries;

}Here’s the relevant hierarchy with ArrayList:

Page 131 © 2019 Kyle Burke cb

Page 132: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

ArrayList and Above

�interface�Iterable

+ iterator() : Iterator<E>

You can use afor-each loop onanything that’san Iterable.

You can use afor-each loop onanything that’san Iterable.

Collection

+ add(E) : void+ size() : int+ contains(E) : boolean...

List

+ get(int) : E...

ArrayList LinkedList

Page 132 © 2019 Kyle Burke cb

Page 133: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q:Let’s think about changing things to follow the spiritof ”Coding to Interfaces”. Could we generalize thewolverines parameter?

A: Yes!

Q: Great! How general could we make it?

A: Iterable<Wolverine>

Page 133 © 2019 Kyle Burke cb

Page 134: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What else do we have to change? What does our code looklike afterwards?

A:

New version:Wolverine Handling v1

uses

Wolverine

+ getAngerLevel() : int

AnimalHandler

+ getAngries(Iterable<Wolverine>) :ArrayList<Wolverine>

Page 134 © 2019 Kyle Burke cb

Page 135: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: Why can we do that?

A:

Q: What could I choose for the options for the return type ofgetAngries?

A:

Any of:

• ArrayList

• List

• Collection

• Iterable

Q: Which is best?

A:It’s not immediately clear. There’s a benefit tobeing more general and a benefit to being morespecific!

Page 135 © 2019 Kyle Burke cb

Page 136: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What’s the benefit to being more general?

A:You can change the actual return type insidethe method to another subtype of the returntype without affecting any code that calls it.

Q: What’s the benefit of being more specific?

A:Code calling your method may have more func-tionality they can use. (E.g. List has manymore methods than Iterable.)

Q: What do we definitely not want to have as the return type?

A: ArrayList: it offers no extra functionality overList.

Page 136 © 2019 Kyle Burke cb

Page 137: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q:Okay, let’s pretend nothing else is calling this method yet,so we can change it to whatever we want without affectingother code. What should we actually do?

A:Probably Collection or List. Let’s use Collec-tion, because it has so much to offer but isn’tas restrictive as List.

Q: Okay, change your code to match this change.

A:

New version:

Page 137 © 2019 Kyle Burke cb

Page 138: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Wolverine Handling v2

uses

Wolverine

+ getAngerLevel() : int

AnimalHandler

+ getAngries(Iterable<Wolverine>) :Collection<Wolverine>

Q: Can we improve the internals of getAngries?

A: Absolutely!

Page 138 © 2019 Kyle Burke cb

Page 139: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What should we do? Hint: Code to Interfaces!

A:

Q: Why can’t we declare it as an Iterable?

A:

Two reasons:

• We need to return a Collection, and

• We call the add method on it, which is inCollection (not Iterable)

Page 139 © 2019 Kyle Burke cb

Page 140: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q:

Okay, one more generalization. Many members of theMustelid family of mammals are known for being ornery(e.g. wolverine, badger, and honey badger). What if allMustelids have the getAngerLevel method? How can wegeneralize further?

A:

New version:Wolverine Handling v3

uses

Mustelid

+ getAngerLevel() : int

Wolverine

+ getAngerLevel() : int

Badger

+ getAngerLevel() : int

HoneyBadger

+ getAngerLevel() : int

AnimalHandler

+ getAngries(Iterable<Mustelid>) :Collection<Mustelid>

Page 140 © 2019 Kyle Burke cb

Page 141: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What does the new code look like for getAngries?

A:

Q: What would be even better than Mustelid?

A:

If we have an Angerable interface:

�interface�Angerable

+ getAngerLevel() : int

Final version:

Page 141 © 2019 Kyle Burke cb

Page 142: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Wolverine Handling v4

uses

�interface�Angerable

+ getAngerLevel() : int

Wolverine

+ getAngerLevel() : int

Badger

+ getAngerLevel() : int

HoneyBadger

+ getAngerLevel() : int

AnimalHandler

+ getAngries(Iterable<Angerable>) :Collection<Angerable>

Page 142 © 2019 Kyle Burke cb

Page 143: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What does this final version of the getAngries method looklike?

A:

Q: What’s the benefit of coding to interfaces?

A: You grant lots of Freedom both to other codeand to the internals of your own code.

Page 143 © 2019 Kyle Burke cb

Page 144: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

7.7 Coupling

Q:From the first version to the final version of the Wolverine-Handling code, what’s different about the connection be-tween Wolverine and Animal Handler? Hint: graphical ex-planations are expected!

A:• There’s an extra box (Interface/Class) be-

tween them.

• Part of the connection is a dashed line in-stead of a solid line.

Q: What does this highlight?

A: The independence of AnimalHandler andWolverine.

Q:Sometimes you will find classes that are very dependent onone another. We say these classes are tightly coupled. Isthis good or bad?

A:Bad! You want to minimize the interconnec-tions between different parts of the program,either single classes or groups of classes.

Page 144 © 2019 Kyle Burke cb

Page 145: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What if two different parts of a class diagram have lots ofinterconnections between each other?

A:

Q: What do we want to do instead? (There are lots of ways torefer to this.)

A:

• Decouple classes, or minimize coupling.

• Minimize interdependence between classes.

• Keep classes orthogonal (another word forperpendicular)

16

16The term orthogonal comes from vectors. Two vectors have a dot product of zeroexactly when they’re orthogonal. It means the two vectors neither agree nor disagree atall.

Page 145 © 2019 Kyle Burke cb

Page 146: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

17

Q: How can I rephrase this if I think of a class diagram as agraph?

A:

17Source: https://twitter.com/jezenthomas/status/576376992167276544

Page 146 © 2019 Kyle Burke cb

Page 147: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What is the benefit of minimizing coupling?

A:

7.8 Encapsulation and Information Hiding

TODO: is this really a good transition to Encapsula-tion and Information Hiding?

As a result of decoupling classes, they become moreself-contained. In order to keep them independent, weconceal their actual implementation. This is calledinformation hiding.

Page 147 © 2019 Kyle Burke cb

Page 148: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What practices are part of Information Hiding?

A:

• Using private fields instead of public fields.

• Making some methods private (espe-cially those that might not maintain theinvariants—see the previous section on that(TODO: ref that)).

• ”What, not How”: Including documenta-tion that only describes what code does, nothow it works.

• Anything other practice that conceals theimplementation of code.

Q: When do we violate this?

A:

Sometimes it’s necessary to include some de-tails about how the underlying code works inorder to convince programmers that it’s worthusing. For example, Java’s ArrayList class ex-plains that the add method can run in Θ(n)time sometimes, but runs in Θ(n) time whenamortized over n runs. Some of the details arehidden here, but some are revealed to ensurethat good algorithms are used in the class.

Page 148 © 2019 Kyle Burke cb

Page 149: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What do we call a class that uses good information hiding?

A:These classes are encapsulated, meaning there isa ”logical” wall separating their internals fromthe outside world. In order to use the class, youneed to use the interface specified in the API.

Q: Can we do this with all classes?

A:No! Sometimes there are pairs or small groupsof classes that are tightly coupled and kind ofneed to be. (There is an example in the Com-posite Pattern section (TODO - make a ref))

Tightly Coupled Class Group v0

ClientA

ClientB

ClientC

TightA

TightB

TightC

Page 149 © 2019 Kyle Burke cb

Page 150: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

7. ELEGANT CLASSES CONTENTS

Q: What should we do in that case?

A:Encapsulate the group of classes instead of asingle class. If possible, have your other classesinteract only with one of the classes, a ”point-of-contact”.

In this example, TightA is the single point-of-contactclass for the whole group.

Tightly Coupled Class Group v1

ClientA

ClientB

ClientC

TightA

TightB

TightC

Q: What can we do after do to further encapsulate things aftercreating a single point of contact?

A:Make the other classes private (static?) classesof the point of contact. That way other codecan never use them directly! All the implemen-tation of the group is hidden.

Page 150 © 2019 Kyle Burke cb

Page 151: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

TODO: add another image here after we figure outhow to do inner classes in class diagrams and tikzuml.:)

7.9 Example: Known and Unknown Prices

TODO: Use the Price.java you wrote for the Bot here.Show how that evolved! :)

8 OODP: Composite Pattern

Sometimes we want to treat collections and individualobjects the same way.

8.0 Pac Man

Consider the following: I’m making a poster aboutthe history of video games. I’m making the poster inLibreOffice18 and I start by making a few objects. Imake the following three single objects:

⟨ Draw this:

19 ⟩18http://www.libreoffice.org/19Yes, I did make this in Libre Office.

Page 151 © 2019 Kyle Burke cb

Page 152: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Which classic character can I make from these?

A:

⟨ Draw the combination:

Q:I’m probably going to be using this combination a bunch.Copy-pasting, resizing, etc. What should I do with bothof these? (Hint: it’s a LibreOffice thing and probably alsosomething you can do in other graphics programs.)

A:

Q: Sweet! Who else might be an important character to in-clude on my poster? Hint: similar in drawing to Pac-Man.

A:

Page 152 © 2019 Kyle Burke cb

Page 153: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: How do I ”draw” Ms. Pac-Man?

A:

⟨ Draw Ms. Pac-Man:

Q: How do I draw a hairbow?

A:

Q: Now what do we do?

A:

Page 153 © 2019 Kyle Burke cb

Page 154: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Which kind of data structure is the grouping like?

A:

⟨ Draw the tree:

Page 154 © 2019 Kyle Burke cb

Page 155: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Which figures are the leaves?

A:

Q: Which are the internal nodes?

A:

Q: Often we have a collection of objects that we want to actas a single object. How can we do this?

A:

8.1 Composite Pattern Specifics

The idea here is that we want our object to be eithera leaf or a composite object.

⟨ Draw the initial figure: (note the space left blankfor Composite fields!)

Page 155 © 2019 Kyle Burke cb

Page 156: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

+ operation(L) : x

<<abstract>>

Component

+ operation(L) : x

Leaf

+ operation(L) : x

Composite?

⟩Composite Pattern v0

Component

+ operation() : Object

Leaf

+ operation() : Object

Composite

— ??

+ operation() : Object

Page 156 © 2019 Kyle Burke cb

Page 157: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Then I could give the Composite class a Collection<Leaf>

objects. Does that solve the problem?

A:

Q: What should the Composite have instead? Hint: to gettrees of any level?

A:

⟨ Draw the figure:

+ operation(L) : x

<<abstract>>

Component

+ operation(L) : x

Leaf *

+ operation(L) : x

Composite or 2

Page 157 © 2019 Kyle Burke cb

Page 158: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Composite Pattern v1

2..*

Component

+ operation() : Object

Leaf

+ operation() : Object

Composite

+ operation() : Object

TODO: add the figure from https://www.reddit.

com/r/ProgrammerHumor/comments/60lm55/oop_what_

actually_happens/

Multiple ways to implement Composite:

• Constant number of ”children” (usually 2) E.g.left : Component, right : Component.

• Variable number of children: children : Collection<Component>

Q: If we’re doing the 2-Component-field option, what does theComposite constructor look like?

A:

Page 158 © 2019 Kyle Burke cb

Page 159: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: What class is missing from our picture?

A: A Client

Q: Which classes will the Client interact with?

A:

TODO: include a figure with the Client and a usesconnection to the Component.

Q: Why is this good?

A:Information Hiding: Hiding the implementa-tion of the class. Client doesn’t need to knowthat we’re using the Composite Pattern.

Page 159 © 2019 Kyle Burke cb

Page 160: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: How should the Client create a multi-Component element?

A:

Expect one of these answers:

• Call the Composite constructor.

• Call an add method (or something likethat) in the Composite class.

Q: Which should we do?

A:

Q:Okay, what’s the signature going to look like for thismethod? That signature will go in the abstract Compo-nent class.

A: public void add(Component other)

Page 160 © 2019 Kyle Burke cb

Page 161: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Can this method be a modifier?

A:

Q: So what does add have to be?

A: Pure function!

Q: What’s the return type? Actually, what’s the entire signa-ture going to be?

A: public Component add(Component other)

Q: Okay, so what do we put in the abstract class?

A:The abstract stub:public abstract Component add(Component

other);

Page 161 © 2019 Kyle Burke cb

Page 162: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: How does that work?

A:

Q: Okay, let’s implement the add method for the Leaf class.

A:

Q: Now write the add method for the Composite class.

A:

Q: Oh no! Repeated code! What should we do here?

A:

TODO: is there a relevant refactoring I can mention

Page 162 © 2019 Kyle Burke cb

Page 163: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

here?We’re going to do this for a lot of the methods in

the Composite Pattern. Some are really easy to write;others are more difficult. If they’re ever the same inboth subclasses, we can move them up to the superclass.

8.2 Composite Nim

Okay, we’ve been abstract enough. Let’s talk aboutan example: Nim.

⟨ Describe the game of Nim. Play on a 3, 5, 7 board.Explain the winning strategy, because it’s pretty cool.⟩

Page 163 © 2019 Kyle Burke cb

Page 164: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q:

Here’s some client code (say in NimEnthusiast) creatingthe board we started with:Nim top = new NimRow(3);

Nim middle = new NimRow(5);

Nim bottom = new NimRow(7);

Nim topTwo = top.add(middle);

Nim game = topTwo.add(bottom);

System.out.println(game);

Collection<Nim> options = game.getOptions();

What do we need to do to make this work?

A:

Q: Okay, let’s use the Composite pattern here (big surprise).What will the participants be?

A:

• Component → Nim.

• Leaf → NimRow

• Composite → CompositeNim

• Client → NimEnthusiast

Page 164 © 2019 Kyle Burke cb

Page 165: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: What fields will CompositeNim have?

A:

Q: What about the fields for NimRow?

A:

Here’s the class diagram for what we’ve got so far.Note: can’t get the attribute to jump out yet.

Nim v0

2

uses

Nim

+ add(Nim) : Nim+ toString() : String+ getOptions() :

Collection<Nim >

NimEnthusiast

NimRow

- numSticks : int CompositeNim

- left : Nim- right : Nim

+ CompositeNim(Nim, Nim)

Page 165 © 2019 Kyle Burke cb

Page 166: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Why didn’t I put toString and getOptions in the sub-classes?

A:

Q: Next let’s write the constructor for the Nim class as theNimEnthusiast uses above. Write it!

A:

Q: Let’s implement add next. Where am I going to implementthis?

A: Nim

Page 166 © 2019 Kyle Burke cb

Page 167: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Why can we do this? What’s the code?

A:

Q: Let’s implement toString() next. Where does this codeneed to go?

A: Just the actual implementations in NimRowand Composite Nim

Q: Why don’t we need a stub in Nim?

A:

Page 167 © 2019 Kyle Burke cb

Page 168: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Implement toString in NimRow.

A:

Q: Now implement toString in CompositeNim.

A:

Wow, that was super easy! This is how most of themethods should be in the Composite Pattern.

Page 168 © 2019 Kyle Burke cb

Page 169: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Let’s add hasMoves() : boolean to the Nim interface.Where do we need to add code?

A:• abstract stub in Nim:

public abstract boolean hasMoves();

• implementation in NimRow and Compos-iteNim

Q: Where will the JavaDoc go?

A:

Q: What are we adding to NimRow?

A:

Page 169 © 2019 Kyle Burke cb

Page 170: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: What’s the code for CompositeNim?

A:

Q: Next let’s write getMoves() : Collection<Nim>. Whereare we going to put code?

A:

Q: Implement getMoves in NimRow.

A:

Page 170 © 2019 Kyle Burke cb

Page 171: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q:Okay, now implement getMoves in CompositeNim. (Youmay have to show an example of all the moves from, say,two piles: 3, 4.)

A:

Q: Can we now change hasMoves to reduce the number of im-plemented methods?

A: Yes! Move hasMoves() up to Nim!

Page 171 © 2019 Kyle Burke cb

Page 172: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: What will the implemented version of that look like in Nim?

A:

Note: This is as far as I got in 2017. We talkedabout equals, but didn’t get there.

Here’s where I get most years.

2

Nim

+ hasMoves() : boolean+ getMoves() : Collection<Nim>

NimRow

- numSticks : int

+ NimRow(int)+ getMoves() : Collection<Nim>+ toString() : String

CompositeNim

- left : Nim- right : Nim

+ CompositeNim(Nim, Nim)+ getMoves() : Collection<Nim>+ toString() : String

Q: We’d probably like a hasMove(Nim) : boolean method,but it will be much easier if we do which other method first?

A:

Page 172 © 2019 Kyle Burke cb

Page 173: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Let’s see if we can agree on when two Nim games should beequal. Are 3, 5, 7 and 7, 3, 5 equivalent?

A:

Well, yes, but it’s a bit odd. A player might besurprised if they moved from 3, 6, 7 to 7, 3, 5.It really depends on what we’re doing here. Forour purposes, let’s say they’re not equivalent.(i.e. order matters)

Q: How many different ways can we represent the game 3, 5,7 with our code?

A:

Q:Let’s add equals(Object) : boolean to the Nim in-terface. Plan: abstract equals(Nim) in Nim, imple-mented equals(Object) : boolean in Nim, then imple-ment equals(Nim) in subclasses, which comes next...

A:

Page 173 © 2019 Kyle Burke cb

Page 174: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q:Let’s add equals(Nim) : boolean to the NimRow class.Hint: also include a equals(NimRow): boolean methodhere.

Q:Now let’s add equals to the CompositeNim class. Does theorder of the rows in a Nim board really change the game atall?

A:

Oh yikes! That’s a problem. To handle this, let’swrite a protected toMap() method that returns aMap<Integer, Integer>. Then we can just test theequality of two maps.

⟨ Describe Maps if someone is not familiar withthem. ⟩

Q: Okay, let’s write toMap. First the NimRow version!

A:

Q: Okay, now the CompositeNim version of toMap.

A:

Page 174 © 2019 Kyle Burke cb

Page 175: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Okay, now let’s write equals for the CompositeNim class.

A:

Q: Does anyone see something we can do to clean things up?

A:

Q: Now let’s add hasMove(Nim) : boolean. Can we imple-ment this in the abstract class?

A:

Q: What does the code for that look like? Hint: Can you writeit in one line?

A:

⟨ Describe algorithm for determining whether a Nimposition has a winning move. ⟩

Page 175 © 2019 Kyle Burke cb

Page 176: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

8. OODP: COMPOSITE PATTERN CONTENTS

Q: Let’s write a hasWinningMove() method. Is there a methodwe might want to write first?

A:

Q: Okay, let’s write the getNimSum. First in the NimRow class.

A:

Q: Okay, now for the CompositeNim class.

A:

Q: Okay, now where should we implement hasWinningMove()?What’s the code for that?

A:

Page 176 © 2019 Kyle Burke cb

Page 177: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

9. OODP: FACTORY METHOD PATTERN CONTENTS

9 OODP: Factory Method Pattern

Sometimes we either can’t or don’t want to have theuser call a constructor to create an object. In that case,it might be time to use the Factory Method Pattern.

9.0 Example: Nim

Continuing from the Nim example introduced in sec-tion 8.2 we have overlooked one vital piece: we can’tcreate Nim objects! Issues:

• Can’t initialize Nim objects: it’s abstract.

• User shouldn’t interact with the Leaf or Compositeclasses in the Composite Pattern, so can’t call theconstructor there.

Q: Why shouldn’t the user interact with those classes?

A:

Q: How do we get around not using the constructor for thesubclasses directly?

A:

Page 177 © 2019 Kyle Burke cb

Page 178: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

9. OODP: FACTORY METHOD PATTERN CONTENTS

Q: Which class should createNim be implemented in?

A:

Q:To start off, let’s have this method always return the game:3, 5, 7. How are we going to use it? (Write a line of codefor a Client class.)

A:

Q: So is our method going to be static or not?

A:

Page 178 © 2019 Kyle Burke cb

Page 179: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

9. OODP: FACTORY METHOD PATTERN CONTENTS

Q: Implement the method!

A:

Page 179 © 2019 Kyle Burke cb

Page 180: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

9. OODP: FACTORY METHOD PATTERN CONTENTS

Q:Remember how we learned about coding to interfaces. Let’spractice that now! How can we change the declared typesof the variables in that method?

A:

Q: It’s slightly inelegant to use the CompositeNim and NimRow

constructors. Why is that?

A:

Q: How could we fix this problem?

A:

Page 180 © 2019 Kyle Burke cb

Page 181: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

9. OODP: FACTORY METHOD PATTERN CONTENTS

Q: Okay, what does our class diagram look like now?

A:

Q: It looks like NimFactory is very tightly coupled with thethree Nim game classes. How do we fix that?

A:

Q: What do I do if I want to create something other than the3-5-7 board? Let’s create random boards!

A:

Page 181 © 2019 Kyle Burke cb

Page 182: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

9. OODP: FACTORY METHOD PATTERN CONTENTS

9.1 Factory Method Pattern Basics

Q: What does the Factory Method class diagram look like?

A:

creates

Client

�interface�Product

ConcreteProduct

Creator

+ factoryMethod() : Product ? operation() : void

ConcreteCreator

+ factoryMethod() : Product

Page 182 © 2019 Kyle Burke cb

Page 183: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

9.2 Factory Method with State Pattern

TODO: drawing of RandomNimFactory subclassingNimFactory.

Q: Why is this better?

A:

TODO: more here! Three factories: StandardNimFactory,SpecifiedNimFactory, and RandomNimFactory.

10 OODP: Command Pattern

Often we want to treat executable code as a reference-able/passable/storeable value. Example: OS sched-ules jobs. Solution: keep a priority queue of jobs toexecute, possible if each job is storeable.

Q:In some programming languages, you can do this with func-tions. Called: ”first-order functions”. What are some lan-guages you know that act like this?

A:

Luckily a solution exists even for languages like Javawithout first-order functions: the Command Pattern.

Page 183 © 2019 Kyle Burke cb

Page 184: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

10.0 Command Pattern Specifics

Four main participants:

• Command: interface with an execute() : void

method.

• ConcreteCommand: implementes the Command in-terface, encapsulating the action.

• Invoker: The class that invokes the execute()

method of the Command objects.

• Client: The class that creates the ConcreteCommandobjects and sends them to the Invoker.

⟨ Draw this figure: ⟩

Page 184 © 2019 Kyle Burke cb

Page 185: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Command Pattern

0..*

createsuses

�interface�Command

+ execute() : void

ConcreteCommand

— receiver : Receiver

+ execute() : void

public void execute() {this.receiver.action();

}

public void execute() {this.receiver.action();

}

Invoker

- commands : Command(s)

Receiver

+ action() : void

Client

Page 185 © 2019 Kyle Burke cb

Page 186: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q: What is the advantage of separating the Invoker andClient?

A:

Q: Can the Invoker store commands?

A:

Q: What are some other benefits?

A:

Page 186 © 2019 Kyle Burke cb

Page 187: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q: Does Java have a similar class to Command?

A:

Q: What is especially awesome about the Runnable class.

A:

10.1 Example: Web Browsing

I’ve created a bare-bones WebBrowser class with onemethod:

Web Browser v0

WebBrowser

+ loadPage(String url) : void

loadPage does all the necessary stuff to actuallyload a page into the browser.

Page 187 © 2019 Kyle Burke cb

Page 188: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q:Next I would like to add Back and Forward buttons,so I’m going to add two new methods: goBack() andgoForward(). What do I need to keep track of?

A:All the previous pages I’ve visited and, afterpushing the back button, pages to go forwardto!

Q: How should I model going forward and backwards?

A: Use Commands!

Q: What should we name our command?

A: I named them BrowseCommand

Q: What should it implement?

A: Runnable already exists in Java, so let’s usethat.

Page 188 © 2019 Kyle Burke cb

Page 189: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Web Browser v1

WebBrowser

+ loadPage(String url) : void

�interface�Runnable

+ run() : void

BrowseCommand

+ run() : void

Q: Should the WebBrowser be calling the run method directly?

I would like a WebBrowser class with:

• + goToPage(String url):void (Called when alink is clicked new URL is typed into the addressbar or a link is clicked.)

• + goBack():void

• + goForward():void

We’ll assume there is another method that does the ac-tual loading of a page: loadPage(String url):void

Assume this one is already implemented.Let’s use the Command Pattern to implement the

other three methods. Plan:

Page 189 © 2019 Kyle Burke cb

Page 190: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

• use a Command for moving to a new page. (WebBrowseCommand)

• store all the page movements in back and forwardstacks of commands.

Q: Which role will the WebBrowser class fulfill?

A:

Q: Who will store the stacks of WebBrowseCommands?

A:

I called my Invoker: UrlManager and gave it similarmethods to my Client:

• +goBack():void

• +goForward():void

• +goToNewPage(WebBrowseCommand):void

Q: Which role remains to be filled?

A:

I called mine GoToPageCommand. It has two fields:

Page 190 © 2019 Kyle Burke cb

Page 191: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

• url:String

• browser:WebBrowser

Q: What does the GoToPageCommand constructor look like?Hint: it’s boring.

A:

Q: What about the execute() method?

A:

Q: What will the fields of the WebBrowser look like?

A:

Page 191 © 2019 Kyle Burke cb

Page 192: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q:

Let’s try to implement the UrlManager. What fields do weneed here? Hint: we need three:

• Stack of commands

• Another stack of commands

• A single command.

What are their roles?

A:

Page 192 © 2019 Kyle Burke cb

Page 193: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q: Let’s implement the goToNewPage(WebBrowseCommand)

method!

A:

Q: Let’s implement the goBack method next!

A:

Page 193 © 2019 Kyle Burke cb

Page 194: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q: Let’s implement goForward.

A:

Q: What about the methods in WebBrowser? What should thegoBack and goForward methods do?

A:

Q: What should that goToPage method do?

A:

Page 194 © 2019 Kyle Burke cb

Page 195: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q: Implement it!

A:

Q:We would like other code to not call theWebBrowser.loadPage() method. Can we make itprivate?

A:

Q: Isn’t there another solution?

A:

An inner (non-static) class solves a lot of problems:

• Code in the inner class has access to all membersof the outer class.

• Then loadPage can be private!

• Increases encapsulation of the WebBrowser and it’s

Page 195 © 2019 Kyle Burke cb

Page 196: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

components.

• If the inner class is private, then we increase in-formation hiding!

10.1.1 New Order of things

1. Give basic navbarInit code with the UrlManagerand WebBrowser details left out.

2. Give the loadPage method in WebBrowser.

3. What’s the name of the ConcreteCommand goingto be (I used GoToPageCommand)

4. What’s its execute method going to do? (CallWebBrowser’s loadPage.)

5. What are the fields needed for GoToPageCom-mand? (url and browser)

6. Write execute method.

7. What should we call the interface? (Maybe I al-ready give them this: BrowseCommand)

8. Write the rest of the GoToPageCommand class.

9. Now time for the Invoker. I called mine ”UrlMan-ager” (they may have a better name)

10. Desired functionality? (goBack, goForward, new-Page)

11. Fields? (Stacks)

12. Implement the three methods

13. Now fill in the client. (Talk about adding finalparameters to the method.)

Page 196 © 2019 Kyle Burke cb

Page 197: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

10.1.2 Final Code

Web Browser v2

1..*

creates

uses

Client

— navbarInit(UrlManager,WebBrowser) : void

UrlManager

— current : BrowseCommand— history : Stack<BrowseCommand>— future : Stack<BrowseCommand>

+ goBack() : void+ goForward() : void+ goToPage(BrowseCommand) : void

WebBrowser

+ loadPage(String url) : void

�interface�Runnable

+ run() : void

�interface�BrowseCommand

+ run() : void

GoToPageCommand

— url : String— browser : WebBrowser

+ GoToPageCommand(WebBrowser, String)

+ run() : void

public void run() {this.browser.loadPage(this.url);

}

public void run() {this.browser.loadPage(this.url);

}

Page 197 © 2019 Kyle Burke cb

Page 198: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

Q: What’s the final code?

Buttons: (Client)private void navigationToolbarInit(final UrlManager

urls, final WebBrowser browser) {Button backButton = new Button();

backButton.setActionListener(new ActionListener()

{public void actionPerformed(ActionEvent

e) {urls.goBack();

}});Button forwardButton = new Button();

forwardButton.setActionListener(new ActionListener()

{public void actionPerformed(ActionEvent

e) {urls.goForward();

}});//I don’t actually know the right type for

a textbox...

final TextField urlBox = new TextField();

Button goButton = new Button();

goButton,setActionListener(new ActionListener()

{public void actionPerformed(ActionEvent

e) {

Page 198 © 2019 Kyle Burke cb

Page 199: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

10. OODP: COMMAND PATTERN CONTENTS

String url = urlBox.getText();

BrowseCommand command = new GoToPageCommand(browser,

url);

urlsCopy.goToPage(command);

}}//now place the objects

//...

}UrlManager: (Invoker)public class UrlManager {//fields

private Stack<BrowseCommand> history;

private Stack<BrowseCommand> future;

private BrowseCommand current;

//constructor

public UrlManager() {this.history = new Stack<BrowseCommand>();

this.future = new Stack<BrowseCommand>();}

//methods

public void goBack() {this.future.push(this.current);

this.current = this.history.pop();

this.current.run();

}public void goForward() {

this.past.push(this.current);

Page 199 © 2019 Kyle Burke cb

Page 200: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

11. WATERFALL SOFTWARE DEVELOPMENT CONTENTS

this.current = this.future.pop();

this.current.run();

}public void goToPage(BrowseCommand command)

{this.future.clear();

this.past.push(this.current);

this.current = command;

}}

WebBrowser: (Receiver)public void loadPage(String url) {//code to actually fetch the website and load

it into the browser...

//...

}BrowseCommand: (ConcreteCommand)public void run() {this.browser.loadPage(this.url);

}

11 Waterfall Software Development

Waterfall development is a linear model for creatingsoftware. Each step is succeeded by the next, so thateach step should be fully completed before moving onto the next.

Page 200 © 2019 Kyle Burke cb

Page 201: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

11. WATERFALL SOFTWARE DEVELOPMENT CONTENTS

11.0 Steps

1. Requirements: A complete product requirementsdocument should be produced that details the prod-uct expectations.

2. Design: The structure of the code should be de-signed before any implementation is done.

3. Implementation: The software is actually coded.

4. Verification: The correctness of the software ismeasured so that it’s certain that all the require-ments have been met.

5. Maintenance: The software is changed to removebugs and to implement new features, etc.

I’m not going to go into detail about these steps,mostly because I think you all have learned a bit aboutthis in a previous class.

11.1 Benefits

Design is important! Design before you code! Cowboycoding doesn’t really have a place here.

11.2 Limitations

In practice, these steps don’t actually happen one afteranother.

TODO: add more to this chapter

Page 201 © 2019 Kyle Burke cb

Page 202: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

11.3 Other Philosophies

There are many other software philosophies.20 We’regoing to talk next about the philosophy of Agile Soft-ware development.

12 Agile Software Development

Agile Software Development consists of a bunch of soft-ware development methods where change is expected.Change happens, so the project must be able to evolvewithout waiting for permission.

12.0 The Agile Manifesto

Agile Manifesto:We are uncovering better ways of developing soft-

ware by doing it and helping others do it. Throughthis work we have come to value:

• Individuals and interactions over Processes andtools

• Working software over Comprehensive documen-tation

• Customer collaboration over Contract negoti-ation

• Responding to change over Following a plan

That is, while there is value in the items on theright, we value the items on the left more.

20There’s a long list at https://en.wikipedia.org/wiki/List_of_software_

development_philosophies.

Page 202 © 2019 Kyle Burke cb

Page 203: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What do you think each of the four points means?

A:

12 Major Principles:

• Customer Satisfaction by rapid delivery of usefulsoftware.

• Welcome changing requirements, even late in de-velopment.

• Working software delivered frequently (weeks ratherthan months)

Page 203 © 2019 Kyle Burke cb

Page 204: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

• Close, daily cooperation between business peopleand devs

• Projects built around motivated individuals, whoshould be trusted.

• Co-location allows best communication.

• Working software is measurement of success.

• Sustainable Development to maintain a constantpace.

• Continuous attention to technical excellence andgood design.

• Simplicity—the art of maximizing the amount ofwork not done—is essential

• Self-organizing teams

• Regular adaptation to changing circumstances

Q: Where is Agile Development appropriate?

A:

Page 204 © 2019 Kyle Burke cb

Page 205: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: In Agile Dev, is it better to predict problems or adapt tothem?

A:

An adaptive team may have trouble reporting whatthey’re going to do next week, but will be able to re-port about which features they are planning for nextmonth.

Q: How much should an agile team document their code?

A:

Q: What’s wrong with too much documentation?

A:

Page 205 © 2019 Kyle Burke cb

Page 206: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What’s wrong with too little documentation?

A:

12.1 Agile Iterations

Q: How long should an individual task be?

A:

Q: Each group of tasks organized into an iteration. What hap-pens in each iteration?

A:

Page 206 © 2019 Kyle Burke cb

Page 207: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What does this sequence remind you of?

A:

Each iteration is kind of like a mini-waterfall. Kindof.

Q: How long should each iteration last?

A:

Q: What happens at the end of the iteration?

A:

Page 207 © 2019 Kyle Burke cb

Page 208: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: Why bring the clients in between each pair of iterations?

A:

Consider the functions of the team discussed earlier:planning, requirements analysis, design, coding, unittesting, and acceptance testing.

Q: Which of the functions can only happen once?

A:

Q: When are planning and requirements analysis repeated?

A:

Page 208 © 2019 Kyle Burke cb

Page 209: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: When does unit testing happen?

A:

Q: Why is automated testing vital for an Agile team?

A:

Q: How often should an agile team meet to discuss progress?

A:

Page 209 © 2019 Kyle Burke cb

Page 210: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What does each team member (or subgroup) report at themeeting?

A:

Q: What happens if you (a team member) think you can solveanother team member’s roadblock?

A:

12.2 Customer Representative

Q: Big idea: who is the unusual member of the agile team?

A:

Page 210 © 2019 Kyle Burke cb

Page 211: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What are their responsibilities?

A:

Q:What happens if the customer representative is filled by amember of the software development team (instead of thestakeholders)?

A:

Page 211 © 2019 Kyle Burke cb

Page 212: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What should be done if there cannot be a customer repre-sentative on the team?

A:

12.3 Information Radiator

An information radiator is a large physical display setup to display the current status of the project.

Q: Who should be able to see the information radiator?

A:

Q: Why passerby?

A:

Page 212 © 2019 Kyle Burke cb

Page 213: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What media should the information radiator use?

A:

Q: What is a build light indicator?

A:

Often uses three lights:

• Pass

• Fail

• Being re-tested

Q: Who uses the BLI?

A:

Page 213 © 2019 Kyle Burke cb

Page 214: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

12.4 Code Quality in an Agile Team

Q: We spent lots of time covering good code design. How im-portant is that for an agile team?

A:

Q: How is good design often recognized?

A:

Q: What else helps drive quality code?

A:

Page 214 © 2019 Kyle Burke cb

Page 215: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What happens when code quality is not maintained?

A:

12.5 Team Experience

Q:A customer requests a project be completed with Agile en-gineering with 10 software developers. You have 20 peopleto choose from: 10 senior devs and 10 junior devs. Who doyou put on the project?

A:

Q: Why?

A:

Page 215 © 2019 Kyle Burke cb

Page 216: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: Why don’t new people learn as they go?

A:

Q: What does this tell you about getting into Agile develop-ment?

A:

Page 216 © 2019 Kyle Burke cb

Page 217: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

12. AGILE SOFTWARE DEVELOPMENT CONTENTS

Q: What does this tell you about Agile development from abusiness perspective?

A:

Q:I’ve seen college described the following way: Enough Sleep,Good Grades, Social Life; Choose two. How could we usethe “choose two” mentality in the Iron Triangle?

A:

Q: If you are choosing to use Agile Development, which twoare you choosing?

A:

Page 217 © 2019 Kyle Burke cb

Page 218: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: In what ways is it expensive?

A:

13 OODP: Visitor Pattern

13.1 Motivation: Collectibles from the 1980’s

Let’s say we have a binary tree describing a My LittlePony toy collection.22 The MyLittlePony class has atoString method so the client’s tree can nicely printthe collection.

22Note: I came up with this example before the Friendship is Magic TV series wascreated. It predates any bronyhood I may or may not have adopted.

Page 218 © 2019 Kyle Burke cb

Page 219: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q:Old My Little Pony toys can be sold for money, and theirrecent trade values are updated daily on a fan website. Howmight our clients want us to improve the MyLittlePony

class?

A:

One solution to this problem is to include a toStringWithPrice()method in the MyLittlePony class.

Q: Why should we add this new method instead of change thetoString method to print out the price?

A:

Let’s complicate the matter further:

• Another client has a collection of G.I. Joe toys,which we have recorded in an ArrayList<GIJoe>.

• A client also has a collection of Cabbage PatchKids, itemized in a Graph<CabbagePatchKid>.

• Online, updating-value databases exist for both!

Page 219 © 2019 Kyle Burke cb

Page 220: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: What do these two clients probably want?

A:

Q: What is probably true of the CabbagePatchKid,MyLittlePony, and GIJoe classes?

A:

Q:Since we’re such good developers, we also find a way todetermine the eBay trade value and volume for each of thethree 80’s toys. What will our clients want once we tellthem?

A:

Page 220 © 2019 Kyle Burke cb

Page 221: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: How many specialized toString-ish methods do we have?

A:

Q: In general, how many will we have if we have n toy typesand m different methods required?

A:

Q: Where do we probably have some repeated code?

A:

Q: What should we do to fix this?

A:

This is what code that used that might look like:

Page 221 © 2019 Kyle Burke cb

Page 222: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

MyLittlePony posey = new MyLittlePony(...);

EbayVolumePrinter printer = new

EbayVolumePrinter();

printer.print(posey);

Q: What’s a problem with this?

A:

Q:Wait... how is that? What does theEbayVolumePrinter.print(EightiesToy toy) methodhave to do?

A:

public String print(EightiesToy toy) {if (toy instanceOf MyLittlePony) {

MyLittlePony pony = (MyLittlePony)

toy;

return this.printPony(pony);

}...

}

Page 222 © 2019 Kyle Burke cb

Page 223: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: Also, now how many total methods do we have?

A:

Q: How many in general for n toys and m printers?

A:

Let’s do something that looks a bit like a step back-wards. Let’s add a method to the MyLittlePony class:

public String toStringWithEbayVolume() {EbayVolumePrinter printer = new

EbayVolumePrinter();

return printer.printMyLittlePony(this);

}

Q:Now how many total public methods do we have for thesespecialized toString-type methods? (For our specific 3 toytypes.)

A:

Page 223 © 2019 Kyle Burke cb

Page 224: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: And in general? (n toys, m printers)

A:

Q:Is there some way we can condense all of the methodstoStringWithEbayVolume, toStringWithEbayPrice, andtoStringWithPrice?

A:

Q: Let’s call that method specialToString. Is it going totake any parameters?

A:

Q: What is the parameter it’s going to take?

A:

Page 224 © 2019 Kyle Burke cb

Page 225: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

public String specialToString(Printer

printer) {return printer.printMyLittlePony(this);

}

Q: What’s the signature for the printMyLittlePony method?

A:

Q: Can I change this to public String print(MyLittlePony

pony)?

Q: Wait... then is it different from public String

print(GIJoe joe)?

A: Yup! Different Signatures!

Page 225 © 2019 Kyle Burke cb

Page 226: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: Wow! What’s specialToString going to look like now?

A:

Q: Anything specific to Ponies in there?

A: Nope!

Q: Then where can we move it?

A: Nowhere.

Q: Why can’t we move it up to EightiesToy class?

A:Because inside each of the subclasses, thetype of this is specific. There isn’t anyprint(EightiesToy) method in the Printer

classes.

Page 226 © 2019 Kyle Burke cb

Page 227: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: How many total methods do we have now?

A:

Q: Can we do any better?

A: Not really

Q: What’s the benefit of this reorganization, then?

A: The Printers are well-separated from the Toys

Q: Which can we add without having to modify anything else,Toys or Printers?

A:

Page 227 © 2019 Kyle Burke cb

Page 228: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

13.2 Visitor Pattern Participants

We can generalize this plan for any objects by usingthe Visitor Pattern! Participants:

• ConcreteElement: Object to perform some oper-ation on.

• Element: interface for different ConcreteElementclasses.

• ConcreteVisitor: Object that will perform theaction on the visited object.

• Visitor: Interface for the different visitors.

• Client: Uses the ConcreteVisitors to performoperations on elements.

Q: Which of the above roles do we want each of our exampleclasses to fit in?

A:

The Printers are our Visitors, which do differentthings based on both:

• Visitor type

Page 228 © 2019 Kyle Burke cb

Page 229: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

• Element type

Both dynamically! The Visitor Pattern lets us dothis without sacrificing polymorphism, using a double-dispatch technique: we’re going to use dynamic methodinvocation twice by making two method calls.

First invocation: choose the element type; the sec-ond one dynamically chooses the element.

Q:The pattern’s two interfaces, Visitor and Element, are abit different from what we’ve built so far as our abstractclasses, Printer and EightiesToys. What can we do tomake our visiting more flexible?

A:

Using the generic type: our Visitor<T> means thatthe visit methods have return type T.

Q:On the Element<T> side, we’re going to need to accept thevisitor, like the 80’s toys accepted the printer. What is thesignature of that accept method?

A:

Page 229 © 2019 Kyle Burke cb

Page 230: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: We can implement that accept method in the abstract su-perclass! What does that method look like?

A:

Q: What’s the problem with implementing this in the abstractclass?

A:

Q: What should we do instead?

A:

Q: What’s super weird about this?

A:

Page 230 © 2019 Kyle Burke cb

Page 231: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: And that makes Kyle sad because...?

A:

Q: What’s another benefit of this?

A:

Q: What is going to be in the abstract Visitor?

A:

Q: To add a new visitor, where do we have to add code?

A:

Page 231 © 2019 Kyle Burke cb

Page 232: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: Why is this helpful?

A:

⟨ Draw the class diagram! ⟩ TODO: add the dia-gram here

13.3 Implemented Example

Let’s implement the Visitor pattern with our classesfrom before: EightiesToy, Printer, and their sub-classes.

Q: What will the code look like for EightiesToy?

A:

Page 232 © 2019 Kyle Burke cb

Page 233: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: Okay, let’s implement one of the subclasses: MyLittlePony.Ignore all other methods aside from the accept method.

A:

Q: Do the same for GIJoe and CabbagePatchKid.

Q: Let’s implement the EightiesToyVisitor superclass. Doit!

A:

Page 233 © 2019 Kyle Burke cb

Page 234: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

13. OODP: VISITOR PATTERN CONTENTS

Q: Let’s implement the EbayVolumePrinter class! (We don’tneed to include the bodies of any methods here...)

A:

Page 234 © 2019 Kyle Burke cb

Page 235: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

13.4 Downsides

Q: What are some limitations of this pattern?

A:

14 Parallel OODP: Producer-Consumer

I’m completely redoing this section by starting withsome concrete code. If I haven’t finished this yet, theolder stuff will be available afterwards.

Sesame Street has written some code to simulatesupplying cookies for Cookie Monster.

Page 235 © 2019 Kyle Burke cb

Page 236: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Cookie Supplythis.monster = new CookieMonster();

this.baker = new CookieBaker();

final Queue<Cookie> toEat = new Queue<Cookie>(10);

//launch thread for baking cookies

this.bakingProcess = new Runnable() {public void run() {

bakingLoop(toEat);

}}new Thread(this.bakingProcess).start();

//launch thread for eating cookies

this.eatingProcess = new Runnable() {public void run() {

eatingLoop(toEat);

}}new Thread(this.eatingProcess).start();

The loops are as follows:

Baking Looppublic void bakingLoop(Queue<Cookie> buffer) {

while (!buffer.isFull()) {Cookie cookie = this.baker.bakeCookie();

buffer.add(cookie);

if (buffer.size() == 1) {new Thread(this.eatingProcess).start();

}}

}

Page 236 © 2019 Kyle Burke cb

Page 237: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Eating Looppublic void eatingLoop(Queue<Cookie> buffer) {

while (!buffer.isEmpty()) {boolean wasFull = buffer.isFull();

Cookie cookie = buffer.remove();

if (wasFull) {new Thread(this.bakingProcess).start();

}this.monster.eat(cookie);

}}

Q: There are certainly many problems with this code, but let’saddress a concurrency issue first: what is a deadlock?

A: A deadlock is when no threads are makingprogress; they are all waiting on other threads.

Q: Can a deadlock happen with the above code?

A: Yes!

Page 237 © 2019 Kyle Burke cb

Page 238: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: How? (Hint: Describe the situation)

A:

Scenario: The buffer has a size of 10 and thereare 9 cookies in it.

1. The eating loop (eL) sets wasFull tofalse; the baking loop (bL) bakes a cookie.

2. eL removes a cookie; bL adds a cookie(there are 9 cookies in the queue again)

3. eL fails the conditional; bL fails the condi-tional

4. eL gives the cookie to the monster to eat;bL fails the while condition and breaks outof the loop

5. eL runs through the loop 9 more times, eachtime removing a cookie.

6. At the end of the ninth time, eL fails thewhile condition and breaks out of the loop.

The threads have completed, even though theywere supposed to keep running. This is a verysimplified version of a deadlock.

Page 238 © 2019 Kyle Burke cb

Page 239: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: Are there other bad things about those loops?

A:Yes: we could create multiple threads for eitherof the loops. (That might be okay, or we mightnot want that.)

Q:

There are lots of mundane ways we can change the codeto be more resilient to deadlocks or other synchroniza-tion problems, but, while they might reduce the likelihoodof problems, they don’t fix everything. In order to solvethings, we will need some actual synchronization tools.

14.0 Old stuff

Q:Remember old newspaper printers with the big machines?If you’re printing up today’s newspapers, it can take a whilefor them all to finish. What should I do after the firstbundles of papers come off the machines?

A: Start distributing them!

Page 239 © 2019 Kyle Burke cb

Page 240: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

14.1 Motivation and the Big Problem

Q:In this metaphor, the machine is the Producer, creating thenewspapers, and my army of young ”Newsies”23 (hooray nochild labor laws) is my Consumer. What’s the big idea here?

A:

Page 240 © 2019 Kyle Burke cb

Page 241: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What are some examples of this (both real-world andcomputing-land)?

A:

Real World:

• Grocery Stores put milk into the fridge cab-inets, customers buy them.

• I produce lecture notes as fast as I can andthen teach them during my classes.

• Students are assigned homework in theirdifferent classes and turn it in when due.

Computing:

• Computer Jobs are created by applicationsand the user and are run on the CPU whenthe scheduler decides.

• Routers receive packets in one channel andsend them out on another.

Q:There’s an easy solution here: just put a queue as a ”buffer”between the Producer and Consumer. Boom, code up aQueue using an ArrayList and we’re done! Right? What’sthe problem here?

A:

Page 241 © 2019 Kyle Burke cb

Page 242: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What do we want the Producer to do if they try to addsomething to a full buffer?

A:

Q: What do we want the Consumer to do if they try to removesomething from an empty buffer?

A:

14.2 Common First Code

Let’s look at an example of some producer-consumercode and improve it:

All of this code is in the same class:public void launch() {final Queue buffer = new Queue();

Runnable producer = new Runnable() {public void run() {

producerLoop(buffer);

}};new Thread(producer).start();

Runnable producer = new Runnable() {public void run() {

consumerLoop(buffer);

Page 242 © 2019 Kyle Burke cb

Page 243: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

}};new Thread(producer).start();

}Producer:public void producerLoop(Queue buffer) {while (true) {

Object produced = this.generate();

if (buffer.isFull()) {producerSleep(); //blocks ’til producerAwaken()

call

}buffer.add(produced);

if (buffer.size() == 1) {consumerAwaken();

}}

}Consumer:public void consumerLoop(Queue buffer) {while(true) {

if (buffer.isEmpty()) {consumerSleep(); //blocks until consumerAwaken()

}boolean wasFull = buffer.isFull();

Object produced = buffer.remove();

if (wasFull) {producerAwaken();

}this.consume(produced);

Page 243 © 2019 Kyle Burke cb

Page 244: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

}}

24

24Comic source: https://xkcd.com/1926/

Page 244 © 2019 Kyle Burke cb

Page 245: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What are some issues with this design? (There are lots.)

A:

• Not very OO. The producer and consumerseem like separate roles and should eachhave their own class. Then there’s a lotto do there...

• Looks like generics could be useful in theresince we are declaring things to be of typeObject.

• These methods are not thread safe! Thatmeans that if you run them, a race con-dition can occur: unexpected results canhappen due to the timing of instructions inseparate threads. In this case, there is thepotential for a deadlock!

TODO: point out the deadlock! Somehow we re-moved that... :’(

14.3 Sleeping with Semaphores

Q: Let’s first address an implementation issue: How do weimplement the awaken and sleep methods?

A: Semaphores!

Page 245 © 2019 Kyle Burke cb

Page 246: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What is the interface for a Semaphore?

A:

• Constructor: Semaphore(numTokens :

int)

• p(): asks to ”borrow” a token. If none isavailable it blocks until one becomes avail-able.

• v(): returns a token. Sometimes it’s okayfor code that never borrowed a token to re-turn one.

2526

Q: How many semaphores will we need?

A:

25p is short for the Dutch proberen (to try out); v is short for verhohen (to increase)26Java’s Semaphore implementation (https://docs.oracle.com/javase/7/docs/

api/java/util/concurrent/Semaphore.html) uses acquire() and release() as p()

and v(), respectively.

Page 246 © 2019 Kyle Burke cb

Page 247: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What will we call them?

A:

How about:

• producerAwake (blocks when the producerneeds to sleep) and

• consumerAwake (block when the consumerneeds to sleep)

Q:

Can we just make the following replacements?

• producerSleep() → this.producerAwake.p()

• producerAwaken() → this.producerAwake.v()

• consumerSleep() → this.consumerAwake.p()

• consumerAwaken() → this.consumerAwake.v()

A:Not really. Remember that the problem hap-pened because we skipped over some of theawaken calls.

Q: What can we do instead?

A:We’ll set it up so that the calls are not insideconditionals. We’ll just call them every singletime through the loops!

Page 247 © 2019 Kyle Burke cb

Page 248: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q:

There are two things to think about to understand how thisworks:

• How many tokens is each Semaphore going to startwith? (Hint: not 1) and

• Where exactly are the calls to p and v going to go?

Let’s tackle the second question first. Let’s rewrite theproducer loop.

A:

public void producer(Queue buffer) {while(true) {

Object produced =

this.generate();

//block until there’s space in

the buffer

this.producerAwake.acquire();

buffer.add(produced);

//indicate that there’s another

element in the buffer

this.consumerAwake.release();

}}

Page 248 © 2019 Kyle Burke cb

Page 249: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: How about the consumer loop?

A:

Q: Okay, how many tokens is the producerAwake Semaphoregoing to have initially?

A:The size of the buffer. So:this.producerAwake = new

Semaphore(buffer.size());

Page 249 © 2019 Kyle Burke cb

Page 250: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What about the consumerAwake Semaphore?

A:

14.4 Instilling OO principles

This fixes the race condition, but there are other prob-lems related to the design that do make it easier to runthis code. We will definitely be making other changeswith the Semaphores also.

Page 250 © 2019 Kyle Burke cb

Page 251: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q:What do I need to do to get the current code running?What would the constructor (let’s just put everything inthere for now) have to look like to get everything running?

A:

Q:

Page 251 © 2019 Kyle Burke cb

Page 252: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: Okay, let’s think ahead a bunch and see if we can figure outwhat the four participants of our final design pattern are.

A:

• Producer: Class that creates objects thatneed to be consumed.

• Consumer: Class that consumes createdobjects.

• Buffer: Data Structure that holds pro-duced objects that are waiting to be con-sumed.

• Client: Creates the Producer, Consumer,and Buffer and launches the Producer andConsumer.

Q: Which of the three main classes will have references to theothers?

A: Producer and Consumer will have references tothe Buffer.

Page 252 © 2019 Kyle Burke cb

Page 253: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Consumer-Producer v0

uses

uses ClientCallsProducer.produce()

andConsumer.consume()

CallsProducer.produce()

andConsumer.consume()

Producer

- buffer : Buffer

+ producer() : void+ generate() : Object

Consumer

- buffer : Buffer

+ consumer() : void+ consume(Object) : void

Buffer

- maxSize : int- elements : Collection

+ add(Object) : void+ remove() : Object+ isEmpty() : boolean+ isFull() : boolean

14.5 Improvements

Q: What’s the first change we notice? Hint: think about thedata structures class.

A:

Q: What about the Producer class. What is going on in theproducer method?

A:

Page 253 © 2019 Kyle Burke cb

Page 254: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: Should that be running in its own thread?

A:

Q: So what should we do with it?

A:

Q: What about Consumer’s consumer method?

A:

Page 254 © 2019 Kyle Burke cb

Page 255: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: What might the code in the Client look like that launcheseverything? (Hint: I used Strings in my example.)

A:

New Class Diagram! (Note: I’ve removed the Clientfrom here on out.)

Page 255 © 2019 Kyle Burke cb

Page 256: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Consumer-Producer v1

�interface�Runnable

+ run() : void

Producer

- buffer : Buffer

+ run() : void+ generate() : T

Consumer

- buffer : Buffer

+ run() : void+ consume(T) : void

Buffer

- maxSize : int- elements : Collection<T>

+ add(T) : void+ remove() : T+ isEmpty() : boolean+ isFull() : boolean

5

14.6 Shifting Responsibilities

Q:Okay, now where are we going to put the semaphores tokeep everything thread safe? If we had to choose just oneobject to handle the concurrency, where does that respon-sibility fit most cleanly?

A: Use the buffer!

Page 256 © 2019 Kyle Burke cb

Page 257: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: Let’s give the buffer a semaphore field. How can we usethis to solve our problem?

A:

Q: Let’s implement the add method for the Buffer.

A:

Q: Okay, now implement the remove.

A:

Page 257 © 2019 Kyle Burke cb

Page 258: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Here’s the updated figure

Consumer-Producer v2

�interface�Runnable

+ run() : void

Producer

- buffer : Buffer

+ run() : void+ generate() : T

Consumer

- buffer : Buffer

+ run() : void+ consume(T) : void

Buffer

- maxSize : int- elements : Collection<T>- semaphore : Semaphore

+ add(T) : void+ remove() : T+ isEmpty() : boolean+ isFull() : boolean

Q: Let’s fix the Producer’s run method. Hint: significantlyeasier now!

A:

public void run() {while (true) {

T produced = this.generate();

this.buffer.add(produced);

}}

Page 258 © 2019 Kyle Burke cb

Page 259: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

14. PARALLEL OODP: PRODUCER-CONSUMER CONTENTS

Q: Now what about Consumer’s?

A:

Q: How can I simplify this in Java?

A:

27

I found out about these classes from the Java Re-visited blog [3].

27API: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/

LinkedBlockingQueue.html

Page 259 © 2019 Kyle Burke cb

Page 260: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What will our Client code look like, then? (Use the Stringexample again.)

A:

15 Parallel OODP: Master-Worker

28

Master-Worker is a classic parallel design pattern[1],though the specifics vary a bit. It is also known as theMaster-Slave pattern and the SPMD (Single Program;Multiple Data) pattern.

28Thanks a ton to Dale Skrien for helping me work out the details of this!

Page 260 © 2019 Kyle Burke cb

Page 261: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

15.0 Motivation

Q: What should we do if we have one big computation to solveand lots of available hardware threads?

A:Split the problem up into little pieces. If wecan’t divide up the problem into smaller con-current problems, we can’t use this pattern.

Q: If we divide it up into m pieces and have p threads, is it aproblem if m >> p?

A: Not really.

Q: What are we going to do?

A: Give each thread a piece to solve. When they’redone, give it another one.

Q: What are we hiding under the rug here?

A: The actual part to break-down the problem intolittle pieces.

Page 261 © 2019 Kyle Burke cb

Page 262: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: And what happens when all the little pieces are done?

A: We have to put them back together.

15.1 Initial OO Master-Worker

The original object-version of this pattern was givenin [1]. It has the following parts:

Master-Worker v0

creates

uses Client Calls Mas-ter.service();Calls Mas-ter.service();

Master

+ Master(...)+ service() : void- splitWork() : void- callWorkers() : void- combineResults() : void

Worker

+ subservice() : void

Page 262 © 2019 Kyle Burke cb

Page 263: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What’s the purpose of the three private methods in Master?

A:

To do the three things we talked about:

splitWork : divides the work up into smallpieces. (Presumably this sets up a datastructure with all the data for the subcom-putations.

callWorkers : assigns the data pieces tothe Workers, then calls their subservice

method, until all the data is processed.)

combineResults : takes the results of eachsubcomputation and builds the final dataresult.

15.2 First Improvements

Q: What’s a problem with Master.service?

A: It doesn’t return anything.

Page 263 © 2019 Kyle Burke cb

Page 264: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Okay, let’s make it fruitful. What should it return?

A:

Q: Even better?

A:

Q: How else should we change service?

A: Give it a parameter.

Q: And what type should that be?

A:

Page 264 © 2019 Kyle Burke cb

Page 265: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Can we write the body of Master.service()?

A: Yes!

Q: Write it!

A:

public Out service(In input) {this.splitWork(input);

this.callWorkers();

return this.combineResults();

}

Q: What is splitWork going to do if it’s void?

A: It will have to assign the results of the splittingto a field! Okay, let’s add a field: workerInputs

Q: How is combineResults going to work without taking anyparameters?

A:

Page 265 © 2019 Kyle Burke cb

Page 266: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q:Since we know the necessary methods in Master andWorker, how can we take the first step to improving thesepatterns?

A: Use abstract classes.

Q: Can we implement any of the methods in the abstractclasses?

A:

Here are the improvements we’ve made so far:TODO: generic types are not working in the title of

an abstract class.

Page 266 © 2019 Kyle Burke cb

Page 267: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Master-Worker v1

creates

uses Client

Master

- workerInputs : Collection- workerOutputs : Collection

+ service(In input) : Out- splitWork(In) : void- callWorkers() : void- combineResults() : Out

body of service:this.splitWork(input);

this.callWorkers();

return

this.combineResults();

body of service:this.splitWork(input);

this.callWorkers();

return

this.combineResults();

ConcreteMaster

+ ConcreteMaster(...)- splitWork(In) : void- callWorkers() : void- combineResults() : Out

Worker

+ subservice() : void

ConcreteWorker

+ ConcreteWorker(...)+ subservice() : void

15.3 Using the Command Pattern

Q: Which part of this is reminiscent of the Command Pattern(section 10)?

A: Worker

Page 267 © 2019 Kyle Burke cb

Page 268: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What class should we replace Worker with (in Java)?

A: Runnable29

Q: What are the added benefits of using Runnable?

A:

Q: What changes do we have to make to replace Worker withRunnable?

A:

We’ll also change ConcreteWorker to just be Worker.Here’s the most recent version of our design. (Notice,I’m leaving the Client out from this point on.)

29https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html

Page 268 © 2019 Kyle Burke cb

Page 269: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Master-Worker v2

creates

Master

- workerInputs : Collection- workerOutputs : Collection

+ service(In) : Out- splitWork(In) : void- callWorkers() : void- combineResults() : Out

ConcreteMaster

+ ConcreteMaster(...)- splitWork(In) : void- callWorkers() : void- combineResults() : Out

�interface�Runnable

+ run() : void

Worker

+ Worker(...)+ run() : void

Q: What does the code look like to create and dispatch aWorker?

A: Worker worker = new Worker(...);

new Thread(worker).start();

Page 269 © 2019 Kyle Burke cb

Page 270: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

15.4 Double-down on Command

Q: How different are each of the Workers going to be?

A: Not very. Going to run the exact same code...but on different input.

Q: What design pattern could we use here?

A:

Q: Again??

A:

Q: Who will own this command?

A:

Page 270 © 2019 Kyle Burke cb

Page 271: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What should ConcreteMaster.callWorkers look like?

A:

private void callWorkers() {for (Object datum :

dataForWorkers) {Worker worker = new

Worker(this.command, datum);

new Thread(worker).start();

}}

Q: The Object variable is a bit awkward. How can we cleanthis up using generics?

A: Include Generics for input/output for the work-ers. Let’s use WIn and WOut.

Page 271 © 2019 Kyle Burke cb

Page 272: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Okay, let’s fix ConcreteMaster.callWorkers().

A:

Q: Should the Worker’s command field be Runnable, Callable,or something else?

A:

30

30Callable is the version of Runnable that returns a value: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html

Page 272 © 2019 Kyle Burke cb

Page 273: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Returning is nice. Why can’t the Worker extend Callableinstead of Runnable?

A:

Q: It’s really important for the Command to either have nostate or be immutable. Why is that?

A:The same Command object is used for all theworker commands. If any fields are changedduring the execute method, then we can havesome race conditions!

Update the class diagram:

Page 273 © 2019 Kyle Burke cb

Page 274: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Master-Worker v3

creates

*

Master

- workerInputs : Collection- workerOutputs : Collection- command : Command

+ service(In) : Out- splitWork(In) : void- callWorkers() : void- combineResults() : Out

ConcreteMaster

+ ConcreteMaster(...)- splitWork(In) : void- callWorkers() : void- combineResults() : Out

�interface�Runnable

+ run() : void

Worker

- command: Command- input: WIn

+ Worker(Command, WIn)+ run() : void

�interface�Command

+ execute(WIn): WOut

15.5 Giving Back

Q: If the worker’s run method is void, how will we hand databack to the ConcreteMaster?

A: Include a method in ConcreteMaster that ac-cepts the finished work.

Page 274 © 2019 Kyle Burke cb

Page 275: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: How will that method put the work back in the properplace?

A:It will have to know the location in the datastructure to return the information. E.g.:public void returnData(WOut datum, int

index)

Q: What are some problems with this?

A:

Q: Can we do better?

A: Yes!

Page 275 © 2019 Kyle Burke cb

Page 276: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: How?

A:

Q: What other methods does this capsule object need?

A:

Q: What is the problem with these? Specifically, isFull?

A: Polling.

Q: What’s the solution to polling?

A:

Page 276 © 2019 Kyle Burke cb

Page 277: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Okay, so what methods will we add to the Capsule class?

A:

Q: Which methods can we remove then?

A:

Q: What’s the signature of this class going to be?

A:

Q: Let’s implement some of these! First off: the constructor.

A:

public Capsule() {this.isFull = false;

this.value = null;

this.listeners = new

LinkedList<ActionListener>();

}

Page 277 © 2019 Kyle Burke cb

Page 278: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Next, fill()

A:

public void fill(T value) {this.value = value;

this.isFull = true;

this.notify();

}

Q: Finally, getValue()

A:

public T getValue() {if (this.isFull) {

return this.value;

} else {throw new

RuntimeException("Tried to get the

value from an empty capsule!");

}}

Page 278 © 2019 Kyle Burke cb

Page 279: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What about the add(Observer) method?

A:

Just like the one shown in the Ob-server pattern. For Java, we can usethe ActionListener interface, so it’ll beaddActionListener(ActionListener):public void addActionListener(ActionListener

listener) {this.listeners.add(lisetener);

}

Q: So what about the notify method?

A:

public void notify() {for (ActionListener listener :

this.listeners) {listener.actionPerformed(new

ActionEvent(this, 0, ""));

}}

TODO: add another iteration of the class diagramhere

Page 279 © 2019 Kyle Burke cb

Page 280: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: I think we can finally implement the Worker class! Firstup: constructor, which is extremely boring.

A:

public Worker(Command command, WIn

input, Capsule capsule) {this.command = command;

this.input = input;

this.capsule = capsule;

}

Q: Can we write the Worker.run method yet?

A:

Q: What could be a problem with the data structures for theworker inputs and outputs?

A:

Page 280 © 2019 Kyle Burke cb

Page 281: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Do they need to be the same?

A:

Q: What should we do here?

A:

Q: Okay, what do we need to add to our capsule class?

A:

Page 281 © 2019 Kyle Burke cb

Page 282: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: How can this improve the Worker class’s constructor?

A:

Q: So what method do we need to update?

A:

Q: Update it!

A:

⟨ Make sure the class diagram matches this: ⟩

Page 282 © 2019 Kyle Burke cb

Page 283: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Master-Worker Pattern v4

creates

*

Master

- command : Command- workerData :

Collection<IOCapsule>

+ service(In) : Out- splitWork(In) : void- callWorkers() : void- combineResults() : Out

ConcreteMaster

splitWork(In) : voidcombineResults() : Out

�interface�Runnable

+ run() : void

Worker

- command : Command- capsule : IOCapsule

+ Worker(Command,IOCapsule)+ run() : void

�interface�Command

+ execute(WIn): WOut

IOCapsule

- input : WIn- output : WOut

+ IOCapsule(WIn)+ getInput() : WIn+ fill(WOut) : void+ getOutput() : WOut

Page 283 © 2019 Kyle Burke cb

Page 284: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

15.6 Waiting for Workers

Q: Last big issue: There’s a weird part in our old service

method. What’s wrong with this?

A:We need to wait for the workers to finish beforecalling combineResults. Right now it doesn’twait!

Q: How do we get the code to wait? (Either at the beginningof combineResults or at the end of callWorkers)

A:

Page 284 © 2019 Kyle Burke cb

Page 285: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What is a Semaphore?

A:

Q: What is the interface for a Semaphore?

A:

• Constructor: Semaphore(numTokens :

int)

• p(): asks to ”borrow” a token. If none isavailable it blocks until one becomes avail-able.

• v(): returns a token. Sometimes it’s okayfor code that never borrowed a token to re-turn one.

3132

Q: Which class will have a Semaphore field?

A: Master

31p is short for the Dutch proberen (to try out); v is short for verhohen (to increase)32Java’s Semaphore implementation (https://docs.oracle.com/javase/7/docs/

api/java/util/concurrent/Semaphore.html) uses acquire() and release() as p()

and v(), respectively.

Page 285 © 2019 Kyle Burke cb

Page 286: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: When will it be created?

A:

Q:

Let’s implement the following strategy:

• Start with a semaphore with lots of tokens.

• Each worker requests a token before it starts work, thenreturns it when it’s done.

• Before we call combineResults, we need to request to-kens again so that doesn’t go until all workers havefinished.

How many tokens should we include initially?

A:

Q: How many tokens do we need to request at that end part?

A:

Page 286 © 2019 Kyle Burke cb

Page 287: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Is there a benefit to putting all of this synchronization codeinto callWorkers?

A:

Q:Okay, so we want all of the workers to take a token whenthey launch, and return it when they’re done. Where shouldwe put another call to p()?

A:

Q: Okay, when should the other calls to p() and v() happen?

A:

Q: Okay, where do I put that call to p?

A:

Page 287 © 2019 Kyle Burke cb

Page 288: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What about the call to v?

A:

Q: What does that mean about the workers?

A:

Page 288 © 2019 Kyle Burke cb

Page 289: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Let’s update the callWorkers method!

A:

Q:Why does there have to be a separate loop at the end? Whycan’t I just put the call to acquire in at the last line of theloop?

A:

Page 289 © 2019 Kyle Burke cb

Page 290: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Let’s update Worker.run?

A:

Q:We can actually make our code run faster by removing somecalls to acquire (and modifying the semaphore construc-tor). How can we do that?

A:

Page 290 © 2019 Kyle Burke cb

Page 291: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What does the updated method look like now?

A:

Q:There are two ways to remove that last loop and replace itwith a single call to acquire. What are those ways? (Hint:I had to look at the Semaphore API to make sure both werelegal.)

A:

Page 291 © 2019 Kyle Burke cb

Page 292: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: What’s the code for the negative tokens version? (Hint:how many negative tokens do you need to initialize with?)

A:

Q: Do we still need to use the Observer Pattern?

A:

Page 292 © 2019 Kyle Burke cb

Page 293: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Q: Okay, so what was the thing about the binary tree to re-combine?

A:

There’s a bit of a bottleneck in terms of launch-ing all the threads: it all uses a single loop.What if instead, we had a binary tree wherethe leaves had the data for the workers. Thenwe could launch them in parallel from the rootin Θ(log(n)) steps. We’d have to have the re-combining done in that much time too, though.Definitely a good plan, but that’s for anothertime...

15.7 Master-Worker: Summary

Sweet! We did a lot of work! Here’s the final classdiagram:

Page 293 © 2019 Kyle Burke cb

Page 294: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

15. PARALLEL OODP: MASTER-WORKER CONTENTS

Master-Worker Pattern Final

creates

*

Master

- command : Command- workerData :

Collection<IOCapsule>- semaphore : Semaphore

+ service(In) : Out- splitWork(In) : void- callWorkers() : void- combineResults() : Out

ConcreteMaster

splitWork(In) : voidcombineResults() : Out

�interface�Runnable

+ run() : void

Worker

- command : Command- capsule : IOCapsule- semaphore : Semaphore

+ Worker(Command,IOCapsule, Semaphore)+ run() : void

�interface�Command

+ execute(WIn): WOut

IOCapsule

- input : WIn- output : WOut

+ IOCapsule(WIn)+ getInput() : WIn+ fill(WOut) : void+ getOutput() : WOut

Page 294 © 2019 Kyle Burke cb

Page 295: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

16. PARALLEL OODP: PIPELINE PATTERN CONTENTS

Q: What are the benefits of this pattern?

A:• Everything runs in parallel.

• No possibilities of data structure errors.

• User only has to implement a little bit.

Q: What exactly does the user have to implement?

A:

16 Parallel OODP: Pipeline Pattern

Requirements: need to have already seen the Block-ingQueue Java stuff from the Producer/Consumer pat-tern.

TODO: flesh out this section a bunch more. I don’tremember what I did, but it went really well. I startedwith the state pattern.

Page 295 © 2019 Kyle Burke cb

Page 296: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

16. PARALLEL OODP: PIPELINE PATTERN CONTENTS

16.0 Pipeline Pattern based on State PatternPaper

I built this all off of the paper I read many yearsago... an earlier version of this one by MacDonald,Szafron, and Schaffer: ”Rethinking the Pipeline as Ob-ject–Oriented States with Transformations” (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.

1.1.150.4556&rep=rep1&type=pdf)Talk about this stuff. Make some drawings on the

board. We don’t want an actual pipeline, just thestages in a queue that get run. Note: we have to makesure that Order Does Not Matter. (Otherwise, thisdoesn’t really work.)

Page 296 © 2019 Kyle Burke cb

Page 297: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

16. PARALLEL OODP: PIPELINE PATTERN CONTENTS

16.1 Final Code and Diagram

Pipeline Pattern - Final

�interface�Runnable

+ run() : void

PipeStepElement

- toProcess : BlockingQueue<PipeStepElement>- finished : BlockingQueue<PipeStepElement>

+ run() : void- addToProcess(PipeStepElement)- addToFinished(PipeStepElement)

ConcretePipeStepAElement

+ ConcretePipeStepAElement(...)+ run() : void

ConcretePipeStepBElement

+ ConcretePipeStepBElement(...)+ run() : void

ConcretePipeStepCElement

+ ConcretePipeStepCElement(...)+ run() : void

TearDownElement

+ TearDownElement(...)+ run() : void

Dispatcher

- numPipeElements : int- toProcess : BlockingQueue<PipeStepElement>- finished : BlockingQueue<PipeStepElement>

+ Dispatcher(BlockingQueue<PipeStepElement> toProcess, ...)+ processAll() : void+ getFinished() : PipeStepElement

TODO: add the Client to the picture. The Clientcreates the toProcess queue, puts all the initial pipe

Page 297 © 2019 Kyle Burke cb

Page 298: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

17. EVOLUTION OF DESIGN PATTERNS CONTENTS

steps in there, then calls processAll on the Dispatcher,then calls getFinished to get them all out.

Here’s the code for the processAll method in theDispatcher class:

public void processAll() {while (this.numPipeElements > 0) {

PipeStepElement element = this.toProcess.take();

new Thread(element).start();

}}

Here’s the code for getFinished, also in the Dis-patcher class:

public synchronized PipeStepElement getFinished()

{PipeStepElement finished = this.finished.take();

this.numPipeElements --;

if (this.numPipeElements <= 0) {this.toProcess.put(new TearDownElement());

}return finished;

}

17 Evolution of Design Patterns

TODO: include the image from https://www.reddit.

com/r/DesignPatterns/comments/9cmhtm/most_comprehensive_

design_pattern_diagram_ive/

Page 298 © 2019 Kyle Burke cb

Page 299: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

17. EVOLUTION OF DESIGN PATTERNS CONTENTS

Page 299 © 2019 Kyle Burke cb

Page 300: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

17. EVOLUTION OF DESIGN PATTERNS CONTENTS

17.0 Downsides of Design Patterns

33

33Monkey User comic ”Design Patterns Bureaucracy, from http://www.monkeyuser.

com/2017/design-patterns-bureaucracy/

Page 300 © 2019 Kyle Burke cb

Page 301: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

17. EVOLUTION OF DESIGN PATTERNS CONTENTS

There are some arguments against Design Patterns.One is: it creates too much repeated code. If I imple-ment a complicated pattern in 12 places, then there isgoing to be lots of repeated code.

Q: What’s the solution?

A:

17.1 OODP and PL

New languages and/or language features often pop upto simplify or remove common code patterns.

TODO: talk about how this works with non-OOpatterns. E.g. evolution of Java for-each loops.

Q: Which patterns have already been integrated into Java?

A:

The Master-Worker patternis completely unneces-sary in some languages, e.g. Chapel34.

34http://chapel.cray.com

Page 301 © 2019 Kyle Burke cb

Page 302: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A Little Holiday Software JokeI usually arrive here—the end of the notes—at theend of the fall semester. The midst of the holidayseason. The following tweet is excellent advice forbudding software developers.

35

Appendices

A Java Programming with Objects

⟨ Do Basic OOD pages 8 - 15 ⟩35Source: https://twitter.com/chrisalbon/status/943342608742604801

Page 302 © 2019 Kyle Burke cb

Page 303: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q:

What if we have the getName method implemented in bothPrimate and Monkey. Which of those two does the followingsnippet call?Primate primeape = new Monkey(‘‘Primeape", O57);

primeape.getName();

A:

Q: What is this called?

A:

A.0 Downcasting

Q: Let’s return to the primeape example. What if we laterwant to get primeape’s Bananas?

A:

Page 303 © 2019 Kyle Burke cb

Page 304: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q: What will that code look like?

A:

Q: What could be the result if we’re not careful?

A:

Q: Workaround?

A:

Two red flags just jumped up:

• instanceof: Means you’re probably not usingPolymorphism when you should. Leads torepeated, ugly conditionals!

• ”Workaround” Yuck! That means we’re notbeing elegant.

Page 304 © 2019 Kyle Burke cb

Page 305: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

A.0.1 Java Generics

Sometimes Programming Language changes can aidelegance. Prior to Generics (1.4, say) a Java snippetmight look like:

ArrayList stolenBananas =

monkey.getBananas();

Object element;

Banana banana;

for (int i = 0; i < stolenBananas.size();

i++) {element = stolenBananas.get(i);

banana = (Banana) element;

monkey.peelAndEat(banana);

}

Q: Would Java complain about any of this at compile time?

A:

Q: Why is this a problem?

A:

Page 305 © 2019 Kyle Burke cb

Page 306: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q: How do generics solve this problem?

A:

Q: Assume now that getBananas returns anArrayList<Banana>. How can we rewrite the code?

A:

Page 306 © 2019 Kyle Burke cb

Page 307: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q: Which of our elegance criteria does this improve?

A:

Q: Is this new stuff worse in any way?

A:

That programming pattern became very common.Even before for-each loops existed, iterators weredevised to abstract away the need for reliance onlinear-shaped data structures.

Page 307 © 2019 Kyle Burke cb

Page 308: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

ArrayList<Banana> stolenBananas =

monkey.getBananas();

for (Iterator<Banana> bananaIterator

= stolenBananas.iterator();

iterator.hasNext(); ) {//leave a space here

monkey.peelAndEat(iterator.getNext());

}

Q: Why is this an improvement?

A:

Q: Any downsides?

A:

Page 308 © 2019 Kyle Burke cb

Page 309: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q: What do we have to change to make this extremelyreusable?

A:

Q: How does this change make our code more Extensi-ble/Maintainable?

A:

Q: Let’s rewrite the snippet using a for-each loop!

A:

Page 309 © 2019 Kyle Burke cb

Page 310: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q: How is this an improvement?

A:

Q: Is there any more room for improvement here?

A:

Q: What do you think that signature is?

A:

Q: But... Monkeys can also eat Oranges! Should we have twomethods?

A:

Page 310 © 2019 Kyle Burke cb

Page 311: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

A. JAVA PROGRAMMING WITH OBJECTS

Q: How can we combine them?

A:

The code might look like this:

public void peelAndEat(Fruit fruit) {fruit.peel();

this.eat(fruit);

}

Great! Now we’re using lots of inheritance.⟨ Draw a little class diagram: Banana and Orangeare subclasses of Fruit! ... and so is Watermelon. ⟩

Q: Any problems?

A:

Q: What might we want to do?

A:

Page 311 © 2019 Kyle Burke cb

Page 312: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

A.1 Summary

Q: What are some basic Heuristics (rules of thumb) we’velearned so far? (Some might be from previous courses too!)

A:

B Java and XML (JAXB)

Often we want the data from our program to persistbetween uses of the application, so we need to savethat data to a file. One way to do this is to useXML.36

36This section uses code adapted from https://www.mkyong.com/java/

jaxb-hello-world-example/ and https://www.mysoftkey.com/java/

jaxb-nested-list-of-java-object-example/.

Page 312 © 2019 Kyle Burke cb

Page 313: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

B.1 XML

TODO: Explain XML here...Suppose we have aMonkey class like this:

public class Monkey {

private String name;

private double tailLength; //in cm

//standard constructor

public Monkey(String name, double

tailLength) {this.name = name;

this.tailLength = tailLength;

}} //end of Monkey.java

I would like to be able to convert that to an XMLstring to save in a file, maybe looking something likethis:

<monkey>

<name>Mr. Peepers</name>

<tailLength>0.0</tailLength>

</monkey>

The conversion to XML is often called Marshallingand creating an object back from the XML is calledUnmarshalling.

Page 313 © 2019 Kyle Burke cb

Page 314: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

B.2 JAXB

JAXB is one of the most simple ways to convert JavaObjects to XML and back. To make saving to XMLwork for our Monkey.java class above, we have to dothe following:

• Import the proper packages.

• Add a no-argument constructor.

• Add a full suite of getters and setters for allfields I want to record.

• Mark the setters with decorator tags(@XmlElement) as necessary.

• Add the code (potentially elsewhere) to do theactual marshalling.

Here are the changes to the Monkey.java file fromabove:

Page 314 © 2019 Kyle Burke cb

Page 315: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

import javax.xml.bind.annotation.*;

public class Monkey {private String name;

private double tailLength; //in cm

//no-arg constructor for JAXB

public Monkey() {this.name = "";

this.tailLength = 0.0;

}//standard constructor

public Monkey(String name, double tailLength) {this.name = name;

this.tailLength = tailLength;

}

public String getName() {return this.name;

}@XmlElement

public void setName(String name) {this.name = name;

}

public double getTailLength() {return this.tailLength;

}@XmlElement

public void setTailLength(double tailLength) {this.tailLength = tailLength;

}} //end of Monkey.java

Page 315 © 2019 Kyle Burke cb

Page 316: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

Then let’s add another file, MonkeySaver.java thatdoes the actual marshalling:

import java.io.File;

import javax.xml.bind.*;

public class MonkeySaver {

public static void main(String[] args) {Monkey peepers = new Monkey("Mr. Peepers",

0.0);

File file = new File("monkey.xml");

try {JAXBContext jaxbContext =

JAXBContext.newInstance(Monkey.class);

Marshaller jaxbMarshaller =

jaxbContext.createMarshaller();

jaxbMarshaller.setProperty(

Marshaller.JAXB FORMATTED OUTPUT,

true);//nice printing

jaxbMarshaller.marshal(peepers, file);

} catch (JAXBException e) {e.printStackTrace();

}}

} //end of MonkeySaver.java

Now, upon running the MonkeySaver class, thiscreates a new file, with the desired XML.To recreate a Monkey object from the XML, we haveto do the unmarshalling:

Page 316 © 2019 Kyle Burke cb

Page 317: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

import java.io.File;

import javax.xml.bind.*;

public class MonkeyRestorer {

public static void main(String[] args) {File file = new File("monkey.xml");

try {

JAXBContext jaxbContext =

JAXBContext.newInstance(Monkey.class);

Unmarshaller jaxbUnmarshaller =

jaxbContext.createUnmarshaller();

Monkey peepers = (Monkey)

jaxbUnmarshaller.unmarshal(file);

} catch (JAXBException e) {e.printStackTrace();

}}

} //end of MonkeyRestorer.java

Now, by running MonkeyRestorer, it should createthe Monkey object from the XML file.

B.2.1 Composite Objects

So far we’ve seen how this works with objectscontaining basic fields. For objects with other objectsas fields or collections, we do much the same thing,but make sure to annotate the subobjects as well.Consider the following class, PrimateHouse, thatcontains a bunch of Monkey objects:

Page 317 © 2019 Kyle Burke cb

Page 318: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

public class PrimateHouse {private String name; //official name

private ArrayList<Monkey> inhabitants;

public PrimateHouse(String name) {this.name = name;

this.inhabitants = new ArrayList<Monkey>();

}

public void addMonkey(Monkey m) {this.inhabitants.add(m);

}} //end of PrimateHouse.java

In order to update this for use with JAXB, we needto do the usual stuff (like we did to Monkey.javabefore) as well as add another tag for the collection.To make it work, we need to add the followingsections to PrimateHouse.java:

Page 318 © 2019 Kyle Burke cb

Page 319: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

B. JAVA AND XML (JAXB)

import javax.xml.bind.annotation.*;

public class PrimateHouse {...(previous code is still here)...

//no-arg constructor for JAXB

public PrimateHouse() {this(""); //call the other one

}public String getName() {

return this.name;

}@XmlElement

public void setName(String name) {this.name = name;

}public ArrayList<Monkey> getInhabitants() {

return this.inhabitants;

}@XmlElementWrapper

@XmlElement

public void setInhabitants(ArrayList<Monkey>

inhabitants) {this.inhabitants = inhabitants;

}} //end of PrimateHouse

With this code, you can write classes likeMonkeySaver and MonkeyRestorer (but for thePrimateHouse) that will save and restore thePrimateHouse object.It’s important to point out that JAXB doesn’tactually set the wrapper collection element the way

Page 319 © 2019 Kyle Burke cb

Page 320: CS 4140: Software Engineeringkgb1013/DB/4140/lecture... · 2019-06-03 · grad school. Luckily, the torch continued burning, and I got to teach an upper-level software course right

REFERENCES REFERENCES

you would probably expect. Instead of creating acollection and setting the inhabitants to thatcollection using setInhabitants, it uses thegetInhabitants method to get a pointer to thecollection, then adds them via that. The problemhere is that if you have something else going on insetInhabitants besides just setting the field, thoseoperations won’t get activated.37

References

[1] F. Buschmann, R. Meunier, H. Rohnert,P. Sommerlad, and M. Stal. Pattern-orientedSoftware Architecture: a System of Patterns,Volume 1. Number v. 1. John Wiley and Sons,1996.

[2] Erich Gamma, Richard Helm, Ralph E. Johnson,and John Vlissides. Design Patterns: Elements ofReusable Object-Oriented Software.Addison-Wesley, Reading, MA, 1995.

[3] J. Paul. Producer consumer design pattern withblocking queue example in java, 2012.http://javarevisited.blogspot.com/2012/

02/producer-consumer-design-pattern-with.

html.

[4] Dale Skrien. Object-Oriented Design Using Java(1. ed.). McGraw-Hill Education, 2008.

37I’m not sure whether there’s a workaround for this or not. Perhaps I need to havethe parameter to setInhabitants be a Collection or Iterable of Monkeys instead of themore-strict ArrayList.

Page 320 © 2019 Kyle Burke cb