josh bloch charlie garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · source: braude,...

35
1 17-214 Principles of Software Construction: Objects, Design, and Concurrency Part 1: Design for reuse Behavioral subtyping Josh Bloch Charlie Garrod

Upload: others

Post on 22-Jun-2021

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

1 17-214

PrinciplesofSoftwareConstruction: Objects,Design,andConcurrencyPart1:DesignforreuseBehavioralsubtypingJoshBloch CharlieGarrod

Page 2: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

2 17-214

Administrivia

•  Homework1gradedsoon•  PleasesignandreturncollaborationpolicytoGradescope

•  Readingduetoday:EffectiveJava,Items17and50–  OptionalreadingdueThursday–  RequiredreadingduenextTuesday

•  Homework2dueSunday11:59p.m.

Page 3: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

3 17-214

Requiredreadingparticipationquiz

•  https://bit.ly/32x0vsU

Page 4: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

4 17-214

DesigngoalsforyourHomework1solution?

Functionalcorrectness Adherenceofimplementationtothespecifications

Robustness Abilitytohandleanomalousevents

Flexibility Abilitytoaccommodatechangesinspecifications

Reusability Abilitytobereusedinanotherapplication

Efficiency Satisfactionofspeedandstoragerequirements

Scalability Abilitytoserveasthebasisofalargerversionoftheapplication

Security Levelofconsiderationofapplicationsecurity

Source: Braude, Bernstein, Software Engineering. Wiley 2011

Page 5: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

5 17-214

OneHomework1solution…

classDocument{privatefinalStringurl;publicDocument(Stringurl){this.url=url;}publicdoublesimilarityTo(Documentd){…ourText=download(url);…theirText=download(d.url);…ourFreq=computeFrequencies(ourText);…theirFreq=computeFrequencies(theirText);returncosine(ourFreq,theirFreq);}…}

Page 6: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

6 17-214

ComparetoanotherHomework1solution…

classDocument{privatefinalStringurl;publicDocument(Stringurl){this.url=url;}publicdoublesimilarityTo(Documentd){…ourText=download(url);…theirText=download(d.url);…ourFreq=computeFreq(ourText);…theirFreq=computeFreq(theirText);returncosine(ourFreq,theirFreq);}…}

classDocument{privatefinal…frequencies;publicDocument(Stringurl){…ourText=download(url);frequencies=computeFrequencies(ourText);}publicdoublesimilarityTo(Documentd){returncosine(frequencies,d.frequencies);}…}

Page 7: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

7 17-214

UsingtheDocumentclass

Foreachurl:ConstructanewDocumentForeachpairofDocumentsd1,d2:Computed1.similarityTo(d2)…

•  Whatistherunningtimeofthis,fornurls?

Page 8: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

8 17-214

LatencyNumbersEveryProgrammerShouldKnowJeffDean,SeniorFellow,Google

PRIMITIVELATENCY:nsusmsL1cachereference0.5Branchmispredict5L2cachereference7Mutexlock/unlock25Mainmemoryreference100Compress1KbyteswithZippy3,0003Send1Kbytesover1Gbpsnetwork10,00010Read4KrandomlyfromSSD*150,000150Read1MBsequentiallyfrommemory250,000250Roundtripwithinsamedatacenter500,000500Read1MBsequentiallyfromSSD*1,000,0001,0001Diskseek10,000,00010,00010Read1MBsequentiallyfromdisk20,000,00020,00020SendpacketCA->Netherlands->CA150,000,000150,000150

Page 9: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

9 17-214

Thepoint

•  Constantsmatter•  Designgoalssometimesclearlysuggestonealternative

Page 10: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

10 17-214

DesigngoalsforyourHomework2solution?

Functionalcorrectness Adherenceofimplementationtothespecifications

Robustness Abilitytohandleanomalousevents

Flexibility Abilitytoaccommodatechangesinspecifications

Reusability Abilitytobereusedinanotherapplication

Efficiency Satisfactionofspeedandstoragerequirements

Scalability Abilitytoserveasthebasisofalargerversionoftheapplication

Security Levelofconsiderationofapplicationsecurity

Source: Braude, Bernstein, Software Engineering. Wiley 2011

Page 11: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

11 17-214

KeyconceptsfromlastThursday

Page 12: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

12 17-214

KeyconceptsfromlastThursday

•  Exceptions•  Specifyingprogrambehavior:contracts•  Testing:

–  Continuousintegration,practicaladvice–  Coveragemetrics,statementcoverage

