OO ANALYSIS & DESIGN
OO ANALYSIS & DESIGN CSCI 6448
Popular in Course
Popular in ComputerScienence
This 29 page Class Notes was uploaded by Allie West II on Thursday October 29, 2015. The Class Notes belongs to CSCI 6448 at University of Colorado at Boulder taught by Staff in Fall. Since its upload, it has received 6 views. For similar materials see /class/231999/csci-6448-university-of-colorado-at-boulder in ComputerScienence at University of Colorado at Boulder.
Reviews for OO ANALYSIS & DESIGN
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/29/15
Credit where Credit is Due Some of the material for this lecture and LeCture 28 RefaCtoring part 2 lecture 25 is taken from Refactoring Improving the Design of Existing Code by Martin Fowler as such some Kenneth M Anderson material is copyright Addison Wesley ObjectOriented Analysis and Design 1999 CSCI 6448 Spring Semester 2003 April 17 2003 University of Colorado 2003 2 Last Lecture Goals for this lecture Refactoring Presenta more complete tutorial on Introduced core ideas refactoring using a slightly larger example Improve design without changing functionality that requ39res mUIt39ple refaCtOr39ngS Watch out for bad smells in code Covered several examples April 17 2003 University of Colorado 2003 3 April 17 2003 University of Colorado 2003 4 Tutorial A simple program for a video store vie Rental Customer customer object can print a statement in ASCll We d like to modify the code to also print a statement in HTML and have discovered that none ofthe existing code can be reused See example code available on class website Added a test case We will test our code after each refactoring April 172003 University of Colorado 2003 5 Does this code need refactoring For such a simple system probably not but imagine that these three classes are part of a larger system a then the refactorings we do during the tutorial can indeed be useful the point is to imagine following this process on a daily basis in a larger system projec refactoring needs to be incremental systematic and safe April 172003 Universiton Colorado 2003 s Initial Class Diagram statement works by looping through all rentals for each rental it retrieves its movie and the number of days it was rented it also retrieves the price code of the movie it then calculates the price for each movie rental and the number of frequent renter points and returns the generated statement as a string see page 4 of Refactoring April 172003 University of Colorado 2003 7 Step 1 refactor statement Why It s a long methodquot which is one of the bad smellsquot presented in the last lecture Besides our purpose is to add a new method to generate an HTML statement and refactoring statement may lead to code that can be reused by the new function a This matches one of Fowler s conditions for refactoring cleaning up the code to make it possible to add a new function April 172003 University of Colorado 2003 s How to start a We want to d e ecompose t Wl llCl I ar he statement method into smaller pieces easterlo manage and move around act Methodquot et the switch statement rst each and thIsAmount ahles eah he passed as parameters to the hew method 1 required odrned vahahles requlre more Dareslnee there is only ohe we eah make it the returh value or the hew method Pitta s a be caretul about return types in the Onglnal statement Il llSAmOunI lS a n nhl return an lnl rryou do yourtest will ral because the rounding orrnts to the Customer class 1n the stem directory April 172003 o Unlverslty or Colorado 2003 Step 2 rename variables The variable names in the new amountFor method don t make sense now that they have been moved out of the statement method a Any fool can write code that a computer can understand Good programmers write code that humans can understandquot Lets rename them and run our test a so far so good April 172003 o Unlverslty or Colorado 2003 Step 3 move method amountFor uses information from the Rental class but it does not use information from the customer class where it is currently located methods should be located close to the data they operate so lets move amountFor to the Rental class we can get rid of the parameter this way lets also rename the method to getCharge to clarify what it is doing as a result back in Customer we must delete the old method and change the call to amountForeach t eachgetChargeo then we need to compile and test all good Aprll 172003 Unlverslty of Colorado 20 New class diagram 1 Ima HEW No major changes however Customer is now a smaller class and an operation has been moved to the class that has the data it needs to do its job De nitely making progress April 172003 o Unlverslty or Colorado 2003 Step 4 Replace Temp with Query In the statement method thisAmount is now redundant It is set once with the cal eachgetCharge and is not changed afterward lets t ri 39 Don39t forget to run your test Removing temp variables is a good thing because they often cause the need for parameters where none are required and can also cause problems in long methods of course the charge is now calculated twice through the loo but we can optimizet e calculation later but only if we determine that it is slowing us down April 172003 University of Coloraoo 2003 13 Step 5 frequent renter points Lets do the same thing with the logic to calculate frequent renter points Step 5a extract method each can be a parameter as in step l frequentRenterPoints has a value before the method is 39 e new metho oes not read it we simply need to use appending assingment outside the method Step 5b move method Again we are only using information from Rental not customer so lets move getFrequentRenterPoints to the Rental class Be sure to run your test case after each step April 172003 University of Coloraoo 2003 14 New class diagram m i s Women qetFreqUemRellteerntSil Customer continues to get smaller Rental continues to get larger but Rental now has operations that change it from being a data holder to a useful object Our sequence diagram has changed see page 25 statement used to call the movie class to get the price code for each movie Now rental takes care of thaL and statement now calls methods that have names that mean something rather than presenting tons of code whose purpose may not be clear Aprll172003 Unlversltyof Colorado2003 15 Step 6 Remove temp variables statement still has temp variables totalAmount and frequentRentalPoints Both of these values are going to be needed by statement and htmlStatement Lets replace them with query methods little more dif cult because they were calculated within a loop we have to move the loop to the query methods Step 6a replace totalAmount Step 6b replace frequentRentalPoints test after each step April 172003 University of Coloraoo 2003 is Currentclass diagram siaiem n10 gelTatd Chargeli canoiairreqoeninenierpainisll Customer class is now bigger but has two methods that can be shared with the existing statementO method and the planned htmlStatementO method Our sequence has again changed see page 31 because now we have three loops instead of one again performance can be a concern but we should wait until a pro ler tells us so April 172003 University of Colorado 2003 17 Step 7 add htmlStatement We are now ready to add the htmlStatement function a Note I m not going to testthis function but lwill add it so you can see how our refactorings so far have made it easy to add this function I added a file to the step7 directory that prints out the results of calling htmlSta ement you can send the output to a web browser if you want a You can actually improve these two methods using a refactoring called Form Template Method but I will not cover that to ay April 172003 o Universiton Colorado 2003 13 New Requirements It is now anticipated that the store is going to have more than the three initial types of movies a as a result ofthese new classifications renter points and charges will vary with each new movie type a as a result we should probably move the getCharge and getFrequentRenterPoints methods to the Movie class April 172003 University of Colorado 2003 19 Step 8 move methods a Step 8a move getCharge to Movie getCharge needs to know the number of days the movie was rented since this is information that Rental has it needs to be passed a parameter a Step 8b move getFrequentRenterPoints to Movie ditto April 172003 University of Colorado 2003 20 Current class diagram Movie has new m stalemen ll methods nally making e in a Char E ggffgjjgg mpmm 3eralalne ellneaietnmeii the transttion from data holder to object these methods will allow us to handle new I f 1 qFthwiqal xyK inii YPBS 0 mew 5351 y qelFrequenl enterFulntstdays inii April 17 2003 University of Colorado 2003 21 How to handle new Movies Regular Movie New Release Mavie But movies can change type A children s movie when it is rst released is a new release later it becomes a children s movie So this approach won t work Aprll172003 University or Colorado 2003 22 The State pattern to the rescue gelCHargell Regular Price aeronaiaail A movie has a particular state its charge and its renter points depend on that state so we can use e state pattern to han 1 new types of movies for now at least Aprll172003 University or Colorado 2003 23 Step 9 Replace Type Code with StateStrategy We need to get rid of our Type Code eg MovieCHlLDRENS and replace it with a Price object a We first modify Movie to get rid of its priceCode field and replace it with a price object this involves changing the constructor to make use of the setPriceCodeo method before it was setting ipriceCode directly we also have to change getPriceCode and setPn ceCode to access the Price object a We of course need to create Price and its subclasses Aprll172003 University or Colorado 2003 24 Step 10 Move Method Now we need to move the method getCharge to the newly created Price class It s a very simple move we just need to remember to change Movie to delegate its getCharge operation to Price April 17 2003 University of Colorado 2003 25 Step 11 Replace Conditional with Polymorphism Now we move each branch of the switch statement into the appropriate subclass I do this in one move Fowler actually recommends moving one branch at a time and introducing a bug so you can be sure that the subclass s method is the one being invoked After you have done the move change Price s getCharge to an abstract method I Don t forget to test everything still works April 17 2003 University of Colorado 2003 26 Step 12 handle renter points I Now we repeat step 10 and 11 this time applying them to frequent renter points I I combine both steps into one we move the method over to price and use polymorphism to handle the logic note this time we leave a default implementation in Price and have newRelease override that implementation since it is the only class that returns a different value Run the test and everything still works April 17 2003 University of Colorado 2003 27 We re done We ve added new functionality changed data holders to objects and made it very easy to add new types of movies with special charges and frequent rental points The final version of the code is in the after directory compile it and run the test test passed April 17 2003 University of Colorado 2003 28 Final class diagram What s Next SW Now that we have covered design patterns and refactoring we will next look at testdriven design and object gelChargEMuii ml VeiFRPidavs int 1 v gleRPldays my Note not all methods and attributes are shown oriented design heuristics geLFRP is an abbreviation N M F R ofge requenmmmpoms w n se ecall that a heuristic is a rule of thumb an 00 design heuristic is a rule of thumb that See page 51 for m can help us distinguish between bad 00 nal sequence designs and good 00 designs iagmm g i m genetics qeiTaiaiFiequeniRenierPaintsli April 172003 University of Colorado 2003 29 April 172003 University of Colorado 2003 30 1 New i Lecture 20 TestDriven Development Kenneth M Anderson ObjectOriented Analysis and Design CSCI 6448 Spring Semester 2005 e v 2 wwww Credit where Credit is Due So e of the material for this lecture is taken from TestDriven as s eh s m VelopmentquotbyKent eck u omeo thismaherial is 2003 De copyright Addison Wesley Mam 172nn5 a unmrsny mcuinmnn Balldnr2n 5 9 oiwtitoi Goals for this lecture to Introduce the concept of TestDriven Development TDD I Present an example 4 March 17 2005 University of Colorado Boulder 2005 i TestDriven Development 1 The idea is simple a No production code is written except to make a failing test pass I Implication You have to write test cases before you write code e March 17 2005 University of Colorado Boulder 2005 OI Writing Test Cases First I This means that when you first write a test case you may be testing code that does not exist I I l I I l I I l l l l l l I I I l 1 I l l I I l l 0 And since that means the test case will not compile obviously the test case fails amp After you write the skeleton code for the objects referenced in the test case it will now compile but also may not pass 1 So then you write the simplest code that will then make the test case pass fl March 17 2005 University of Colorado Boulder 2005 6 I Consider writing a program to score the game of bowling J You might start with the following test public class TestGame extends TestCase public void testOneThrow Game g new Game g addThrow 5 assertEquals 5 g getScore to When you compile this program it fails because the Game class does not yet exist e March 17 2005 University of Colorado Boulder 2005 Kl il llll Example continued I You would now write the Game class I l l I I l I l l l l l l l I I I l 1 I l l I I l public class Game public void addThrowint pins public int getScore return 0 to The test code now compiles but the test will still fail a In TestDriven Design Beck recommends taking small simple steps 1 So we get the test case to compile before we get it to pass 4 March 17 2005 University of Colorado Boulder 2005 lilil 00 Example continued I Once we confirm that the test still fails we would then write the simplest code to make the test case pass that would be public class Game public void addThrowint pins public int getScore return 5 to The test case now passes e March 17 2005 University of Colorado Boulder 2005 O TDD Life Cycle 3 The life cycle of testdriven development is amp Quickly add a test a Run all tests and see the new one fail Make a simple change amp Run all tests and see them all pass a Refactor to remove duplication to This cycle is followed until you have met your goal note that this cycle simply adds testing to the add functionality refactor loop of refactoring covered in the last two lectures ti March 17 2005 University of Colorado Boulder 2005 L C TDD Life Cycle continued 1 Kent Beck likes to perform TDD within a Testing Framework such as JUnit within such frameworks a failing tests are indicated with a red bar a passing tests are shown with a green bar 1 As such the TDD life cycle is sometimes described as amp red bargreen barrefactor a March 17 2005 University of Colorado Boulder 2005 311 Example Background MultiCurrency Money I Lets design a system that will allow us to perform financial transactions with money that may be in different currencies a eg if we know that the exchange rate from Swiss Francs to US Dollars is 2 to 1 then we can calculate expressions like amp 5USD10CHF 10 USD or amp 5USD10CHF20 CHF 4 March 17 2005 University of Colorado Boulder 2005 L h Starting From Scratch I Lets start developing such an example 1 How do we start a TDD recommends writing a list of things we want to test This list can take any format just keep it simple Example amp 5 10 CHF 10 if rate is 21 amp 5 2 10 e March 17 2005 University of Colorado Boulder 2005 First Test 1 The first test case looks a bit complex lets start with the second 5USD210USD amp First we write a test case public void testMultiplication Dollar five new Dollar5 five times 2 assertEquals 10 five amount ll l l l I I l I l l l l l l l I I l l 1 I l l I I l 4 March 17 2005 University of Colorado Boulder 2005 Discussion on Test Case wwwi public void testMultiplication Dollar five new Dollar 5 five times 2 assertEquals 10 five amount a What benefits does this provide target class plus some of its interface 35 we are designing the interface of the Dollar class by thinking about how we would want to use it amp We have made a testable assertion about the state of that class after we perform a particular sequence of operations March 17 2005 University of Colorado Boulder 2005 5 UI What s Next a We need to update our test list amp The test case revealed some things about Dollar that we will want to clean up amp We are representing the amount as an integer which will make it difficult to represent values like 15 USD how will we handle rounding of factional amounts amp Dollaramount is public violates encapsulation amp What about side effects we first declared our variable as five but after we performed the multiplication it now equals ten 4 March 17 2005 University of Colorado Boulder 2005 L 6 Update Testing List I The New List 5 USD 10 CHF 10 USD 5 2 10 a make amount private Dollar sideeffects amp Money rounding to Now we need to fix the compile errors amp no class Dollar no constructor no method timesO no field amount e March 17 2005 University of Colorado Boulder 2005 L N First version of Dollar Class public class Dollar l l l I I l I l l l l l l l I I I l 1 I l l I I l l public Dollarint amount public void timesint multiplier public int amount I Now our test compiles and fails 4 March 17 2005 University of Colorado Boulder 2005 wwow E18 1 Note we did the simplest thing to make the test compile to now we are going to do the simplest thing to make the test pass to Is this process too slow amp Yes as you get familiar with the TDD life cycle you will gain confidence and make bigger steps a No taking small simple steps avoids mistakes beginning programmers try to code too much before invoking the compiler they then spend the rest of their time debugging or March 17 2005 University of Colorado Boulder 2005 5 lt9 How do we make the test pass 1 Here s one way public void times int multiplier amount 5 2 amp The test now passes we received a green bar I Now we need to refactor to remove duplication But where is the duplication amp Hint its between the Dollar class and the test case ti March 17 2005 University of Colorado Boulder 2005 N O Refactoring I To remove the duplication of the test data and the hardwired code of the times method we think the following 3 We are trying to get a 10 at the end of our test case and we ve been given a 5 in the constructor and a 2 was passed as a parameter to the times method So lets hook things up a March 17 2005 University of Colorado Boulder 2005 h 5 l lamp First version of Dollar Class public class Dollar l l l I I l I l l l l l l l I I l l 1 I l l I I l public Dollarint amount thisamount amount public void timesint multiplier amount amount multiplier public int amount I Now our test compiles and passes and we didn t have to cheat 4 March 17 2005 University of Colorado Boulder 2005 h h One loop complete 1 Before writing the next test case we update our testing list a W amp 5 2 10 I make amount private 5 Dollar sideeffects amp Money rounding a March 17 2005 University of Colorado Boulder 2005 h 60 One more example I Lets address the Dollar SideEffects item and then move on to general lessons to So lets write the next test case When we called the times operation our variable five was pointing at an object whose amount equaled ten not good amp the times operation had a side effect which was to change the value of a previously created value object amp Think about it as much as you might like to you can t change a 5 dollar bill into a 500 dollar bill the 5 dollar bill remains the same throughout multiple financial transactions l l l l l l l l l l l l l l l I l l 1 l l l I I l 4 March 17 2005 University of Colorado Boulder 2005 N h Next test case I The behavior we want is public void testMultiplication Dollar five new Dollar5 Dollar product fivetimes2 assertEquals10 productamount product fivetimes3 assertEquals15 productamount assertEqualsS fiveamount amp Note the last assert is redundant it is implicitly shown to be true by the second assert I decided to make it explicit March 17 2005 University of Colorado Boulder 2005 h n Test fails I The test fails because it won t compile l I l I I l I I l l l l l l I I I l 1 I l l I I l l I We need to change the signature of the times method previously it returned void and now it needs to return Dollar public Dollar timesint multiplier amount amount multiplier return null I The test compiles but still fails as Kent Beck likes to say Progress ti March 17 2005 University of Colorado Boulder 2005 326 I To make the test pass we need to return a new Dollar object whose amount equals the result of the multiplication public Dollar timesint multiplier return new Dollaramount multiplier I Test Passes Cross Dollar Side Effects off the testing list second loop complete there was no need to refactor in this case e March 17 2005 University of Colorado Boulder 2005 h 1 Discussion of the Example 3 There is still a long way to go a only scratched the surface amp But we saw the life cycle performed twice amp we saw the advantage of writing tests first amp we saw the advantage of keeping things simple we saw the advantage of keeping a testing list to keep track of our progress I Plus as we write new code we will know if we are breaking things because our old test cases will fail if we do if the old tests stay green we can proceed with confidence 4 March 17 2005 University of Colorado Boulder 2005 h C Principles of TDD 30 Testing List keep a record of where you want to go amp Beck keeps two lists one for his current coding session and one for later You won t necessarily finish everything in one go 0 Test First Write tests before code because you probably won t do it after a Writing test cases gets you thinking about the design of your implementation does this code structure make sense what should the signature of this method be e March 17 2005 University of Colorado Boulder 2005 h D l Principles of TDD continued I Assert First a How do you write a test case I I l I I l I I l l l l l l I I I l 1 I l l I I l l amp By writing its assertions first Suppose you are writing a clientserver system and you want to test an interaction between the server and the client amp Suppose that for each transaction some string has to have been read from the server and that the socket used to talk to the server should be closed after the transaction Lets write the test case ti March 17 2005 University of Colorado Boulder 2005 00 CD Assert First public void testCompleteTransaction assertTruereaderisClosed assertEquals abc replycontents I Now write the code that will make these asserts possible or March 17 2005 University of Colorado Boulder 2005 00 5 amp Assert First continued public void testCompleteTransaction Server writer ServerdefaultPort abc Socket reader Socket localhostquot defaultPort Buffer reply readercontents assertTrue reader isClosed assertEquals abcquot reply contents I Now you have a test case that can drive development to if you don t like the interface above for server and socket then write a different test case amp or refactor the test case after you get the above test to pass 4 March 17 2005 University of Colorado Boulder 2005 00 h Principles of TDD continued I Evident Data 1 How do you represent the intent of your test data Even in test cases we d like to avoid magic numbers consider this rewrite of our second times test case public void testMultiplication Dollar five new Dollar5 Dollar product fivetimes2 assertEquals5 2 productamount product fivetimes3 assertEquals5 3 productamount to Replace the magic numbers with expressions ex March 172005 University of Colorado Boulder 2005 Lblr to TestDriven Design is a mini software development life cycle that helps to organize coding sessions and make them more productive a Write a failing test case Make the simplest change to make it pass a Refactor to remove duplication amp Repeat 4 March 17 2005 University of Colorado Boulder 2005 LL alr Re ec ons I TestDriven Design builds on the practices of Agile Design Methods If you decide to adopt it not only do you write code only to make failing tests pass but you also get amp an easy way to integrate refactoring into your daily coding practices amp an easy way to introduce integration testingbuilding your system every day into your work environment I because you need to run all your tests to make sure that your new code didn t break anything this has the side effect of making refactoring safe amp courage to try new things such as unfamiliar design pattern because now you have a safety net March 17 2005 University of Colorado Boulder 2005 Goals for this Lecture 39 Introduce Lecture 13 Interfaces and Objects Interfaces Objects 39 Examine their associated UML Notations Kenneth M Anderson Object Oriented Analysis and Design CSCI 6448 Spring Semester 2001 February 27 2001 Kenneth M Anderson 2001 Interfaces UML Notation 39 An interface is a collection of operations 39 The most simple notation for an interface is not data that specifies a particular service a labeled circle Of a Class or a component Interface names can be grouped using For instance lists queues stacks and trees packages typically provide an Iterator interface that allows other classes to cycle through their Iterator elements Java Collection Iterator February 27 2001 Kenneth M Anderson 2001 3 February 27 2001 Kenneth M Anderson 2001 UML Notation 39 However a full class diagram can be used to specify the particular operations associated with an interface interface Iterator 4 No attributes allowed init next more February 27 2001 Kenneth M Anderson 2001 5 February 27 2001 How interfaces are used You cannot instantiate an instance of an interface instead other classes and thus their objects choose to implement certain interfaces 7 An interface can act as a type so you can declare variables that have for instance the Iterator type 7 This allows you to point at a class who implements the Iterator interface without knowing or caring about what its actual type is Kenneth M Anderson 2001 6 UML Notation To indicate that a class implements a particular interface use the lollipop notation This is also called realization o Iterator The lollipop February 27 2001 Kenneth M Anderson 2001 7 February 27 2001 UML Notation continued When drawing an interface using a class diagram realization is shown using the following notation lt t f lt1n er ace The fact that Iterator reahzatlon has initO lt quotquot quot two notations nexto 1s 1n my opmlon unfortunate more Kenneth M Anderson 2001 8 Roles 39 A class can implement more than one interface each interface represents a role that a class can play we saw how roles can be specified for associations back in lecture 11 February 27 2001 Kenneth M Anderson 2001 Returning to Lecture 12 In lecture 12 we deferred two advanced association notations interface specifiers interface realization We have already covered interface realization February 27 2001 Kenneth M Anderson 2001 Interface Specifiers 39 In an association a role name can specify the specific interface that it is presenting to the class on the other side of the association worker Employee supervisor Manager February 27 2001 Kenneth M Anderson 2001 Links 39 An association specifies a relationship between two classes A link is an instance of an association student adviser Ken Person Susanne Person adv1sor student February 27 2001 Kenneth M Anderson 2001 Objects 39 Objects are instances of classes an object can be named or unnamed A named object An unnamed obj ect Ken s Print 5 ueue 5 meme February 27 2001 Kenneth M Anderson 2001 13 Multiobjects 39 If you need to model a collection of anonymous objects such as a stack or queue you can use the multiobject notation This represents the collection object and all of its individual instances February 27 2001 Kenneth M Anderson 2001 14 Orphan Instances In some situations you may need to model an object whose type is unknown This can occur in practice when dynamically loading an object into memory Use the orphan notation to indicate such an ObJeCt If you later discover the type of an orphan instance you can transform it to a named instance using the become stereotype not yet covered February 27 2001 Kenneth M Anderson 2001 15 Active Objects 39 Finally you can indicate that an object has its own flow of control e g it s a Thread object using the following notation n noti er February 27 2001 Kenneth M Anderson 2001 16
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'