Software Design CSE 335
Popular in Course
Popular in Computer Science and Engineering
This 22 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 Xiang-Yang Liu in Fall. Since its upload, it has received 11 views. For similar materials see /class/207408/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.
Date Created: 09/19/15
CSE 335 Syllabus for Fall 2009 httpwwwcsemsueduNalexliucourses335Spring20l 2Syllabus html CSE 335 Software Design Spring 2012 TuampTh 1240 PM 200 PM in room 145 Communication Arts Building Instructor TA Dr Alex X Liu Office Hours Tuesday amp Thursday 200 PM 300 PM or by appointment Email alexliucsemsuedu Office 2132 Engineering Bldg Course homepage httpwww me msn 4 walexliucoursesTiWnrino w 2 Syeda Momina Tabish tabishsymsuedu Office hours Monday and Wednesday 500 600 PM Friday 1200 100 PM or by appointment Extra of ce hours 600PM900PM on 26 212 216 311 321 325 48 422 425 Location 3353 Engineering Simpsons Lab Eric Norige norigeercsemsuedu Regular of ce hours Tuesday and Thursday 1000 AM 1100 PM Friday 430 530 PM or by appointment Extra office hours 600PM 9z00PM on 122 25 219 34 318 320 41 415 424 Location 3353 Engineering Simpsons Lab Prerequisites CSE 232 uency in the C programming language CSE 260 discrete structures Background and goals This course will introduce students to the development of large software products libraries and product families with emphasis on design concerns that dominate the development of such so ware These concerns include reliability reusability maintainability and ease of extension and contraction Students will learn how to use objectoriented design techniques to address these concerns The course emphasizes explicit modeling and critical analysis of designs prior to implementation Students will learn heuristic methods to design for integration and changes in requirements Students will also learn the fundamentals of software speci cation and techniques for designing software to meet its speci cation This course focuses on implementation techniques analysis and design heuristics and best practices that have proved useful in making the softwaredevelopment process rigorous systematic repeatable and manageable Students will be introduced to current methods which they will apply to programming and design projects Finally this course is primarily about design which is very dif cult to learn by reading a book or cramming for a test Design problems involve choices and tradeoffs and often there is no single quot11 tquot answer The instructor s role in such a course is to set up an environment that will force students to confront and appreciate dif cult design issues and to provide critical and continual feedback to students on their choices It is the student s responsibility to actively participate in this environment and to re ect and respond to the issues that are discussed To achieve these goals we will supplement the lectures and required readings with inclass collaborative exercises and materials on heuristics for problem solving Topics to be covered include lof4 llO20l2 1139AM CSE 335 Syllabus for Fall 2009 httpwwwcsemsueduNalexliucourses335SpringZOl2Syllabus html 0 Design principles speci cally abstraction anticipation of change generality incrementality modularity reusability and separation of concerns c Design methods patterns and heuristics 0 composites strategies visitors observers and adapters 0 rolecollaboration design Maintenance issues Modeling notations and methods speci cally UML Software architecture Speci cation and documentation Required textbooks ObjectOriented Modeling and Design with UML 1 Second Edition by Blaha and Rumbaugh PearsonPrenticeHall 2005 Design Patterns Elements of Reusable Obiectoriented Software by Gamma Helm Johnson and Vlissides Addison Wesley 1995 Grading Your grade will be determined as follows 1 0 2 0 3 0 Grading Policy All grades become nal two days after the grade is issued There will be no exceptions If a student wishes to challenge any exam grade he or she must do so in writing with a concise explanation for why his or her misgIaded answer is correct This explanation should be submitted to the TAs Regrading request will cause the entire exam of the student to be regIaded and thereby the overall grade of the student may increase or decrease ALL questions regarding exam and project grades should go to the TAs If the problem cannot be resolved after consultation with the TAs the TAs will forward a summary of the problem to the instructor with an email carboncopy the student 5 Equot PMquot Attendance Policy Attendence is REQUIRED Your attendance will be monitored and graded based on random roll calls Examinations There will be three examinations during the term There will be no nal exam per se The dates and times for these exams are as follows 20f4 llO20121139AM CSE 335 Syllabus for Fall 2009 30f4 httpwwwcsemsueduNalexliucourses335Spring20l 2Syllabus html Extra TA Of ce Hours 600PM900PM on Exam 1 27 1240 PM 200 PM EB 2243 25 No ge and 26Tabish Extra TA Of ce Hours 600PM900PM on Exam 2 322 1240 PM 200 PM EB 2243 320N0rige and 321Tabish Extra TA Of ce Hours 600PM900PM on Exam 3 426 1240 PM 200 PM EB 2243 424N0rige and 425Tabish The exams will cover material 39om assigned reading projects homework assignments and the lectures No makeup exams will be given For cases that you have documented illness or personal emergency if you miss one of the first two exams you grade for the missed exam will be the grade of the next exam if you miss the third exam your grade for the missed exam will be the average of the first two exam grades A student not taking an exam without veri able documentation will receive a grade of 0 for that exam Projects There are three programming design projects with intemediate submission deadlines You are encouraged to form a team with a maximum of two students If you form a team then you are required to work together with your team in writing codes For each submission you must submit a plain text document stating the number of lines of code written by each student and that by both In case that the effort of the two students is signi cantly unbalanced we will assign different grades to each students No late submission is accepted no matter what illness of personal emergency that you have You need to manage your time to avoid last minute submissions This rule is FIRM and no exception will be made Mni prajects There are 6 programming miniprojects You are encouraged to form a team with a maximum of two students If you form a team then you are required to work together with your team in writing codes For each submission you must submit a plain text document stating the number of lines of code written by each student and that by both In case that the effort of the two students is signi cantly unbalanced we will assign different grades to each students No late submission is accepted no matter what illness of personal emergency that you have You need to manage your time to avoid last minute submissions This rule is FIRM and no exception will be made Homework There are 7 homework assignments which will not be graded However I highly encourage you to do these homework assignments because they are very useful for you to understand the concepts and also very useful for you to do the projects and miniprojects Grading Scale The grading scale will be as follows 90 100 40 85 89 35 80 84 30 75 79 70 74 65 69 60 64 060 or academic misconduct 00 N OK D ID I OUI The instructor reserves the right to modify this syllabus during the course of the term Email Policy Speci c technical questions should be directed to the TAs first if approriate If you cannot obtain a satisfactory llO2012 1139AM CSE 335 Syllabus for Fall 2009 40f4 httpwwwcsemsueduNalexliucourses335Spring20l 2Syllabus html answer from the TAs then email the instructor brie y explaining when you email the TA what s his reply and why you are not satisfactory I tend to defer reading email until the end of a day but you should be able to receive my reply within 24 hours Integrity and ethics The policy of the university on integ1ity of scholarship and grades pages 4950 Academic Programs 1993 will be followed Implicit in handing in homework papers and exams is that they represent the student s own work Any exceptions should be preapproved by the instructor and explicitly noted Note that for any material that you can nd especially if it is available on the web I can nd it too Students who plagiarize will receive a 00 for the course or 00 for the assignment at the instructor s discretion All students are expected to be responsible users of the computer system provided for this course Account usage guidelines published by the Department of Computer Science and Engineering are available at httpwwwcsemsuedufacili policyhtml In addition students are expected to adhere to MSU39s policy on quotGood Citizenship in Cyberspace quot Section IV p85 of Spartan Life Article 235 of the Academic Freedom Regort APR for students at Michigan State University states quotThe student s behavior in the classroom shall be conducive to the teaching and learning process for all concernedquot Article 2310 of the E states that quotThe student has a right to scholarly relationships with faculty based on mutual trust and civilityquot General Student Regulation 502 states quotNo student shall interfere with the functions and services of the University for example but not limited to classes such that the function or service is obstructed or disrupted Students whose conduct adversely affects the learning environment in this classroom may be subject to disciplinary action through the Student Faculty Judiciary process 11020121139AM CSE 335 Spring 2011 httpwwwcse msueduNalexliucourses335Spring2012Lectures html Date Topic Announcements and notes 0110 TU Introduction 1 D0 homework 1 1 D0 homework 2 To access HW directory please login to your CSE 01 12 Class Inheritance account Then type the followmg TH commands cd cd cse335A1exLiuHW 10f3 0117TU MiniProject 1 on Polymorphism is out LP39 P01 m hlsm Due at 1159 PM on 122 3419 UML Basic Class Modeling Rumbaugh book chaper 3 amp 4 1 Gamma book quotCompositequot chapter 0124 TU Composite Pattern 2 D0 homework 3 0126 I I 1 Gamma book quotVisitorquot chapter TH V1s1t0r Pattern 2 Project 1 is out 0131 TU Case Study Composite Pattern Visitor Pattern 23402 Review Session for Exam 1 Extra Of ce Hours for Exam 1 Eric Norige ericn0rigegmailc0m 0207 TU Exam 1 at EB 2243 600PM900PM on Feburary 5th Syeda Momina Tabish tabishsymsuedu 600PM900PM on Feburary 6th 0209 TH Exam 1 Debrle ng 02 14 TU Make and Make le 1 Gamma book quotAbstract Factoryquot chapter 23416 Abstract Factog Pattern Exam 1 Debrie ng 2 MiniProject 2 on Abstract Factog Pattern is out Due at 1159 PM on 226 1 Gamma book quotBuilderquot chapter 0221 TU W 2 MiniProject 3 on Builder Pattern is out Due at 1159 PM on 34 1 Gamma book quotAdaptorquot chapter iii23 Ada tor Pattern 2 D0 homework 4 3 MiniProject 4 on Adapter Pattern is out Due at 1159 PM on 311 1 Gamma book quotObserverquot chapter 0228 TU Observer Pattern 2 D0 homework 5 3 Project 2 is out 11020121139AM CSE 335 Spring 2011 httpwwwcse msueduNalexliucourses335Spring2012Lectures html 4 MiniProject 5 on Observer Pattern is out Due at 1159 PM on 318 3101 nllnhnmtin n Modeling and lquot quot 0306 TU Spring Break 03 08 TH Spring Break 03 13 TU Collaboration Synthesis 1 Do homework 6 1 Gamma book quotMediatorquot chapter 2 Example code for Mediator Pattern that can compile on b1ackcse AlexMediator b1ackzip 03 15 M d t P n TH M 3 Example code for FLTK GUI with menu that can compile on b1ackcse Mediator2zip 4 MiniProject 6 on Mediator Pattern is out Due at 1159 PM on 325 0320 TU Review Session for Exam 2 Extra Of ce Hours for Exam 2 Eric Norige ericnorigegmailcom Exam 2 at EB 2243 600PM900PM on March 20 Syeda Momina Tabish tabishsymsuedu 600PM900PM on March 21 0322 TH 03 27 TU Application of Design Patterns in Industry 12 3429 Application of Design Patterns in Industry 2 2 0403 TU Template Method Exam 2 Debriefmg Gamma book quotTemplate Methodquot chapter 0405 Sample Code PerlisismBrowserzip Copse TH concu 200703302ip DetachedThreadszip 1 Project 3 is out 04 10 TU Synchronization 2 Do homework 7 3 Rumbaugh book chapter 5 amp 6 04 12 TH State Modeling Rumbaugh book chapter 5 amp 6 04 17 TU State modeling for Concurrent Software Sesign Rumbaugh book chapter 5 amp 6 gig19 Reference Counting 0424 TU Profess1ona1 C Coding ReV1ew Sess1on for Exam 3 Extra Of ce Hours for Exam 3 0 4 2 6 Eric Norige ericnorigegmailcom TH Exam 3 at EB 2243 600PM900PM on April 24 Syeda Momjna Tabish tabishsymsuedu 600PM900PM on April 25 2of3 11020121139AM CSE 335 Spring 2011 httpwwwcse msueduNalexliucourses335SpringZOl2Lectures html Acknowledgement The slides contain material from the books quotDisign Patternsquot and quotObjectOriented Modeling and Design with UMLquot R E K Stirewalt39s slides and some other resources 3of3 11020121139AM CSE 335 Software Design Dr Alex X Liu alexliucsemsuedu http wwwcsemsueduNalexliu 2243 Engineering Building Department of Computer Science and Engineering Michigan State University Reasons to take CSE 335 39 Many reasons to take CSE 335 E g it is required Help you to become a master programmer and designer 39 Help you to succeed injob interviews e gooogle 39 You are very fortunate How to learn thls course well 39 1 Before class Smdy slides or corresponding chapters Bring your questions to the class 39 2 During class Listen to lectures carefully ASK any questions at any time 39 3 After class Reviewlectures in team Do homework in team Do miniprojects in team Do projects in team Strictly follow the above 3 steps I guarantee that you will enjoy and learn this course we 1 Science vs Engineering 39 Science is on discovery 39 Engineering is on design useful structures amp machines Programnnng vs Eng1neer1ng Programming 7 mail project You 7 Build what you want one product 7 Few sequenuai changes Shortrlived 7 eap 7 srnan consequences Engineering 7 Huge project 7 Costly 7 Large Consequences Software Engineering 39 Software engineering is a special type of engineering So ware is extremely complex Software consti39uctionis humanintensive Software is intangible and invisible So ware is constantly subject to pressure for ehange Software needs to conform to arbitrary interfaces and contexts o Eg business rules and processes vary drarnaucany from business to business o E g exrsung databases ofmformatzon Software Development Lifecycle Waterfall Model n Valldatlan i Problem Definition 7Requuemems Speci cation 7 damning exactlywhatthz cu urn71 mam71 want 7 develop 5 mm with the cmmmex 7 speci eswh m suf xAre pmductis suppsss m da Dif culties pzaduct 7 client ls camputexsa ware ilhtente m 7 eyesi cauansare m guausmsanssunt incumplete 7 2 1 T 1 quot3e51gn 1 amp Integration Design 7 Implementation mm WWW mm m mm quot mm m 7 implem ntmanhles verify thattheymeetthzu spssl smms 7 ang amp m1 swam mam alums 7 h M amp m m d 7 mammna ncaxdm39dzslgndzcismns andtnceahih m m 5 c g 5 SPEND mm mm D an mm 7 haw a sum mm m mm mum 7 mmwmbmmm isms mems 7 as n be mmm samples mm 7 mm Wmm ms Architecture vs Design 7 mom smmmam m mm armmmmm m mammals and m mums an mass exams and m mmms mm m was rmkammhm mm mums mum mm M ang 7 new m m momma dztmlzd Wm M aw aims Miami and aims mm wwsmasam mm m mom mam My quotNews 9 m Verification and Validation Deployment amp Evolution Analysis 7 sun Science 7 Formal Veri cation tax 7 Issues mm adequacy Operation 7 Change 7 mm sufoIAre mungah use operaan 7 damning Wham71 m mm sun functions currently Dif culties lack af Aacunzntahan 7 persamel mmavex Economic and Management Aspects v 39 Maintenance costs gt 60 of all development costs 39 Quicker development is not always preferable higher up ont costs may defray downstream costs poorly designedimplemented so ware is a critical cost factor Relative Costs of Fixing Software Faults 200 10 mamquot manna Mummy Hardware Failure Curve infant ortallty Wears out Failure Rate Time Ideal Software Failure Curve continues at same rate until software is retired Failure Rate Actual Software Failure Curve actual Curve Failure Rate ideal Curve Time How to become a software design master Learning to develop good software is similar to learning to play good chess To become a chess master To become a software design master 39 First learn the rules e g names ofpieces legal movements captures board geometxy etc 39 Second learn the principles e g relative value ofcertain pieces power ofa threat etc But principles are abstract How to apply them inpmctice39 39 Third learn the patterns by studying games of other masters and applied repeatedly until they become the second nature 39 First learn the rules e g programming languages data stxuctures etc 39 Second learn the principles But principles are abstract How to apply them in practice Third learn the patterns by studying designs of other masters and applied repeatedly until they become second nature 20 Software Englneermg Prrnciples Rigor and formality 39 Rigor and formality 39 Software development is a creative design process But creativity implies informality imprecision and inaccuracy 39 Separation of concerns 39 Rigor and formality are necessary Modularity to improve quality and assurance of creative re ult to ensure accuracy in de ning and understanding problems 39 Abstraction 39 Rigor and formality help to improve reliability and verifiability 39 Anticipation of change 39 Evident in Generality Design notations requirements speci cations process de nitions 39 Incrementality 21 22 Separation of concerns Modularity 39 We cannot deal with all aspects ofa problem simultaneously A complex system may be divided into simpler pieces called odules 39 To conquer complexity we need to separate issues and tasks A system that is composed ofmodules is called modular Separate functionality from ef ciency 39 Supports separation ofconcerns Separate requirements speci cauon from design 56pm spongbmdes when dealing with amodule we canignore details of other modules 39 Three goals with modularity 39 Divide amp conquer quot Composability construct solution from sub solutions Today s applications involve interoperability of Understandabillty understand system by understanding subsystems clientServer Legacy system cors Commercial OffTheShelt Two essential properties databases etc Mumple my ng languages C CH I m oheilon degree tofvyhcmPartsdofa rrodule are liztled wrtlun a ms lule H dmgg mus hquot dwm ms pmfoms oup lng amount o inter epen enee etween mo es among mo es 39 Separation of concerns is critical 23 A Visual Representation Abstraction 39 Identify the important aspects and ignore the details 39 Abstraction supports separation of concerns Divide amp conquer vertically Modularity divide amp conquer horizontally 39 Abstractions dominate computing Design Models ER U39ML etc Programming Languages c c Java etc high coupling low coupling I Example Pain oe ee u ene roueh Pad Mouse Light Pen Txac Ball nn739l39xack Hall 25 26 Anticipation of change Generality Sottware changes and evolves throughout all stages from speci cation I When given a speci c problem try to discover if it is an Md instance ofa more general problem whose solution can be changes are inevitable reused in other cases 7 Reqm emem mg Supermarket Systemvs Inventory Control 7 Programmer changes Hospital Application vs Health Care Product 7 Technology changes This affects all aspects ofso wm engined c template link list ofmtegerslmkhstof oats 7 Make sure all artifacts are easy to change Mudulanzzttunand Sepamtlun efcencems 39 Reuse adapt general solution to speci c problem Make sure W can mantaquot many vermns artifacts Inventory Control for Supermarket Auto Parts video Tape Rental etc a Pam me mm Health Care Product for HospitalMD oftice Dental office etc 7 Plan for a rapidly changing market Plan for rapidly changng technolo Amupmon of mg supports 5 e 39 Addltlonal shortterm effort Vs longterm galns maintenance lanzataon encapsulate areas forpotentaal changes 7 Separation ofconcems 27 28 Incrementality Just learning principles is not enough 39 Move towards the goal in a stepwise fashion incrementr 39 Software should be built incrementally Identify useful subsets ofan application and deliver in increments Deliver subsets ofa system early to get early feedback Focused less errors in smaller increments Phased prototypes with increasing functions 39 Separation of concerns in terms offunctionality 39 You need to learn Design Patterns of other masters Etample o Composite pattern o Visitor pattern o Template method 0 More 39 At the end ofthe course you should be able to apply these principles with proficiency in real design contexts Example of Bad Design Example of Good Design class Employee class Manager class Employee class Manager publle Employee publle publle publle publle smng rstName Employee p smng rstName llstltEmployeegt group stxlng lastName llstltEmployeegt group smng lastNam Date lunnggolalc short leve Date lunng date gt snon department department gtr gt 39 Why this design is bad Domain knowledge is stable overtime A manager may have another manager m their group What ifyou want to add another role vice president above manager Whatifyou want to print out the name of every employee Recall the abstraction principle Recall the separation of concerns principle Recall the anticipation of change principle Recall the generality principle Recall the incrementality principle Recall the modularity principle Assignment Do Homework 1 UML Basic Class Modeling Dr Alex X Liu alexliucsemsuedu httpwwwcsemsuedualexliu 2243 Engineering Building Department of Computer Science and Engineering Michigan State University How to describe an object oriented design Objected oriented software has many classes Each class has data members and functions Classes have complex relationship such as inheritance How to describerepresent an 00 design Source code is not suitable for communication and reasoning 0 Low of redundancy and detail irrelevant for some programunderstanding tasks 0 Especially poor at describing relationship among classes in 00 programs 0 To understand an 00 design one must be able to visualize these relationships Solution Unified Modeling Language UML o Represent data members and functions for each class 0 Visualize relationshi amon classes 0 Good for reasoning Whether an 00 design is good Uni ed Modeling Language UML I Collection of notations representing software designs from three points of view Class model describes the static structure of and relationship among objects and classes in a system 0 Object diagrams 0 Class diagrams State model describes the dynamic aspects of objects and the nature of control in a system Interaction model describes how objects in a system cooperate to achieve broader results Generally need all three models to describe a system No single model says everything I In this lecture we focus on class model I Thinking in UML Writing in C UML class diagram notations Boxes denote classes Each box COm39EI lSEEII Class name Em o ee firstname string lastiname strinr srr ith hiredate Date department short Listof0perations gumm prlntv0Id More compact than code 0 eg Employee List of data attributes o eg rstiname lastiname etc Default value Easier to describe relationship among classes City Only list attributes that have intrinsic meaning Attributes of computer artifacts such as pointers should not be listed cityName string population unsigned 4 Abstraction in class diagrams I Class diagrams often elide details Method associated with an operation Attributes and operations may be elided in the diagram to improve readability 0 Even if they exist in the C code ClassName attributeName1dataType1defautVaue1 optional attributeName2dataType2defautVaue2 optional operationName1argumentList11resultType1 39 iltt7t39resultType2 Employee firstname string astname string hiredate 39Date department short Employee Object or instance notation Objectname ClassName attribute1 value1 I Notes The UML symbol for an object is a box with an obj ect name followed by a colon and the class name The object name and class name are both underlined Attribute values and the object name are optional Only list attributes that have intrinsic meaning Attributes of computer artifacts such as pointers should not be listed 6 Example Depicting an ob ect Named vs anonymous objects object name class name UML CH doe Employee doe I Employee Employee doe Johnquot Doequot firstname John Employee doe dag name Doe frrstname John new Employee Johnquot Doe rhiredate Sep1211 k SLEartne 23930 1998 vde artment225 Ire a e ep p department 225 attribute names attribute values doe Employee Em 390 ee eLlst addEmpl firstname Mary new Employee Mr astname Smith hiredate Oct11811980 department 230 Value vs Object Value abstract piece of data no identity Eg the number 17 the string Canada Object concrete thing has identity Eg a student object whose age is 17 a country object whose name is Canada May have multiple attributes and each attribute has a value Often appears as a proper noun or specific reference in discussions with users Houston TX Houston TX 3000000 3000000 9E cityName Houston TX population 3000000 cityName Houston TX population 3000000 What s the big deal about identity Useful in reasoning about the quality of a design Many poor designs result from an encoding of one object within another using attribute values By reasoning about identity one may identify such a design flaw early I Also allows us to model relationships amon obects and classes more explicitly Example Travelplanning system A City has aname a certain population and a specttic time zone A city has one or more airports An airport has a name and a unique code An airport may serve multiple cities cityName string population unsigned Is this a good design tlmezone 1 zone I airportName string airportCode code Bad Design City cityName string population unsigned timeZone zone 39airportName string airpodCode code Answer These attributes hiding an object ie an airport that is meaningful in this domain Question Why might it be bad to encode one object as a collection of attribute values within another Answers Potential for redundancyinconsistency due to duplication 0 some cities served by multiple airports 0 some cities served by no airports 0 some airports serve multiple cities Operations over Airport objects may not need to know details associated with cities such as population City cityName string population unsigned timeZone zone airportName string airportCode code Design tip I When designing a class Apply the identity test to each attribute including attributes in combination 0 ls this an object or the attribute ot an object 0 Do you have operations 7 Value no operations associated 7 Objects have operations associated 7 Eg An Airport object may have an operation to print all cities that it serves 0 If it is the attribute of an object then every object of this type should have this attribute 7 Student name every student must have a name So student name is an attribute 7 Airport some cities do not have airports So airport is an object I UML notation helps enforce this discipline I So then how do we model connections between objects such as Cities and Airports Links among objects vs Associations among classes Link Physical or conceptual connection between objecm Example Human object John and Company object Amazon may have a link indicating that John works for Amazon There maybe multiple links between two objecm Example John an d Amazon also have another link indicating that John is also a customer of Amazon Association Description of a group of links with common structure and semantics Example Human class and Company class may have an association for the workfor relationship There maybe multiple associations between two classes An object is an instance ofa class A link is an instance ofan association 13 14 Example links Example assomation muti lieties Serves 0 HOU Airport airportCode HOU 1 airportName Hobby quot timeZone Central Serves My cityName string airportName string cityName Houstonmquot population unsigned airportCode code population 3000000 IAH Aimort timeZone zone alrp nc de 39AH association name Serves tinieZone Central 15 Multiplicity constraints xy wz n There are There are w to 2 Es xto yAs for eachA for each B X g 0 1 or specific number Also A speci c list y 1 or specifc number is acceptable quot any number 19 2 4 5 01 means Optional 1 means At least onequot 0 means Any number Association End Names I On each end of an association you can also specify the name of the role that the end plays in the association I Association names are optional Implementation Methods of Associations class CitA class CitA protected protected tring citynane string cityllame unsigned population unsigned population vectorltAirportgt serves class Airport class Airport protected protected string airportname string airportnane com airportcode CODE airportcode ZONE timezon 39 ZONE timezone 39 vectorltcitygt serves multinapltcityquot Airportgt citysezves multinapltAirport Citygt airportServes Avoid Infinite Recursion How to model Children and Parent Should we design two classes One is called Child and one is called Parent This is bad because a person is both the child of hisher parent and the fathermother of hisher children ChildrenParent should be modeled as an association not classes I Without 0 this recursion is endless Object diagrams are snapshots Joe Person Sally Person Time T7 39 Time T2 it group Generalization Employee firstname string astname string hiredate Date department short Manaer evel short I A ka the isa relation I Relates class to one that is more general Open arrow points to base class ie the generalization Derived class inherits all public and protected attributesoperations or base class I Relation is antisymmetric and transitive Implementation of Generalization Must use PUBLIC inheritance Definition of isa relationship B is a A if and only if instances of B can be used in contexts that expect instances of A Example A manager is an employee A student is a human Formally defined in the classic paper by Liskov andWing Barbara Liskov leannette Wing A behavioral notion of subtyping ACM Transactions on Programming Languages and Systems TOPLAS Volume 16 Issue 6 November 1994 pp 1811 1841 Why cannot be privateprotected inheritance isa cannot Via privateprotecte Will this comgile include ltiostreamgt using namespace std public Aint t foot virtual voidpnnto coutltlt quotA printquotltlt endl class B private A public B int 1 void print coutltlt quotB printquotltlt endl int mainvoid ap pnnto Errnr 39A39 is an inaccessible base at returnO 39B Nine B abject can be instantiated hntA painter cannnt pninttn 39t Avoidai lapu Defining class B by privately inheritingirom class A is almost always equivalent to giving B a private data 39 e member oI39A Same to protected inheritanc include ltiostreamgt using namespace std class B public Bonn 211 o voidpzo a printO private A a Class Inheritance in C Header Flles 39 To prevent being included twice 7m DER define MYiHEADER your declarations endil include ltiostreamgt search in include search pa Used for system header les include MyHeaderh search in current directory May check include search pam ifnot found there Used for your own header les Constants I deflne BU39FFERSIZE 100 7 E F RSlZE cannot beused as a Wnable I constlnt buffer y const className aConstan Object 7 Whatlfwe mvuke an upeeauun en a constant objectthat En mange as data memba39s 7 ac unstantob ect setValu nly cunstmEmbEr runenuns ean be lnvukedl ml getValueO const gtHlIWlllnotEl1ange data members constlntgetValueO wrne funeuon39s retum valuel const 7 ypes 7 But mnlngrulruruseedennedlypes getsmdentReeurdoseMameo Pnnclple Query funeuons sueln as getValueO shouldalways be de ned as const van ml 7 mt eumpard cunst Studentamp sl cunst Studentamp 52 lnluallzauon list ofthe constructor 7 StudEnKstnng name studenlNamdnamex gt Static ln c uunterh elass Cuuntalt pu ll CuuntaOlt numgt static mt getNumO lt return num gt Can unlyrefa39tu static meenlseenum rum e static unsigned num une eupy p at elass smn name ne eupy pa object gt ln c Hunter L pp unsl gned c Hunter Static class data members are allocated on a per class basis rather than a per object basis Static class function members can only refer to static data members 4 Namespace Function Overloading 39 Prevent naming con icts l lntmaxrlnmnt l I I I I I I I doublemaxf double double class Declare namespace namespace lbmStxingPackage ass string Mim lanentation ofstrinu class Two ways to use IBM string class 7 2 Declare using namespaee lbm StnngPackag name B lrst then use smng as elass utm thls ease you cannot delare using namespaee stdquot 39 Same function but different signatures retum type parameters 39 One type ofpolymorphism Information Hiding 14 elass A data and functions needed by ehents public interface proteeted data and funetlons needed by derived elasses pnvate data and funetlon needed by elass A only 39 Why private Client programs do not need them only for implementation eyaresubjecttofuturechange or 39 data 39 39 Why protected are not Information Hiding 24 elass DenyedCl assName assessgspesr et BaseClassName Accessspeci er public protected private Default no accessispeci er pnyate Public Inheritance Protected Inheritance Private Inheritance Access control rule effect the stricter one of access and base public pmltcmi privalz public public protested prime protested protested protested prime Information Hiding 34 39 When should access be protected or private some cases when ynuwant tn operat e an datawith more strinth requirements you do nntwant tn inherit th e entire interraee orthe has e For example suppose you have aDequeue elass that eontams operauons to insert nu oft e queue elass which one ean only insert on the left and delete on the nght dassDequeuelt elass Queue private puhhe Dequeue ynldlnsmi mt puhhe ynldlnsmm mt using mtrmuvew Dequeue lnsmL lntranuve Sing pmmed Dequeue remnyeR lntanal data gt39 struet gtv ote u m u Information Hiding 44 39 When access should be protected or pri t va e e In some eases when you only want to lnhent the implementation ufthe npaatmnsln the hase elass and you do not want to lnhent any interraee at all 7 r r mnl Wm h n in ddltl n elass Stank prime Dequeuelt elass Dequeuelt puhhe puhhe vuldpush lntx vnldlnsmi int musedX gtr vnldlnsmm int mtpupo EmmiEM gtr mummyer buul rullo lt return glen lntremnyeao e 39 prnteeted Pm39e 13 V usingDequeue m nm using Dequeue inght 7 Using39 must keep the aeeess level the ameas the hase Pointersreferences amp Inheritance I Pointer resp reference to an object of a derived class vs pointer resp reference to an object of its base voldfoo Manager mquotm Employee e ePtx eptrampm o mptr ampe Error An employee may notbe amanager Advantages of Inheritance 39 Factor out code that is common in multiple classes Derived class inherits function and data members from base class Derived class may add additional function or data members Derived class may override inherited function members with new thods 39 Reuse functions that operate on baseclass obje m tion whose formal parameter is of reference or pointer to class c with actual parameter ofrefermce or pointer to class derived C Represent domain relationships explicitly in code Manager and employee Example Class Figure Example Class Rectangle class Figure 1 pubire Figure unsigned x unsigned y xLoeanonx yLoeationy 1gt on on gt unsigned ge oeationO const 1 returr xLoean unsigned getYLoeationO const 1 returr yLoeauon gt protected unsigned xLoeauorr unsigned yLoeation 39 Note construction initializer list class Rectangle pubire Figure 1 pubire Rectangle unsigned x unsigned y unsignedlen th unsigned height Figurexy lengthDimensionOength heightDimensionheight 1 unsigned getLengthO eonst 1retum lengthDimension unsigned getHeightO must 1 returr heightDimension protected unsigned lengthDimension unsigned heightDimension 13 14 Example Reusing functions Example Reusing functions cont bool nearerongm const F1gureamp 1 eonst F1gureamp 2 1 intmamvoid unsigned 1 1ge oeauorro Figure g112030 rg213050 unsigned 1 1 getYLoeationO Rectangle reet11104013 28 unsigned 2x 2 getXIocauonO Rectangle reet254810150 unsigned f2Yf2 getYLoeationO ifnearer0ngmfig1 fig2 1 gt retum 1 1x 1x 1 1 1 1 lt1 2x 2x 2 1 2y gt r 1rrearerorrgrrr1reet1reet2 1 gt r 1rrearerorrgrrr1 rg2 reet1 1 gt gt 39 Note call by reference Vs call by Value 15 16 Implementation of Derived Classes Function Overriding 39 Objects of derived class implemented as objects ofbase class with ddmorml data pperlded at me en 39 eiassEmpiuyee1 eiassMauager puureEmpiuyee1 quot1 r prmte prmte to a function that expects areference to aFigure object mg mimem mev lmltEmpluyeegt WP shurt depanmmt shurt ievei public public 191 192 rectl void puuto euust1 vurupuut1euust1 euutltlt ame39 ltlt rain Empiuyee puut1us xLocadon ltlt ltltlast7nameltlt andl usltlt Level level ltlt Dept ltlt department n gt r leuglhDimensiou 13 gt39 heightDimension 18