Download presentation
Presentation is loading. Please wait.
Published byHarriet Freeman Modified over 9 years ago
1
Hints - Mandatory 2 / Strategies
2
Learning... http://blogs.hbr.org/johnson/2012/09/throw-your- life-a-curve.html CS@AUH B Christensen2 Jeg fatter ikke en bjælde!?! Aah, det giver da lidt mening!
3
TDD being standard? Henrik Bærbak Christensen3
4
Fake-it is a strong tool... To help new abstractions into development as part of keeping focus on something else. Check out the screencast on weekplan 2 (unit- move-faked). Feature: moveUnit –Require a data structure for storing units in the world, so a World role is faked to keep focus on the moveUnit method... Henrik Bærbak Christensen4
5
Java 8 and Lambda expressions Java 8 (finally) introduced lambda’s –Inline code blocks Henrik Bærbak Christensen5
6
Sprint 2 Functional requirements –Develop and maintain 4 variants Beta: Alternative winning and aging algorithm Gamma: Allows some units to do an action Delta: Alternative world layout –All are variants of AlphaCiv Real requirementsReview the rubrics! –Use AlphaCiv tests to support refactoring GameImpl into a compositional design (strategy pattern) –Demonstrate and argue for your design Remember to TDD the new variant implementations Remember unit and integration testing Henrik Bærbak Christensen6
7
Great discussions “Your specification of feature X in HotCiv is unclear, Henrik!” –Yes. Face it – this is how real life is! –Agile method’s answer: Ask the customer! “on-site customer” / “product owner” My answer is always –I do not really care about functionality This is not an algorithm course! –dSoftArk is about flexible reliable design This is a software architecture course So: pick the simplest algorithmic solution that fit the requirement and spend the time on a flexible and reliable design Henrik Bærbak Christensen7
8
Best way to code... Grab yourself a copy of Uncle Bob’s book ! Ask on the web board! And read the comments –Best way to structure packages ? Good question Henrik Bærbak Christensen8
9
Conditionals are hard to read!!! Is this code correct for moveUnit If it is hard to write then –It is probably buggy! –You yourself cannot understand it in two weeks –Bjarne will never ever be able to understand it Beware when he comes around and “fixes” it!!! Henrik Bærbak Christensen9
10
Real example...
11
Remedy 1: Fail-fast Think which conditions allows me to bail out immedately? Henrik Bærbak Christensen11
12
Remedy 2: Take small steps Divide and conquer. Take small steps. Henrik Bærbak Christensen12
13
Often more analyzable to ‘patch’ Henrik Bærbak Christensen13 Plains
14
Side note Simplicity – Maximize work not done Henrik Bærbak Christensen14 Remember – A GUI handles a lot of cases for us so it is actually wrong to implement code that handles situations that violate preconditions! And to make test cases for it!
15
Fake-it till you make it Fake-it is a wonderful pattern but should be removed and replaced by proper general algorithms as soon as possible!!! Anti example –We must develop: int sum(x,y) –Iteration 1: assertEquals( 3, obj.sum(1,2) ); int sum(int x, int y) { return 3; } –Iteration 2: assertEquals( 5, obj.sum(3,2) ); int sum(int x, int y) { if (x==3 && y==2) return 5; else return 3; } Henrik Bærbak Christensen15 This is a catastrophe and has nothing to do with TDD!
16
Exercise: Why is this unfortunate? In GameImpl: Henrik Bærbak Christensen16
17
Exercise: Why is this unfortunate? In GameImpl: Henrik Bærbak Christensen17
18
The problem... A theme of much code last years: You try to introduce strategies (compositional) But wrap them in param./polym. designs Result:All liabilities from both methods –Inflexibility and code bloat from the if (...) { } / subclass –And all the extra classes and interfaces from Composition Henrik Bærbak Christensen18
19
GammaCiv and UnitAction
20
GammaCiv and 36.11 GammaCiv: Settler and Archer action –destroy settler, create city ; fortify archer Two Solutions / polymorphic or compositional –Who/What (model focus / polymorphic): Who: The settler ’does something’ What: create city (and kill itself?); modify archer def. strength –What/Who (behavioral focus / compositional): What: Encapsulate ’unit action’ = algorithm = Strategy Who: Game’s ’performUnitActionAt’ delegates... Henrik Bærbak Christensen20
21
Settler Action, Polymorphic Polymorphic method on Unit GameImpl.performAction() { u.action(); } Cohesion –High: what a settler /archer does; but unit now ”knows a lot” Coupling –City : Unit now coupled to City (”must say new StdCity()”); –World: Either direct access or ask Game to put city –Destroying: Cannot be done, must ask Game –Making settlers: abstract factory to make subtype outside HotCiv framework (which contain a switch)– OR a switch on unit type (no support for adding types later) Henrik Bærbak Christensen21
22
Polymorphic Henrik Bærbak Christensen22
23
Settler Action, Compositional Strategy on performUnitActionAt Henrik Bærbak Christensen23
24
Settler Action, Compositional Strategy on performUnitActionAt Cohesion: –High: GammaActionStrategy is highly focused; but potentially knows many unit types (parametric switching) but in the delegate!!! Coupling: Must know –Unit (or just the type) –Game Or rather methods to create city and destroy unit Or know city + world –Cities’ unit making: just ”new UnitImpl(type);” - done –GammaActionStrategy: has a switch on unit types... Henrik Bærbak Christensen24
25
Settler Action, Score Board Which is the better? Compositional scores best... Benefit –Lower coupling (No Unit->”Others” coupling) –Easier to create Units (all are alike except type string) Avoid need for factory system when it is a framework –Unit destroying has to be made in Game anyway –Easy to configure Game with new actions strategies –Polymorphic must have a switch anyway! (just in another place) Liabilities –ActionStrategy will contain a type switch Parameterized variance but in ’external’ code. –May become ’blob-code’, difficult to reuse... Henrik Bærbak Christensen25
26
Reuse of Strategies Note that adding, say, a Chariot unit type can be made purely by addition in compositional case... –Compositional: add a ”XYZActionStrategy” which If (type.equals(”Chariot”)) {...} else { [D].performUnitActionAt(p); } –Where [D] is either superin case new strategy inherits from the old one delegatein case we do composition –Which is actually the decorator pattern –Polymorphic: Add ChariotUnit + modify city code Henrik Bærbak Christensen26
27
Keep your Test code clean! Do not duplicate AlphaCiv test cases in BetaCiv Only include the Beta specific test cases –Or better – unit test the WinnerStrategy... Henrik Bærbak Christensen27
28
Delegate Truely! I say –son.takeGarbageToCan() I do not say –son.pickUpGarbage(); –son.walkToCan(); –son.openCanLid(); –son.putGarbageIntoCan(); –son.walkToHouse(); Exercise: Why is second version problematic? Henrik Bærbak Christensen28
29
Delegate Truely Do not tell the strategy the invidiual steps! Let the strategy take its responsibility! –layoutStrategy.layoutWorld( tileList, cityList, unitList ); –Or similar... Henrik Bærbak Christensen29
30
More Fun stuff from trenches Henrik Bærbak Christensen30
31
Beta Winner – General or not? Cities in AlphaCiv, how? –Matrix of City Objects? List of City Objects? –Matrix of Tile objects having reference to City object? –World class? –City redCity; blueCity; ??? Beta Winner: All cities conquered –But Beta is Alpha which has only two cities??? –A) Iterate world, ensure all cities owned by player X –B) redCity.getOwner() == blueCity.getOwner() ? Henrik Bærbak Christensen31
32
Maximize work not done BetaCiv Winner –First to conquer all cities in the world But BetaCiv augments AlphaCiv in which no cities can be produced! –Winner algo: { if owner(c1) == owner(c2) return true; } What if we later can produce cities? –Then we must refactor winner algorithm What if we never will be requested to produce cities? –The we have saved valuable time now
33
Dependency Injection Merits –All variant handling code in cohesive object But think AbstractFactory handles it more elegant Henrik Bærbak Christensen33
34
Variability is variable (3) Encapsulate what varies –Or Cutting the cake properly. It is difficult Henrik Bærbak Christensen34
35
Multiple Maintenance Source code copy. Easy but costly! –Here comes the Chariot! Henrik Bærbak Christensen35
36
NullObject Avoid the if ( strategy != null ) pit fall: Henrik Bærbak Christensen36 if(unitActionStrategy == null) return;
37
Do not dispair TA presented a ‘nice solution’... Morale: We often over-engineer Henrik Bærbak Christensen37
38
Previous Years Henrik Bærbak Christensen38
39
Review your UML ”The blender is in the frog” –Structure of sentences is important! Dependency –Rather vague –Use assoc/aggr istead Unit-GameImpl –The wrong way around Henrik Bærbak Christensen39
40
Design Pitfalls Writing simple algorithms Henrik Bærbak Christensen40
41
”Accessor becomes Mutator” trap I have seen this many times As our code only calls ‘getWinner’ once per round, it seems like a nice place to handle the round increment. What is the major problem in that? Henrik Bærbak Christensen41
42
Cohesive roles Role well defined? Encapsulate what varies? Henrik Bærbak Christensen42
43
Cohesive roles Problem: –moveUnit is same for all game variants –performAction is not Thus –Variable + common behaviour in same unit => one cannot change without other affected Group's solution –Gamma inherits Alpha Henrik Bærbak Christensen43
44
Minor 'not so good' I do not like the 'setGame'. I would prefer –performAction(game,pos); –(I.e. Pass game instance every time.) Why? Henrik Bærbak Christensen44
45
Readability? Henrik Bærbak Christensen45 Positive: –Comments! Negative: –Code duplication! –Nesting level. Code duplication leads to bugs! Exercise: Find duplication bug
46
My refactoring Henrik Bærbak Christensen46 Note: The tile type bugs are kept.
47
Which would you prefer to review ? Henrik Bærbak Christensen47
48
More of the same...
49
Writing simple algorithms... How do I write 'simple' algorithms like moveUnit? Use C style 'bail out': if (x) return; Simplicity: – Take the simplest first (requires fewest info) – Intro more info as you need it (only then!) – Write the comments first (keep focus!)
50
Writing simple algorithms… Try hard to avoid –Conditionals with too many elements If ( cond1 && cond2 || cond3 ) –If you cannot avoid it, then unfold the conditions Boolean noUnitOnFrom = game.getUnitAt(p) == null; Boolean toCannotBeMovedTo =...; If ( noUnitOnFrom || toCannotBeMovedTo ) return false; –Use the C style bail-out, not Pascal style nested ifs If (bad) return false;Simple If (! bad ) {... } else { return false; }Complex
51
Package structure Common and variant code Common = code that is executed in all variants of the final delivered systems –GameImpl Variant = code (delegate) that is executed in one or a few variants Henrik Bærbak Christensen51
52
More State Henrik Bærbak Christensen52 Pro: Learning exercise Con: Overkill!!!
53
Misc... Why not just use the Alpha strategy? Henrik Bærbak Christensen53
54
Unit versus System test Important to test the game because it is what the ’costumer’ pays for No test that ’move’ method will not move the unit! Henrik Bærbak Christensen54
55
The mutable interface danger Pro: –Better to directly set the testable condition (set owner of city to blue) than a lot of (defect-potential) code to get the game into this situation Con: –Really really bad to introduce a mutator method in City interface directly Henrik Bærbak Christensen55
56
Unit/Integeration testing Many groups test AgingStrategy through Game –That is: one zillion ”endOfTurn()” Remember Unit testing –assertEquals( -4000, as.calcAge(0)); –assertEquals( -100, as.calcAge(39)); –assertEquals( -1, as.calcAge(40)); –Etc. Henrik Bærbak Christensen56
57
UML Brush up Review class and sequence diagrams from your old books Henrik Bærbak Christensen57
58
Henrik Bærbak Christensen58 Software View Think roadmap! –Avoid method names Still – take care no to overload with detail... Much different from conceptual view. Navigability Class Realization/impl Interface
59
Henrik Bærbak Christensen59 Behavior Sequence diagrams –Describe a single scenario Example –Buy ticket sequence Participant (object) message return self-call creation Timeline activation
60
Frames Henrik Bærbak Christensen60
61
Src-Code-Copy No no no... –Do not make a copy of AlphaCiv to begin working on BetaCiv etc. You can and will see this in practice, but... This is not the intended learning outcome Henrik Bærbak Christensen61
62
Clean Code That Works...That Works is not enough... Clean code means –Refactoring you existing code Review coupling and cohesion –Removing duplicated code –Review method and variable names Do they convey the proper meaning? –Create classes / packages Move methods / classes into better named software units Henrik Bærbak Christensen62
63
One Strategy to Rule Them All... Henrik Bærbak Christensen63
64
Beware What will happen when... –I have three different winner conditions –I have four different aging strategies –... And eight different configurations of unit actions? Combinatorial explosion of subclasses... Henrik Bærbak Christensen64
65
The Worst of Two worlds... Henrik Bærbak Christensen65
66
There Must Be a Switch Somewhere! However, it is important where it is! –Inside game You cannot add new variants expect by change by modification –In the main method /configuration code All the HotCiv code can be frozen into a JAR file that is not going to be changed! How often have you added a clause to a switch inside Java Swing? Henrik Bærbak Christensen66
67
Getting Info Into the Strategies How does WinnerStrategy know anything??? –Review Finn’s note on the web site... Internal datastructure (like ’array of tile/city’) –Sending internal data structure of GameImpl to the strategy Higher coupling, cannot change datastructure later, no encapsulation... –Double references WinnerStrategy s = new BetaWinnerStrategy(game) Game game = new GameImpl(s); Better: return getWinner(this) in GameImpl... Henrik Bærbak Christensen67
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.