Presentation is loading. Please wait.

Presentation is loading. Please wait.

Mandatory 2 / Strategies Note: I publish this presentation at the week plan for week 4.

Similar presentations


Presentation on theme: "Mandatory 2 / Strategies Note: I publish this presentation at the week plan for week 4."— Presentation transcript:

1 Mandatory 2 / Strategies Note: I publish this presentation at the week plan for week 4

2 Learning... http://blogs.hbr.org/johnson/2012/09/throw-your- life-a-curve.html CS@AUH B Christensen2

3 Tides are turning? Henrik Bærbak Christensen3

4 A story about Kent Beck I attended JAOO many years ago. Kent Beck talked about design patterns I asked him how I should do as a teacher? –Pose problems to students, show DP afterwards? –Show DP first, let students solve problem using DP Henrik Bærbak Christensen4

5 The response Kent answered Let them feel the pain... Henrik Bærbak Christensen5

6 Exercise: Why is this unfortunate? In GameImpl: Henrik Bærbak Christensen6

7 Exercise: Why is this unfortunate? In GameImpl: Henrik Bærbak Christensen7

8 The problem... A theme of much code the TAs sends me is 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 Christensen8

9 So – You will feel the pain Henrik Bærbak Christensen9

10 TDD: Maximize work not done May this is unfair –TDD:Only do what is specified, do not think ahead True, but if two solutions are about equal and one only solves one problem, the other all – we of course pick the general one –int sum(x,y) { return x+y; } –int sum(x,y) { if (x==2 && y==3) return 5; if (x==17&& Henrik Bærbak Christensen10

11 GammaCiv and UnitAction

12 GammaCiv and 36.11 GammaCiv: Settler and Archer action –destroy settler, create city ; fortify archer Two Solutions / polymorphic or compositional –What/Who (behavioral focus / compositional): What: Encapsulate ’unit action’ = algorithm = Strategy Who: Game’s ’performUnitActionAt’ delegates... –Who/What (model focus / polymorphic): Who: The settler ’does something’ What: create city (and kill itself?); modify archer def. strength Henrik Bærbak Christensen12

13 Settler Action, Compositional Strategy on performUnitActionAt Henrik Bærbak Christensen13

14 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 Christensen14

15 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 Christensen15

16 Polymorphic Henrik Bærbak Christensen16

17 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 Christensen17

18 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 Christensen18

19 More Fun stuff from trenches Henrik Bærbak Christensen19

20 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 Christensen20

21 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

22 Dependency Injection Merits –All variant handling code in cohesive object But think AbstractFactory handles it more elegant Henrik Bærbak Christensen22

23 Variability is variable (3) Encapsulate what varies –Or Cutting the cake properly. It is difficult Henrik Bærbak Christensen23

24 Multiple Maintenance  Source code copy. Easy but costly! –Here comes the Chariot! Henrik Bærbak Christensen24

25 NullObject Avoid the if ( strategy != null ) pit fall: Henrik Bærbak Christensen25 if(unitActionStrategy == null) return;

26 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 Christensen26

27 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 Christensen27

28 Analyzability Henrik Bærbak Christensen28

29 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 Christensen29

30 Do not dispair TA presented a ‘nice solution’... Morale: We often over-engineer Henrik Bærbak Christensen30

31 Previous Years Henrik Bærbak Christensen31

32 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 Christensen32

33 Design Pitfalls Writing simple algorithms Henrik Bærbak Christensen33

34 ”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 Christensen34

35 Cohesive roles Role well defined? Encapsulate what varies? Henrik Bærbak Christensen35

36 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 Christensen36

37 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 Christensen37

38 Readability? Henrik Bærbak Christensen38 Positive: –Comments! Negative: –Code duplication! –Nesting level. Code duplication leads to bugs! Exercise: Find duplication bug

39 My refactoring Henrik Bærbak Christensen39 Note: The tile type bugs are kept.

40 Which would you prefer to review ? Henrik Bærbak Christensen40

41 More of the same...

42 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!)

43 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

44 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 Christensen44

45 More State Henrik Bærbak Christensen45 Pro: Learning exercise Con: Overkill!!!

46 Misc... Why not just use the Alpha strategy? Henrik Bærbak Christensen46

47 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 Christensen47

48 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 Christensen48

49 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 Christensen49

50 UML Brush up Review class and sequence diagrams from your old books Henrik Bærbak Christensen50

51 Henrik Bærbak Christensen51 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

52 Henrik Bærbak Christensen52 Behavior Sequence diagrams –Describe a single scenario Example –Buy ticket sequence Participant (object) message return self-call creation Timeline activation

53 Frames Henrik Bærbak Christensen53

54 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 Christensen54

55 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 Christensen55

56 One Strategy to Rule Them All... Henrik Bærbak Christensen56

57 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 Christensen57

58 The Worst of Two worlds... Henrik Bærbak Christensen58

59 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 Christensen59

60 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 Christensen60


Download ppt "Mandatory 2 / Strategies Note: I publish this presentation at the week plan for week 4."

Similar presentations


Ads by Google