Software Design CSE 335
Popular in Course
Popular in Computer Science and Engineering
This 193 page Class Notes was uploaded by Donnell Kertzmann on Saturday September 19, 2015. The Class Notes belongs to CSE 335 at Michigan State University taught by Staff in Fall. Since its upload, it has received 15 views. For similar materials see /class/207422/cse-335-michigan-state-university in Computer Science and Engineering at Michigan State University.
Reviews for Software 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: 09/19/15
Analytical modeling of software Lecture 1 Alloy a language for representing pure abstractions Before we meet again 7 Read Jackson cnapters i and 2 7 Read No SilverBullet paper 7 Download and instaii Alloy analyzer version 4 on your home PC and playvvith the examples c5522 SoMma 0mg K mvawalt Analytical modeling notation Working definition Design notation with a formal syntax semantics and whose features were chosen to enable automated analysis ofmodels written in the notation Implies means for executing or automatically verifying roperties o a model What good are these 7 Provide sirnpie a o precise rneans forexpressing pure abstractions wh cares7 See Brooks paper rovide rnassive pang rortne buck relative to rnore declarative iess automatable notations n 0 ext 25 SoMma 0mg K mvawalt Why model a design I conclude there are two ways ofconstructing a sottware design One way is to make it so simple there are obviously no de ciencies and the other way is to make it so complicated that there are no obvious de cienciesquot Turiy Hoare rroring Award Lecture iBEEI Plan to throw one away you will anyhowquot F P Brooks c5522 SoMma 0mg K mvawalt Imperative vs declarative anything can happen The more you add the less happens Good for partial O description Goodforincremental Y Y modeling nothing can happen ext 25 SoMma 0mg K mvawalt The Alloy analyzer Alloy installed on Adriatic so linuxlbinalloy models in so linuxlalloymodels Or download to your home machine Alloy Choose Alloy 4quot double click alloyjar or execute java jar alloyjarat the command line c5522 SoMma 0mg K mvawalt The Alloy language Inspired by Z notation but with fundamental concessions made to support analysis and several modeling idioms Eg only rstorder relations No builtin distinction between scalars and sets a few others Has an object dented look and feel but also provides support for relational modeling No primitive datatypes eg integers ext 25 SoMma 0mg K mvawalt Consider an email address book As a running example we will begin to model an address book in an e 39e t Address books should map aliases eg joe mary to email addresses to simplify messa e composition Eventually we want to model support for group aliases eg cse814students c5522 SoMma 0mg K mmwan First model of address book sig Name Addr sig Book addr Name 7gt lone Addr This model comprises three sets Name Addr and Book and one relation addr ext 25 SoMma 0mg K mmwan First model one line at a time sig Name Addr This line introduces two sets Name and Addr opaque and disjoint Names suggest their meaning but model says nothing about the structure ofobjects in these sets Question Why aren t we saying more eg elements of Name are strings or that elements of Addr are records with account domain etc c5522 SoMma 0mg K mmwan Virtuenecessity of abstraction Answers Intemal representation ofname resp address objects is irrelevant for the purposes of this model Analytical model must abstract in every way possible so as to avoid state explosion during analysis How a designer chooses to abstract affects the contentscomplexity of the resulting model Tip Clearly understand your reasons for modeling before you write a line of Alloy ext 25 SoMma 0mg K mmwan Signature declaration A signature declaration s a set of objects may also declare relations may or may not de ne a new type Top level signatures introduce disjoint sets First line of our declares that Name objects are distinct from Address objects ie sets do not erlap In fact Name and Address are different types more later c5522 SoMma 0mg K mmwan First model one line at a time sig Book addr Name 7gt lone Addr l Introduces new set Book and relation addr A relation is declared as a field in a signature declaration sig Af e introduces relation fwhose domain is A and range given by the expression e ext 25 SoMma 0mg K mmwan Relations in models The addr relation is actually a three very mapping from Books to Names to Addresses Relation contains the tuple b n a When in book b name n maps to address a The keyword lone indicates a multiplicity constraint on the Name gt Address mappings ie each name maps to at most one address other multiplicities include one exactly one some at least one and set zero or more Default multiplicity is one c5522 swim 0mg K 3mm Question What would be the implications of declaring addr as follows sig Book addr Name gt Add ext 25 swim 0mg K 3mm Models and instances An Alloy model implicitly defines a very large inifinite space of instances An instance is just a valuation for each of the signatures and relations declared in the model Each instance may be either finite or infinite Each instance must respect any constraints that are declared in the model eg the lone multiplicity constraint on addr c5522 swim 0mg K 3mm The virtues of finite instances Key idea Often useful to generate finite instances in order to validate a model Example Name joe mary A0 Book B0 addr BO joe A0 BO mary A0 Instances often illustrate pathological cases and boundary condi ions Eg Name Q Addr Q Book Q addr Q ext 25 swim 0mg K 3mm Generating instances to validate Pathological cases and boundary conditions typically dif cult for humans to reason about but critical to resolve before implementation The Alloy analyzer allows one to easily generate instances of a model subject to a variety of constraints Technique Define a predicate that makes some assertion about the model and then issue a command to find an instance of the predicate c5522 swim 0mg K 3mm Our first predicate pred show H defines a new predicate show with no parameters and an empty body Parameters used to name elements of sets for use in constraints which appear in the body An empty body means there are no constraints which is equivalent to the predicate true ext 25 swim 0mg K 3mm Our first command run show for 3 but 1 Book asks the analyzerto find an instance of the model that satisfies the predicate show using a scope that bounds the search for instances Scope in this case bounds search to include signatures with at most 3 objects except forthe signature Book which is limited to one object c5522 SoMma 0mg K mmwalt A more interesting predicate pred show b Book baddr gt 1 This one uses a parameter b and imposes a constraint that the address mapping of b ie baddr must contain more than one tuple operator gets the cardinality of a set a relation is just a set of tuples ext 25 SoMma 0mg K mmwalt Another predicate pred show b Book baddr gt 1 some 11 Name l n baddr gt 1 Question What does the second constraint say in English Question What would you expect the analyzer to report in this case c5522 SoMma 0mg K mmwalt No instances found Sometimes the analyzer will report that no instances of a predicate were ound This means the predicate is inconsistent with the model at least in the given scope Question How should we interpret such a result 7 Does it rnean there l5 a bug in our rnoden 7 Could it everbe the case that we get no instances found when the model l5 correct 7 Does it prove a property of the model ext 25 SoMma 0mg K mmwalt One more predicate pred show b Book baddr gt 1 Namebaddr gt 1 Question What does this one say in English Question What do you expect the analyzer to return in this case c5522 SoMma 0mg K mmwalt Flexibility of the dot operator Previous examples illustrate the power of the dotjoin operator For now think of dotjoin as playing the role of eld access as in a record functionalrelational composition functionalrelational projection This one operator can be used in so many contexts makes modeling much easierthan having a different operator for each context ext 25 SoMma 0mg K mmwalt Software Engineering CSE 335 Spring 2006 00 design Concurrency and Distribution Stephen Wagner Michigan State University Definitions 0 Process Program in execution Created and managed by the operating system Multiple processes execute in separate address spaces 0 Thread Lightweight process Created and run within a process depends on OS Multiple threads execute in shared address space 0 Distributed applications with graphical user interfaces tend to be multithreaded Distributed application 0 Defn Application comprising multiple processes usually running on different machines over a network 0 Client server systems Server is a process accessed by many client processes 0 Examples CSE HTTP server accessed by any number of browser clients running anywhere in the world X server OO and distributed applications 00 concepts contribute to concurrentdistributed applications development Concurrencysynchronization model Threads enable the design of timemultiplexed active objects Monitors protect concurrent access to passive objects Separation of interface and implementation classes Basis for pluggable39 component technologies JavaBeans EJB ODBC Design patterns Proxy pattern simplifies interprocess communication Basis for distributed object middleware Multithreaded programming C I provides no language features for thread programming Threads are supported directly in Java and C In C threads and thread operations are provided by standard libraries In Unix standard threads library is pthreads Short for POSIX threads Include files usrincludepthreadh Link library libpthreadsa Active Object new definition 0 Defn An object that runs in its own thread 0 Multithreaded applications comprise two or more active objects that manipulate one or more passive objects in shared memory 0 In most objectoriented languages you design active objects and then run them from within separate thread objects Design Pattern for Active Objects class ActiveObjectInterface public virtual bool activate 0 virtual void terminate O class Thread public int startActiveObjectInterface protected ActiveObjectInterface activeObject pthreadt myThread static void startMyThreadvoid Design pattern active objects int ThreadstartActiveObjectInterface ao activeObjectao return pthreadcreateampmyThread 0 startMyThread void ao void Thread startMyThreadvoid vptr ActiveObjectInterface aostaticcastltActive0bjectInterface 3 while aogtactivate return 0 Exercise Write a short program with two threads one of which continually emits HELLOl and the other of which continually emits GOODBYEl Answer class Emitter public ActiveObjectInterface public Emitterconst string amp s words bool activate cout ltlt word ltlt endl return true protected string word int mainvoid Thread t Emitter hello Hello goodbye Goodbye tstartamphello while goodbyeactivate return 0 Question Always a main thread that you need not create explicitly Question What would happen if we removed the statement goodbyeactivate Concurrent access to shared data 0 Problem Multiple active objects might access the same passive object at the same time Generally OK if the active objects are only reading data from the passive objects But if one more active objects is modifying the data members of the shared object then we get anomalies 0 Example two active objects trying to pull an element off of a shared queue 0 To prevent these dataaccess anomalies requires synchronizing the active objects Example class SharedQueue public bool pull string amps bool retval qempty if retval s qback qpopO return retval protected queueltstringgt q pull empty pull back Thread synchronization 0 Definitions A critical section is a region of code in which at most one thread should be allowed to execute concurrently A muteX lock is a facility that is used to synchronize threads gtllt One and only one thread can own a lock gtllt Thread gets to own a lock by acquiring it gtllt A thread will block if it attempts to acquire a lock owned by another thread 0 Design tip Whenever you write multithreaded programs you must identify and protect critical sections in your code Use of mutex locks pthreadmutext type use for declare a lock pthreadmutexinit initializes a lock pthreadmutexdestroy destroys a lock pthreadmutexlock acquires a lock blocking if lock owned by another thread pthreadmutexunlock releases a lock so that other threads may acquire it class SharedQueue public SharedQueue pthreadmutexinitamplock SharedQueueO pthreadmutexdestroyamplock bool pull string amps pthreadmutexlockamplock bool retval qempty if retval s qback qpop pthreadmutexunlockamplock return retval protected queueltstringgt q pthreadmuteXt lock Monitor synchronization o Defn A Monitor is an object whose methods may not be executed by multiple threads concurrently 0 Example Let 0 be a monitor that provides the operation void foo Suppose threads T1 and T2 invoke ofoo One thread eg T1 will execute foo in its entirety while the other thread waits 0 Most 00 languages use monitor synchronization The monitorobject pattern 0 Standard pattern for promoting an arbitrary C l class into a monitor class 0 Let C by the original class and M be the new monitor class M should inherit publicly from C M should contain a protected data member call it look of type pthreadmutext For each public method m of C M should override that method with one that acquires lock invokes Cm and then releases lock Synthetic 00 Design Concepts amp Reuse Lecture 11 More on the mediator pattern Topics Synthesizing collaborations Mediator pattern Modeling interactions with sequence diagrams Recall Tip Calculator Amount of bill Ilium Tip levels r 12 W15 A l195 Amount of gratuity FloatBoxes CheckButtons CheckButtonButtonListener Collaboration 39 39 n39 39n h h quot CheckButton ButtonListener 4 ListensTo cb CheckButton gt bl ButtonListener 4 Implementation of CBBL Collaboration class ButtonListener public virtual void buttonPressedconst char O class CheckButton public FlCheckButton public CheckButton int x int y int w int h const char 1 void setValueint n FlCheckButtonvaluen unsigned getValue return FlCheckButtonvalue void registerListenerButtonListener t targett protected void pressEvent friend void buttonCallback FlWidget ButtonListener target Implementation of CBBL Cont39d void buttonCallbackFlWidget w CheckButton b dynamiccastltCheckButtongtw assertb O bgtpressEvent CheckButtonCheckButton int x int y int w int h const char label FlCheckButtonx y w h label callbackbuttonCallback show target0 void CheckButtonpressEvent if target targetgtbuttonPressedlabel FIoatBox FloatListener Collaboration 39 39 39 I 39 h h 39 a u v v 4 v 4 a Implementation of FBFL Collaboration class FloatListener public virtual void announceNewValueconst char float O class FloatBox public FlFloatInput public FloatBox unsigned unsigned unsigned unsigned const char float getValue return unsigned atofvalue void setValuefloat f void registerListenerFloatListener t targett private void userEvent friend void floatboxCallback FlWidget FloatListener target Implementation of FBFL Cont39d void floatboxCallback FlWidget w FloatBox t dynamiccastltFloatBoxgtw assertt O tgtuserEvent void FloatBoxsetValuefloat f ostringstream v v ltlt f valuevstrcstr void FloatBoxuserEvent if target targetgtannounceNewValuelabelatofvalue Implementation of FBFL Cont39d FloatBoxFloatBoxunsigned x unsigned y unsigned w unsigned h const char n FlFloatInputx y w h n valuequot0quot when FLWHENENTE RKEYALWAYS colorFLGRAY textsizetextsize 2 callbackfloatboxCallback show Recall Mediator Representsencapsulates the protocol of interactions among a set of other objects called colleagues Colleagues send messages to mediator instead of other colleagues Mediator reacts to received messages by sending messages to other colleagues as per the protocol Synthesize Collaboration with Mediator 1 Align Roles fb Cb med 4 ListensTo I I FloatBox 2 l FIoatLIstener I 1 ListensTo CheckButton 3 ButtonListener I 1 Synthesize Collaboration with Mediator 2 Group Roles fb cb rr1egl 4 ListensTo I FloatBox 2 l FIoatLIstener I I 1 Listen To E CheckButton 3 ButtonListener I 1 v i I l 39 TipCaIc Collaboration u I 39 39 n39 39n v n u h v TipCalc 2 a 4 ListensTo fb FloatBox med Director 2 1 1 I 4 ListensTo cb CheckButton l3 Synthesized Mediator Implementation class Director public ButtonListener public FloatListener public Director virtual Director virtual void buttonPressedconst char virtual void announceNewValueconst char float private FloatBox amount CheckButton ten CheckButton twelve CheckButton fifteen FloatBox gratuity Synthesized Mediator Implementation const const const const const string string string string string AMOUNTLABEL quotAmountquot TENLABEL quot10quot TWELVELABEL quot12quot FIFTEENLABEL quot15quot GRATUITYLABEL quotGratuityquot DirectorDirector amount ten twelve fifteen gratuity new new new new new FloatBox0 CheckButton0 CheckButton0 CheckButton0 FloatBox0 o 200 25 200 50 200 75 200 100 200 25 25 25 25 25 fifteen gtvalue1 Set the default tip amount gtregisterListenerthis ten gtregisterListenerthis twelve gtregisterListenerthis fifteen gtregisterListenerthis gratuity gtregisterListenerthis AMOUNTLABELcstr TENLABELcstr TWELVELABELcstr FIFTEENLABELcstr GRATUITYLABEL cstr Synthesized Mediator Implementation DirectorDirector delete amount delete ten delete twelve delete fifteen delete gratuity Synthesized Mediator Implementation void DirectorbuttonPressedconst char label if TENLABEL label twelvegtsetValueO fifteengtsetValueO gratuitygtsetValueOlamountgtgetValue else if TWELVELABEL label tengtsetValueO fifteengtsetValueO gratuitygtsetValueO12amountgtgetValue else if FIFTEENLABEL label tengtsetValueO twelvegtsetValueO gratuitygtsetValueO15amountgtgetValue Synthesized Mediator Implementation void DirectorannounceNewValueconst char label float value if ten gtgetValue gratuitygtsetValueOlamountgtgetValue else if twelvegtgetValue gratuitygtsetValueO12amountgtgetValue else if fifteengtgetValue gratuitygtsetValueO15amountgtgetValue To Complete the Program int mainint char FlWindow mycontainer200 125 0 Director mydirector mycontainerend mycontainershow return Flrun Question Draw a sequence diagram that shows what happens when the percentage is 10 and the user selects 15 IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 l V pre ssEventO IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 E t 39 prefs ven buttonPresedquot15J IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 E t 39 prefs ven buttonPresedquot15J setVEalue0 value O e gt IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 re sE ent p V O I 39 buttonPreSsedquot15 setVEalue0 i V I 5 setValLieO L17 u IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 re sE ent p V O I 39 buttonPreSsedquot15 setVEalue0 E V 5 I 5 1 39 setValLieO LIT quotE up getValue IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 re sE ent p V O I 39 buttonPreSsedquot15 setVEalue0 E V 5 I 5 1 39 setValLieO LIT quotE up getValue IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 re sE ent p V O I 39 buttonPreSsedquot15 setVEalue0 E V 5 I 5 1 39 setValLieO LIT quotE up getValue IamountI I ten I I twelve I I fifteen I IgratuityI I mydirI val 10 value 1 value 0 value 0val100 I value 1 re sE ent p V O I 39 buttonPreSsedquot15 setVEalue0 E V 5 I 5 1 39 setValLieO LIT quotE up getValue Activity Draw a sequence diagram that shows what happens when the bill amount changes from 1000 to 2000 tip still at 15 Software Design CSE 335 Spring 2006 Static Data Modeling Stephen Wagner Michigan State University Some more UML notation o Qualifiers and associations 0 We often identify which attribute is used to partition the set of objects associated with an object across an association account 7 Person Generalization o Defn relationship between class and one or more refined versions of it 0 Benefits Powerful abstraction for sharing similarities among classes while preserving their differences Inheritance is helpful as a vehicle for reusing code Benefits during static modeling gtllt Consolidation of common properties gtllt Identification of discriminators that suggest how objects of a given class va ry Exercise An airline39s flight operations has employees that are either pilots or flight attendants Pilots can be either in the left seat which designates they are in command or in the right seat which designates them as copilot FAA rules require a pilot and copilot on each flight Similarly there is a lead flight attendant who manages the other flight attendants if any Flights operate on a scheduled basis as usual and a flight might be serviced by multiple aircraft due to size limitations and availability What would the class diagram that models the flight operation look like Generalization versus roles 0 Common mistake confusing a derived class with a role in an association 0 Examples PIC and copilot are two roles that might be played by the same Pilot on different flights The same FlightAttendant may be the lead on one flight but not on another Separate classes for Pilot and FlightAttendant make sense because these objects do not switch roles Other Examples 0 If we are not careful the only way to change a role is to destroy the object and then recreate it o I m sorry the only way the computer can change your status is to terminate you and then rehire you Employee A Analysis 0 During analysis associations tend to be more important than generalizations Generalization consolidates shared information but does not change the instances of a model Associations add information to the model Exercise For the airline data model draw an instance diagram of a flight with a pilot copilot and two flight attendants one of whom is the head attendant Overuse of Generalization A VideoRecording AudioRecording MusicVideo l JazzRecording BluesRecording l RockRecording ClassicalRecording Answer 0 Might make sense to distinguish between AudioRecording and VideoRecording o What attributes or associations could be consolidated through the specialization of AudioRecording o Probably better to use an attribute Alternate Solution 0 If there is very little variation in the derived classes this design models the same data and is more extensible hasCategory Recordin Recordin Cate or g g g y title description t t M ls subcategory 0 Point if derived classes do not differ substantially consider modeling another way Specialization and Discriminators o Specialization usually occurs along some characteristic eg behavior A Simple l Toggle l Radio I 0 Choosing characteristics can be hard 0 Derived classes or disjoint or but can have multiple dimensions and Example Multiple Characteristics Car Land A b tgtGasoline 1r oa sea Rocket Sailboat Alr Wind Stagecoach Space Animal Rickshaw Bogs Human SpaceShuttle Useful to document these characteristics with a discriminator Software Design CSE 335 Spring 2006 00 design Control and System Architecture Stephen Wagner Michigan State University Software control 0 Styles of control in a program 1 Procedural Control resides in application code Requests for resources block until resource available 2 Eventdriven Control resides in a central dispatcher Application code does not explicitly request resources Application methods are called back to handle external events 3 Concurrent Multiple simultaneous threads of control New problems to contend with synchronization mutual exclusion Active vs passive objects Eventdriven control Library Code Central Event Queue Dispatcher Application Code Objectl Objectg ObjectN Scrollbar callback scenario Dispatch GUI userEvent announceNewValue retrieve lt JJ retrieve lt JJ Notes on the Dispatch object o The dispatch object is not created by our application code We got it when we linked in the fltk library Function main cedes control to Dispatch once main has created and linked the application objects Control ceded by return Flrun Dispatch is a loop that services device events until all windows have been destroyed Dispatch is always active Exercise Suppose we want to replace the FileManager with a StreamManager which continuously reads lines to display from a service over the network This manager must notify scrobar when a new line is read from the network StreamManager Interaction D 6h EM m1 announceNewData announceNewValueQ retrieve lt i retrieve Observations o Locus of control Resides in object that is active throughout interaction So far our designs have involved single locus of control 0 Streammanager sequence diagram involves two loci of control One for The GUI One for the stream manager As yet we have not discussed a way to build applications with multiple loci of control 0 How can we simulate multiple loci of control Solution Pg Em DEM servi ceNetwork announceNewData announceNewValue retrieve lt 1 retrieve Modifications to main int main void StreamManager new StreamManager New event loop while Flcheck Flwaitinterval smgtserviceNetwork return 0 How to simulate additional loci of control New concept Active objects StreamManager is an example of an active object Appears to be running in its own locus of control distinct from the main application Often needed to monitor asynchronous events eg user input mouse motion network traffic Design complexity increases when application involves multiple active objects How can this complexity be hidden Exercise Develop a class called GUIManager that simplifies extending the event loop to cede time to active objects What other classes will be helpful ActiveObjectlnterface class ActiveObjectlnterface public virtual bool activate 0 virtual void terminate O Class GUIManager class GUIManager public GUIManager void setTimeoutIntervalfloat interval void registerActiveObjectActiveObjectInterface bool activate void terminate protected float timeoutInterval vectorltActive0bjectInterface gt activeObjects Questions What happens if the user clicks on scrollbar during the serviceNetwork transaction What happens to the responsiveness of the user interface if the call to serviceNetwork blocks for some perceivable amount of time How might we fix this Control implementation strategies Eventdriven sequential Central dispatcher invokes registered objects to service asynchronous events Timesliced multiplexing o Scheduler activates each active object in sequence and periodically preempts one actor to schedule another 0 Generally requires operating system support 0 Thread Lightweight process essentially a sequence of code that can be multiplexed with other sequences of code within a sequential process Multiprocess Active objects associated with operating system processes Multiprocess l mainzActor Actor Actor Event Driven l mainzActor act ivate Actor Timeslice multiplexing Actor Actor Design Method After identifying the major interactions in your system 0 Identify the active objects 0 Choose an implementation strategy for associating a locus of control with each object Note the choice of strategy may introduce new roles and collaborations into the problem Eg if we want each active object to be a concurrent process and we want them to be distributed over the network then sending a message is no longerjust a method invocation 0 Use rolecollaboration synthesis techniques we have already studied to develop concrete classes and configuration code Software architecture and larger system design issues Lecture 1 Simulating concurrency Topics Highlevel software architecture and its impact on the design of classes roles and collaborations Focus Concurrency Outline of course topics Foundational OO concepts Synthetic concepts Program families program fragments and abstract classes Separation of concepts Separatingencapsulating crosscutting operations Visitors Mixin classes Reusable strategies and objectoriented frameworks Reusable collaborations Software architecture and larger design issues Outline of course topics Software architecture and larger design issues Strategic design decisions that influence a host of smaller more tactical design decisions Example policy for persistence of data in longrunning system Example allocating functionality to a single centralized system vs distributing functionality among a collection of communicating hosts Often involve a major capital investment Source of both risk and opportunity Require lots of a priori modeling and analysis Focus Design issues related to concurrent and distributed systems Strategic design decisions Defn Highlevel design decisions that influence the form of much of the final code Have dramatic impact on performance extensiblity reusability andor maintainablity of the final system Should be made very deliberately Analogy Good design yields software assets Strategic design decisions are major capital investments System design Defn Highlevel strategy for solving an information flow problem and building a solution Blahaamp Rumbaugh Includes decisions about organization of functionality Allocation of functions to hardware software and people Other major policy decisions that are prior to technical design Assumes and builds upon a thorough requirements analysis Example systemdesign decisions Choose system performance constraints Organize system into subsystems Identify concurrency and choose a strategy for implementing concurrent control Choose a policymechanisms for managing persistent data Make a reuse plan Etc Example systemdesign decisions Identify concurrency and choose a strategy for implementing concurrent control Example concern Concurrency Many modern desktop applications perform multiple tasks concurrently Lots of different ways to implement concurrency in an application Each approach comes with its own set of costs and benefits More important Each approach can have a dramatic impact on how one designs every class in the system Recall design of document browser sd design3 I sb lvp lvpm lldm userEvent 0 gt J announceNewValueX I r update 8 3 retrieve0 3 getLineX m I g 71 a Z 1 O C 3 3 t39 3 g rer39eVe gt getLineXn I 1 nCass Activity Suppose we want to replace the DocManager with a StreamManager which continuously reads lines to display from a service over the network This manager must notify scrollbar and viewport when a newline is read from network Task Draw a sequence diagram that depicts what happens when the stream manager reads a newline from the network Demo the application Start of solution sketch sd stream lsb lvp lvpm llsm serviceNetwork Finished solution sketch sd stream update getLineX a 2 E a Z a o C 3 o C C as Question Who generates this call to serviceNetwork Where would we place it in our application code Design of function main int main void StreamManager sm new StreamManager MyScrollBar sb new MyScrollBar MyViewPort vp new MyViewPort MyViewPortModel vpm newMyViewPortModel sbgtregisterListenervpm sbgtregisterListenervp vpgtsetModelvpm vpmgtsetModelsm sm gtregisterListenersb t Fl 0 Question Will this cause re urn 3 run serVIceNetworkO to be invoked periodically By Whom At end of configuration phase Application listener model Operating system E Event Queue mouse Entering collaboration phase Application listener model I IT mam t gt FL3939run 1 Operating system E Event Queue mouse Step 11 App checks event queue Application listener model I gt x mam I fLrun 1 Operating system gt E Step 12 App blocks on empty queue Application listener model Operating system 2 Event Queue mouse User then moves scrollbar handle Application listener model Operating system 39 lt E Step 13 application wakes when event arrives Application listener model l I gt x K 27am I fLrun 1 Operating gt E system g Event Queue Step 14 app pulls event off queue Application listener model I gt x mam I fLrun 1 Operating system gt E Step 21 app dispatches event to sb Application listener model I p pressEventO I mam t gt FL3939run I Operating system E Event Queue mouse Step 22 sb notifies its isteners Application listener model I p pressEventO I main t gt FL3939run I Operating system E Event Queue mouse Step 2k dm is queried for last time Application listener model I p pressEventO I main t gt FL3939run I Operating system E Event Queue mouse Step 2k1 dm query returns Application listener model I p pressEventO I main t gt FL3939run 1 Operating system E Event Queue mouse Step 2kj listenerannounceNewValue returns Application listener model I p pressEventO I mam t gt FL3939run I Operating system E Event Queue mouse Step 31 App checks event queue Application listener model I gt x mam I fLrun 1 Operating system gt E Step 32 App blocks on empty queue Application listener model Operating system 2 Event Queue mouse Observations Thread of control Single path of execution through program Thus far our designs have involved single thread of control Stream browser involves two threads of control One for the GUI One for the stream manager As yet we know of no way to build applications with multiple threads of control Question How could we modify our design to simulate multiple threads of control Modifications to main int mainint char StreamManager sm new StreamManager New event loop while Flcheck Fl waitinterval Note Replaces sm gtserviceNetwork can to Frun return 0 Strategy Application simulates concurrency by having a master loop which periodically cedes control to concurrent activities Each activity must be designed to be performed via multiple invocations each of which performs only a small part of the overall task must never invoke an operation that could block for any perceivable amount of time Question How would we have to modify our program to simulate additional threads of control Example What if there were two stream managers Software control and active objects Software control Styles of control in a program 1 Procedural Control resides in application code Requests for resources block until resource available Eventdriven Control resides in a central dispatcher Application code does not explicitly requests resources Rather application methods are called back to handle external events Examples mouse clicks key presses network traffic etc Concurrent Multiple simultaneous threads of control New problems to contend with synchronization Active vs passive objects Software control strategy Major design decision that affects the design of lots of individual classes in system New concept Active objects StreamManager example of an active object Appears to have its own thread of control distinct from that of the main application Often needed to monitor asynchronous events Examples user input mouse motion network traffic Note Design complexity increases when application involves multiple active objects Example need to explicitly design dispatcher Exercise Develop a class called GUIManager that simplifies extending the dispatch loop to cede control to active objects Invent an interface class that all active objects must implement Active objects register with the Dispatcher an instance of GUIManager to request periodic control ActiveObjectlnterface class ActiveObjectlnterface public virtual int activate O The activate operation is invoked to cede a small quantum of control to the object that implements this interface Return value integer allows active object to return an error code to the dispatcher Class GUIManager class GUIManager public GUIManager void setTimeoutInterval float interval void registerActiveObject ActiveObjectInterface int run private float timeoutInterval vectorltActiveObjectInterfacegt listeners Class GUIManager lt31ass GUIManager Observer listener pattern public GUIManager int run private float vectorltActiveObjectInterfacegt listeners Class GUIManager Cede quanta of control to each active object int GUIManagerrun while Flcheck FlwaittimeoutInterval for unsigned i O i lt listenerssize i listenersigtactivate return 0 Application of new collaboration class MyStreamManager public ActiveObjectInterface public StreamManager public int activate return StreamManagerserviceNetwork int mainint char GUIManager dispatcher MyStreamManager sm dispatcherregisterActiveObjectampsm return dispatcherrun Questions What happens if the user clicks on scrollbar during the serviceNetwork transaction What happens to the responsiveness of the user interface if the call to activate blocks for some perceivable amount of time How might we fix this Control implementation strategies Eventdriven sequential Central dispatcher invokes registered objects to service asynchronous events Timesliced multiplexing Scheduler activates each active object in sequence and periodically preempts one actor to schedule another Generally requires operatingsystem support 08 Thread Lightweight process essentially a unit of time sliced multiplexing within a sequential process Multiprocess Active objects associated with operating system processes Software Engineering CSE 335 Spring 2006 Objectoriented programming Rolebased design Stephen Wagner Michigan State University Terminology 0 Collaboration pattern of message exchange among multiple objects to achieve some goal or purpose Terminology Collaboration pattern of message exchange among multiple objects to achieve some goal or purpose Role that subset of an object39s characteristics needed to fulfill its responsibilities in a collaboration We would like to design reusable collaborations Key is to model collaborations with abstract roes Concrete to Abstract Concrete the print button the document receiving a message from the button the print button and document collaboration Abstraction the Button class the abstract ButtonListener role the ButtonButtonListener collaboration press event printbuttonzButtonl A Collaboration buttonPressed l leMgrzMyDocMgr l printDocument Collaboration with Abstract Roles press event Button I targetButtonL139stener l buttonPressed Another Application A scroabe viewport that displays the contents of a DocManager There are three objects a Scrollbar a Viewport gtllt keeps track of the first line to be displayed gtllt has an update function that retrieves lines from its model a DocManager What happens when we move the scroll bar What behavior can be abstracted Another Collaboration vszieWPort l leMgrzMyDocMgr l update retrieve dOCSiZeo docLine lt retrieve dOCSiZeo J docLine lt user event ScrollBar Scroll Bar Collaboration l listenerValuatorListener announceNewValue Synthesis 0 The process of constructing an application by composing multiple collaborations o P rocess Gather together all relevant collaborations Identify roles to be played by the same object For each object create an adaptor class to synthesize the role classes in the group for that object Write configuration code that allocates and links the objects S crollB ar Synthesis 1 align collaborations lt List ens lt ltinterfacegt gt Valua torLis ten or modelgt ltinterfacegt gt VieWPortModeI Do cManager 2 compose roles IS Synthes lt ltinterfacegt gt ValuatorListener VieWPort Synthesis 3 design adaptor classes 0 No need to adapt Scrollbar Only class in its columns 0 Other columns require us to adapt classes class MyViewPort public ValuatorListener public ViewPort class MyDocManager public ViewportModel public DocManager Synthesis 4 model configuration code S crollB ar lt Listens VieWPort m0 del DocManager Synthesis 5 write configuration code MyVieWPort Vp ScrollBar sb MyDocumentManager myMgr Synthesis 5 write configuration code MyVieWPort Vp ScrollBar sb MyDocumentManager myMgr sbregisterListenerampvp vpregisterModelampmyMgr Virtues of rolebased designs 0 Reuse with a welldesigned library much of the work of building an application is concerned with the synthesis of collaborations Good because synthesis is relatively mechanical Requires collaborations to be small and abstract 0 Program understanding Easier to understand roles in one collaboration than objects that are in many collaborations Documentation should include sequence diagrams Adding a home button 0 Suppose we want to add a home button to our application that returns you to the beginning of the document 0 What modifications do we have to make to our classes Reusability c We want to design objects that can be reused o In order to do this we need to avoid tight coupling A reusable object should not explicitly refer to an object it interacts with If Button contained a pointer to DocManager it would be an example of tight coupHng c To avoid this we use roles and interfaces What about this template ltclass Egt class Button protected E target int main ButtonltDocManagergt printButton Software Design CSE 335 Spring 2006 Objectoriented programming The Mediator Pattern Stephen Wagner Michigan State University A Simple Example Three objects a scrollbar a left button and a right button Clicking the buttons moves the scroll bar Each button should only be active ifthe scrollbar can be moved in the appropriate direction Elll IE Assume that buttons and scrobars can have multiple listeners How to implement Another Example Filemasks l c h Mmake le Buttonh Buttoncc ButtonListenerh gt Catalogcc Catalog h Font Directory Garbage IvalSlidercc IvalSliderh IvalText cc IvalText h Delete Copy Synchronization Collaboration 0 What happens when we enter a new mask Synchronization Collaboration 0 What happens when we enter a new mask announceNewValue leszListBox l chdirzButton l PeletezButton l loopyzButton update deactivate lt l deactivate lt l deactivate lt J Synchronization Collaboration 0 What happens when we change directory Synchronization Collaboration 0 What happens when we change directory chdirzButton llmaskszTextBox l leszListBox l copyzButton l buttonPressei Chdir getValue J gt update deactivate lt l deactivate lt Problem Assembly from reusable collaborations can lead to tight coupling between application objects Disadvantages The adaptor classes will be overly complicated and not reusable Complicates configuration Distributes invariant logic among a large class of entities Complicates collaboration synthesis due to large number of related collaborations update cycles Solution Mediator o A single object that encapsulates how a set of objects interact 0 Advantages Promotes loose coupling by keeping objects from referring to each other explicitly Central point for cyclic updates Central manifestation of invariant logic Mediated vs Distributed Collaboration ListBox Button TextBox Mediated vs Distributed Collaboration 0 The Mediator class is designed to solve a specific problem It will be tightly coupled with all of the other objects in the collaboration It will generally not be reusable o The other objects will be unadapted and reusable o In the distributed design There will be a large number of adaptor classes None of these classes will be reusable Mediated Collaboration l chdirzButton medzMediator lmaskszTextBox leszListBoxl l cogyzButton l ldeletezButton buttonPressed getvalueo lt update deactivate lt JJ deactivate deactivate lt l J gt lt Mediator Synthesizes Listener Roles class Director public ButtonListener public TextboxListener public ListBoxListener public Director void buttonPressedconst string amp void notifyconst string amp void entryActionconst string amp private Button copy Button delete ListBox fileList TextBox fileMasks The Mediator Class class Director public ButtonListener public TextboxListener public ListBoxListener o The Mediator class implements a number of interfaces 0 The Mediator class is not an adaptor class it does not adapt an existing cas o The Mediator class will contain private members It needs to have pointers to all the objects in the collaboration It could have additional members It could also have additional member functions Mediator Localizes Configuration Code DirectorDirector ok new Button cancel new Button fileList new ListBox fileMasks new TextBox o It usuaHy nwakes sense to have the nwediator create the objectsit nwediates 0 Who should register with the buttons Mediator Localizes Configuration Code DirectorDirector 0k new Button cancel new Button fontList new ListBox fontName new TextBox 0kregisterListenerthis cancelregisterListenerthis fontListregisterListenerthis fontNameregisterListenerthis 0 Why do objects not register with the mediator What s Wrong Here DirectorDirector Button 0k Button cancel ListBox fontList TextBox fontName 0kregisterListenerthis cancelregisterListenerthis fontListregisterListenerthis fontNameregisterListenerthis Foundations Language Mechanisms and Primitive OO Concepts Lecture 1 Classification and Inheritance Topics Software engineering principles and support for them in programming languages Derived classes and inheritance Advantages of inheritance Reusing functions Member function overriding Software Design Body of Knowledge Organized around a set of core principles Rigor and formality Separation of concerns Abstraction Anticipation of change Modularity Generalization lncrementality Goal At end of this course you should be able to apply these correctly in real design contexts Source Fundamentals of Software Engineering by Ghezzi et al Core Principles and Programming Languages Core principles heavily influenced the evolution of programming languages Example good support for data abstraction did not exist in older languages such as Pascal and Fortran Now it is a staple of all generalpurpose languages What is new with objectoriented languages More direct support for generalization abstraction behavioral separation of concerns and incrementality We begin to explore these principles by first looking at new language features that support them Motivation Employee Records Question Do you see any problems with this design Example from Stroustrup 2000 Motivation Employee Records hi ri ngdate39 de39paritmen 3 Questions Is it possible for a Manager to have another Manager in hisher group How would you have to write this code Motivation Employee Records Question How would you write code that prints the first and last names of every employee in a company including those who are managers Derived Classes Defines new class by extending existing class Base class Class that is extended Defines function and data members that are inherited by the derived class Derived class Inherits function and data members from base class May add additional functiondata members May also override inherited function members with new methods How to Declare a Derived Class SName kind BaseCla Where kind 6 public private protected ThinkPair Share Procedure 1 l pose a question or problem 2 Think Silenty sketch out an answer to the question 3 min 3 Pair l assign you a partner 4 Share Discusscompare your answer with your partner39s 3 min 5 I randomly select a student to describe their solution ThinkPair Share Activity Problem Design a better Manager class using inheritance My Solution ranager public EmpI Q Employeegt group a l vel Terminology Manager called the derived class also subclass Employee called the base class also supercass Manager inherits from Employee PointersReferences and Inheritance Pointer resp reference to an instance of a derived class can be used as pointer resp reference to an instance of its base class ampe Advantages of Inheritance Factor out code that is common in multiple classes Less code to maintain Fix errors once Reuse functions that operate on baseclass instances Invoke function whose formal parameter is of reference or pointer to class C with actual parameter of reference or pointer to class derived from C Represent domain relationships explicitly in code Example Class Figure class Figure public Figureunsigned x unsigned y xLocationx yLocationy unsigned getXLocation const return xLocation unsigned getYLocation const return yLocation protected unsigned xLocation unsigned yLocation Example Class Figure class Figure public Figureunsion unsiord y xLocationx yLocationy unsigned getXLocation const return xLocation unsigned getYLocation const return yLocation protected unsigned xLocation unsigned yLocation Example Continued class Rectangle public Figure public Rectangleunsigned x unsigned y unsigned length unsigned height Figurexy lengthDimensionlength heightDimensionheight unsigned getLength const return lengthDimension unsigned getHeight const return heightDimension protected unsigned lengthDimension unsigned heightDimension Example Continued fruoz or initl class Rectangle public Figure public Rectangleunsio d x unsigned y signed length unsigned height Figurexy lengthDimensionlength heightDimensionheight unsigned getLength const return lengthDimension unsigned getHeight const return heightDimension protected unsigned lengthDimension unsigned heightDimension Example Reusing Functions Const Figureamp fl consti i5 f1getXLocation 39 f1getYLocation f2getXLocation 39 z zggetYLocation 7 le f1Yf1Y lt sqrtf Example Reusing Functions Cont39d int mainvoid Figure fig12030 Figure fig23050 Rectangle rect110401328 Rectangle rect2548 101 50 if nearerOriginfigl fig2 m if nearerOriginrectl rect2 m if nearerOriginfig2 rect1 m Recall Conceptual Model of Memory Use by a Running Process Process partitioned into 2 major chunks Static part contains program code static data etc Dynamic part contains runtime stack heap All local variables and objects created using new live here Implementation of Inheritance Reciteingle Figure Object length yLocation yLocatio39nH xLocation eight xLocatiQn angle quot iygure getYLocatig g ThinkPair Share Activity Question Thinking in terms of bits bytes and the layout of data in a computer s memory how is it possible to pass a reference to a Rectangle to a function that expects a reference to a Figure f1getXLocation f1getYLocation f2getXLocation f2getYLocation ThinkPair Share Activity Answer Question Thinking in terms of bits bytes and the layout of data in a computer s memory how is it possible to pass a reference to a Rectangle to a function that expects a reference to a Figure Answer Instances of a derived class are implemented as instances of the base class with additional data appended at the end Derived Class Implementation figl fig2 rectl rect2 xLocation 20 30 10 5 yLocation 3O 50 4O 48 lengthDimension 13 101 heightDimension 28 50 Visibility of Class Members Given Base class A with data or function member m Derived class B which inherits from A Function fa that uses an object of class A Function fb that uses an object of class B ipir39fi it fsji t
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'