•  Thejava.lang.Objectcontracts

Page 13: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

13 17-214

Selectingtestcases

•  Writetestsbasedonthespecification,for:–  Representativecases–  Invalidcases–  Boundaryconditions

•  Writestresstests–  Automaticallygeneratehugenumbersoftestcases

•  Thinklikeanattacker•  Othertests:performance,security,systeminteractions,…

Page 14: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

14 17-214

Methodscommontoallobjects

•  Howdocollectionsknowhowtotestobjectsforequality?•  Howdotheyknowhowtohashandprintthem?•  TherelevantmethodsareallpresentonObject

–  toString-returnsaprintablestringrepresentation–  equals-returnstrueifthetwoobjectsare“equal”–  hashCode-returnsanintthatmustbeequalforequalobjects,andislikelytodifferonunequalobjects

Page 15: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

15 17-214

ThehashCodecontract

Wheneveritisinvokedonthesameobjectmorethanonceduringanexecutionofanapplication,thehashCodemethodmustconsistentlyreturnthesameinteger,providednoinformationusedinequalscomparisonsontheobjectismodified.Thisintegerneednotremainconsistentfromoneexecutionofanapplicationtoanotherexecutionofthesameapplication.–  Iftwoobjectsareequalaccordingtotheequals(Object)method,thencallingthe

hashCodemethodoneachofthetwoobjectsmustproducethesameintegerresult.

–  Itisnotrequiredthatiftwoobjectsareunequalaccordingtotheequals(Object)method,thencallingthehashCodemethodoneachofthetwoobjectsmustproducedistinctintegerresults.However,theprogrammershouldbeawarethatproducingdistinctintegerresultsforunequalobjectsmayimprovetheperformanceofhashtables.

Page 16: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

16 17-214

ThehashCodecontractinEnglish

•  Equalobjectsmusthaveequalhashcodes–  IfyouoverrideequalsyoumustoverridehashCode

•  Unequalobjectsshouldhavedifferenthashcodes–  Takeallvaluefieldsintoaccountwhencalculatingit

•  Hashcodemustnotchangeunlessobjectmutated–  Useadeterministicfunctionofthefieldvalues

Page 17: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

17 17-214

hashCodeoverrideexample

publicfinalclassPhoneNumber{privatefinalshortareaCode;privatefinalshortprefix;privatefinalshortlineNumber;@OverridepublicinthashCode(){intresult=17;//Nonzeroisgoodresult=31*result+areaCode;//Constantmustbeoddresult=31*result+prefix;//""""result=31*result+lineNumber;//""""returnresult;}...}

Page 18: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

18 17-214

AlternativehashCodeoverrideLessefficient,butotherwiseequallygood!

publicfinalclassPhoneNumber{privatefinalshortareaCode;privatefinalshortprefix;privatefinalshortlineNumber;@OverridepublicinthashCode(){returnObjects.hash(areaCode,prefix,lineNumber);}...}

Aoneliner.NoexcuseforfailingtooverridehashCode!

Page 19: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

19 17-214

Formorethanyouwanttoknowaboutoverridingobjectmethods,seeEffectiveJavaChapter2

Page 20: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

20 17-214

Today

•  Behavioralsubtyping–  LiskovSubstitutionPrinciple

•  Designforreuse:delegationandinheritance(Thursday)–  Java-specificdetailsforinheritance

Page 21: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

21 17-214

Recall:Theclasshierarchy

•  TherootisObject(allnon-primitivesareObjects)•  AllclassesexceptObjecthaveoneparentclass

–  Specifiedwithanextendsclause:classGuitarextendsInstrument{...}

–  Ifextendsclauseisomitted,defaultstoObject•  Aclassisaninstanceofallitssuperclasses

Object

ToyInstrument

YoyoGuitar

Page 22: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

22 17-214

Behavioralsubtyping

•  e.g.,Compiler-enforcedrulesinJava:–  Subtypescanadd,butnotremovemethods–  Concreteclassmustimplementallundefinedmethods–  Overridingmethodmustreturnsametypeorsubtype–  Overridingmethodmustacceptthesameparametertypes–  Overridingmethodmaynotthrowadditionalexceptions

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

Barbara Liskov

This is called the Liskov Substitution Principle.

Page 23: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

23 17-214

Behavioralsubtyping

•  e.g.,Compiler-enforcedrulesinJava:–  Subtypescanadd,butnotremovemethods–  Concreteclassmustimplementallundefinedmethods–  Overridingmethodmustreturnsametypeorsubtype–  Overridingmethodmustacceptthesameparametertypes–  Overridingmethodmaynotthrowadditionalexceptions

•  Alsoappliestospecifiedbehavior.Subtypesmusthave:–  Sameorstrongerinvariants–  Sameorstrongerpostconditionsforallmethods–  Sameorweakerpreconditionsforallmethods

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

Barbara Liskov

This is called the Liskov Substitution Principle.

Page 24: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

24 17-214

LSPexample:CarisabehavioralsubtypeofVehicle

abstractclassVehicle{intspeed,limit;//@invariantspeed<limit;//@requiresspeed!=0;//@ensuresspeed<\old(speed)abstractvoidbrake();}

classCarextendsVehicle{intfuel;booleanengineOn;//@invariantspeed<limit;//@invariantfuel>=0;//@requiresfuel>0&&!engineOn;//@ensuresengineOn;voidstart(){…}voidaccelerate(){…}//@requiresspeed!=0;//@ensuresspeed<\old(speed)voidbrake(){…}}

Subclass fulfills the same invariants (and additional ones) Overridden method has the same pre and postconditions

Page 25: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

25 17-214

LSPexample:HybridisabehavioralsubtypeofCar

classCarextendsVehicle{intfuel;booleanengineOn;//@invariantspeed<limit;//@invariantfuel>=0;//@requiresfuel>0&&!engineOn;//@ensuresengineOn;voidstart(){…}voidaccelerate(){…}//@requiresspeed!=0;//@ensuresspeed<\old(speed)voidbrake(){…}}

classHybridextendsCar{intcharge;//@invariantcharge>=0;//@invariant…//@requires(charge>0||fuel>0)

&&!engineOn;//@ensuresengineOn;voidstart(){…}voidaccelerate(){…}//@requiresspeed!=0;//@ensuresspeed<\old(speed)//@ensurescharge>\old(charge)voidbrake(){…}}Subclass fulfills the same invariants (and additional ones)

Overridden method start has weaker precondition Overridden method brake has stronger postcondition

Page 26: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

26 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//methods

}

classSquareextendsRectangle{Square(intw){ super(w,w);}

}

Page 27: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

27 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//methods

}

classSquareextendsRectangle{Square(intw){ super(w,w);}

}

(Yes.)

Page 28: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

28 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//methods

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

}

Page 29: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

29 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//methods

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

}

(Yes.)

Page 30: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

30 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//@requiresfactor>0;

voidscale(intfactor){ w=w*factor; h=h*factor;}

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

}

Page 31: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

31 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//@requiresfactor>0;

voidscale(intfactor){ w=w*factor; h=h*factor;}

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

}

(Yes.)

Page 32: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

32 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//@requiresfactor>0;

voidscale(intfactor){ w=w*factor; h=h*factor;}

//@requiresneww>0;voidsetWidth(intneww){ w=neww;}

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

}

Page 33: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

33 17-214

IsthisSquareabehavioralsubtypeofRectangle?

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//@requiresfactor>0;

voidscale(intfactor){ w=w*factor; h=h*factor;}

//@requiresneww>0;voidsetWidth(intneww){ w=neww;}

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

}

← Invalidates stronger invariant (h==w) in subclass

classGraphicProgram{voidscaleW(Rectangler,intf){r.setWidth(r.getWidth()*f);}}

(Yes! But the Square is not a square…)

Page 34: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

34 17-214

ThisSquareisnotabehavioralsubtypeofRectangle

classRectangle{//@invarianth>0&&w>0;inth,w;Rectangle(inth,intw){ this.h=h;this.w=w;}

//@requiresfactor>0;

voidscale(intfactor){ w=w*factor; h=h*factor;}

//@requiresneww>0;//@ensuresw==neww&&h==old.h;

voidsetWidth(intneww){ w=neww;}

}

classSquareextendsRectangle{//@invarianth>0&&w>0;//@invarianth==w;

Square(intw){ super(w,w);}

//@requiresneww>0;//@ensuresw==neww&&h==neww;@OverridevoidsetWidth(intneww){w=neww;h=neww;}}

Page 35: Josh Bloch Charlie Garrodcharlie/courses/17-214/2021... · 2021. 2. 16. · Source: Braude, Bernstein, Software Engineering. Wiley 2011 . 17-214 11 Key concepts from last Thursday

35 17-214

Today

•  Behavioralsubtyping–  LiskovSubstitutionPrinciple

•  Designforreuse:delegationandinheritance(Thursday)–  Java-specificdetailsforinheritance