What does this code do public static String
What does this code do? public static String cvt(int x, int y, int z) { String. Builder result = new String. Builder(); if (x < 0 || x > 3999) System. out. println("Value must be in the range 0 - 3, 999. "); if (x == 0) return "N"; for (int i = 0; i < 13; i++) { while (x >= values[i]) { x -= a[i]; result = result. append(b[i]); } } return result. to. String(); } Does this help? static int[] a = new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; static String[] b = new String[] {"M", "CM", "D", "C", "XC", "L", "X", "IX", "V", "I"}; What else would have helped? UWO The Computer Science Department 80 minutes 1
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 9: Architecting and Designing Software http: //www. today. com/video/today/53341315#53341315
Design Decision Question: What are some of the things you think, as a programmer, are important in order to say a piece of software is “Well-Designed”? Question: We all have to make design decisions when creating software. Let’s say that we decide to not use a database. • Why might we make that decision? (One reason is that your cs 2212 instructor won’t let you , what are other possible reasons? ) • What do we have to think about when making that decision? UWO The Computer Science Department 3
9. 1 The Process of Design Definition: • Design is a problem-solving process whose objective is to find and describe a way: —To implement the system’s functional requirements. . . —While respecting the constraints imposed by the nonfunctional requirements. . . - including the budget —And while adhering to general principles of good quality UWO The Computer Science Department 4
Facebook Help https: //github. com/jsuwo/facebook-applet-server Look at fbproxy. php (124 -160) and Facebook. Client. java (line 155 and 354 -401) UWO The Computer Science Department 5
Design as a series of decisions A designer is faced with a series of design issues • These are sub-problems of the overall design problem. • Each issue normally has several alternative solutions: —design options. • The designer makes a design decision to resolve each issue. —This process involves choosing the best option from among the alternatives. UWO The Computer Science Department 6
Making decisions To make each design decision, the software engineer uses: • Knowledge of —the requirements —the design as created so far —the technology available —software design principles and ‘best practices’ —what has worked well in the past UWO The Computer Science Department 7
Design space The space of possible designs that could be achieved by choosing different sets of alternatives is often called the design space • For example: UWO The Computer Science Department 8
Component Any piece of software or hardware that has a clear role. • A component can be isolated, allowing you to replace it with a different component that has equivalent functionality. • Many components are designed to be reusable. • Conversely, others perform special-purpose functions. UWO The Computer Science Department 9
Module A component that is defined at the programming language level • For example, methods, classes and packages are modules in Java. UWO The Computer Science Department 10
System A logical entity, having a set of definable responsibilities or objectives, and consisting of hardware, software or both. • A system can have a specification which is then implemented by a collection of components. • A system continues to exist, even if its components are changed or replaced. • The goal of requirements analysis is to determine the responsibilities of a system. • Subsystem: —A system that is part of a larger system, and which has a definite interface UWO The Computer Science Department 11
UML diagram of system parts UWO The Computer Science Department 12
Top-down and bottom-up design Top-down design • First design the very high level structure of the system. • Then gradually work down to detailed decisions about low-level constructs. • Finally arrive at detailed decisions such as: —the format of particular data items; —the individual algorithms that will be used. UWO The Computer Science Department 13
Top-down and bottom-up design Bottom-up design • Make decisions about reusable low-level utilities. • Then decide how these will be put together to create high -level constructs. A mix of top-down and bottom-up approaches are normally used: • Top-down design is almost always needed to give the system a good structure. • Bottom-up design is normally useful so that reusable components can be created. UWO The Computer Science Department 14
Different aspects of design • Architecture design: —The division into subsystems and components, - How these will be connected. - How they will interact. - Their interfaces. • Class design: —The various features of classes. • User interface design • Algorithm design: —The design of computational mechanisms. • Protocol design: —The design of communications protocol. UWO The Computer Science Department 15
9. 2 Principles Leading to Good Design Overall goals of good design: • Increasing profit by reducing cost and increasing revenue • Ensuring that we actually conform with the requirements • Accelerating development • Increasing qualities such as —Usability —Efficiency —Reliability —Maintainability —Reusability UWO The Computer Science Department 16
Design Principle 1: Divide and conquer Trying to deal with something big all at once is normally much harder than dealing with a series of smaller things • Separate people can work on each part. • An individual software engineer can specialize. • Each individual component is smaller, and therefore easier to understand. • Parts can be replaced or changed without having to replace or extensively change other parts. UWO The Computer Science Department 17
Ways of dividing a software system • A distributed system is divided up into clients and servers • A system is divided up into subsystems • A subsystem can be divided up into one or more packages • A package is divided up into classes • A class is divided up into methods UWO The Computer Science Department 18
Design Principle 2: Increase cohesion where possible A subsystem or module has high cohesion if it keeps together things that are related to each other, and keeps out other things • This makes the system as a whole easier to understand change • Type of cohesion: —Functional, Layer, Communicational, Sequential, Procedural, Temporal, Utility UWO The Computer Science Department 19
Functional cohesion This is achieved when all the code that computes a particular result is kept together - and everything else is kept out • i. e. when a module only performs a single computation, and returns a result, without having side-effects. • Benefits to the system: —Easier to understand —More reusable —Easier to replace • Modules that update a database, create a new file or interact with the user are not functionally cohesive UWO The Computer Science Department 20
Cohesion Error 1: No Unifying Concept Function with no real unifying concept This can happen if, for instance • We set arbitrary limits on the size of a function or module • We noticed a common section of code, so put it in a separate function without considering what it does Disadvantages for debugging • Hard to figure out what the function does • Hard to know what function to look in when looking for a fault To avoid when breaking up a function • Try to extract functions with more intuitive meaning UWO The Computer Science Department 21
Layer cohesion All the facilities for providing or accessing a set of related services are kept together, and everything else is kept out • The layers should form a hierarchy —Higher layers can access services of lower layers, —Lower layers do not access higher layers • The set of procedures through which a layer provides its services is the application programming interface (API) • You can replace a layer without having any impact on the other layers —You just replicate the API UWO The Computer Science Department 22
Example of the use of layers UWO The Computer Science Department 23
Communicational cohesion All the modules that access or manipulate certain data are kept together (e. g. in the same class) - and everything else is kept out • A class would have good communicational cohesion —if all the system’s facilities for storing and manipulating its data are contained in this class. —if the class does not do anything other than manage its data. • Main advantage: When you need to make changes to the data, you find all the code in one place UWO The Computer Science Department 24
Sequential cohesion Procedures, in which one procedure provides input to the next, are kept together – and everything else is kept out • You should achieve sequential cohesion, only once you have already achieved the preceding types of cohesion. UWO The Computer Science Department 25
Procedural cohesion Keep together several procedures that are used one after another • Even if one does not necessarily provide input to the next. • Weaker than sequential cohesion. UWO The Computer Science Department 26
Temporal Cohesion Operations that are performed during the same phase of the execution of the program are kept together, and everything else is kept out • For example, placing together the code used during system start-up or initialization. • Weaker than procedural cohesion. UWO The Computer Science Department 27
Utility cohesion When related utilities which cannot be logically placed in other cohesive units are kept together • A utility is a procedure or class that has wide applicability to many different subsystems and is designed to be reusable. • For example, the java. lang. Math class. UWO The Computer Science Department 28
Question Categorize the following aspects of design by the type of cohesion that they would exhibit if properly designed: • All information concerning a booking of an appointment is kept inside a particular class • A module is created to convert a bitmap image to a JPEG format • A separate subsystem is created that runs every night to generate stats about the previous days sales • A data processing operation involves receiving input from several sources, sorting it, summarizing information by input source, sorting according to the input source that generated the most data and then returning the results for the use of other subsystems. The code for these steps is all kept together, although utilities are called to do operations such as sorting UWO The Computer Science Department 29
Another Question What is wrong with the following design from the perspective of cohesion and what could be done to improve it? • There are 2 subsystems in a university registration system that do the following: • Subsystem A displays lists of courses to a student, accepts requests from the student to register in courses, ensures that the student has no schedule conflicts and is eligible to register in the courses, stores the data in the database and periodically backs up the database. • Subsystem B allows faculty members to input student grads, and allows administrators to assign courses to faculty members, add new courses, and change a students registration. It also prints the bills that are sent to students. UWO The Computer Science Department 30
Cohesion Errors: Time-Linked Actions Think about WHY you have divided up your code the way you have? Functions which perform a series of actions related only by the time we need to do them Example of how this can arise: • We have a 300 -line function we want to break up • We break it up into 6 functions —Lines 1 -50 —Lines 51 -100 —… • We broke up the function into smaller pieces all right • However, each piece is just “whatever we needed to do next” Disadvantages for debugging: • We are unlikely to remember when in the sequence of actions we needed to do something • Hence, we need to scan each of the functions in turn • Basically equivalent to scanning the original function UWO The Computer Science Department 31
Avoiding Cohesion Errors Group tasks that the function does conceptually Have a deeper hierarch of functions; e. g. • Before: function f calls f 1, f 2, f 3, f 4, f 5, f 6 • After: —f calls g 1, g 2 —g 1 calls h 1, h 2, h 3 —etc. • Similar to high level design issue of avoiding pancake structure to modules UWO The Computer Science Department 32
Design Principle 3: Reduce coupling where possible Coupling occurs when there are interdependencies between one module and another • When interdependencies exist, changes in one place will require changes somewhere else. • A network of interdependencies makes it hard to see at a glance how some component works. • Type of coupling: —Content, Common, Control, Stamp, Data, Routine Call, Type use, Inclusion/Import, External UWO The Computer Science Department 33
Content coupling: Occurs when one component surreptitiously modifies data that is internal to another component • To reduce content coupling you should therefore encapsulate all instance variables —declare them private —and provide get and set methods • A worse form of content coupling occurs when you directly modify an instance variable of an instance variable UWO The Computer Science Department 34
Content Coupling: Changing Local Variables One function changing local variables of another function • Assumes that functions have their own local data • This is the case in Fortran, C, etc. • Not really possible in O-O languages since data associated with object, not functions Disadvantage: if f changes g’s local variables, then changing f often requires changing g or vice versa • Have to keep both in mind when changing either Note, not the same as one object changing attributes of another in an O-O language • Data is held within an object instance • Can be OK if the changed object is designed to expect it UWO The Computer Science Department 35
Example of content coupling public class Line { private Point start, end; . . . public Point get. Start() { return start; } public Point get. End() { return end; } } public class Arch { private Line baseline; . . . void slant(int new. Y) { Point the. End = baseline. get. End(); the. End. set. Location(the. End. get. X(), new. Y); } } UWO The Computer Science Department 36
Common coupling Occurs whenever you use a global variable • All the components using the global variable become coupled to each other • A weaker form of common coupling is when a variable can be accessed by a subset of the system’s classes —e. g. a Java package • Can be acceptable for creating global variables that represent system-wide default values • The Singleton pattern provides encapsulated global access to an object UWO The Computer Science Department 37
Common Coupling: Global Variable Communication Functions communicating via global variables • One sets variable, another refers to value This is certainly possible in O-O languages • One static object contains all “global data” • This object’s attributes are set and referred to Disadvantage: consider debugging task: e. g. • Global variable count has gotten some strange value • Both f and g have been called • Which changed it to the strange value? • Must flip back and forth between f and g to find out • Are there other functions which change count • Have to keep whole program in mind when debugging UWO The Computer Science Department 38
Avoiding Common Coupling Don’t declare variables as global • Don’t keep them in some public-accessible global object either Pass them instead as parameters Pass them only to those functions which really need them This way: • We know which functions change the data • When there are problems with that data, we can ignore the functions which don’t change it UWO The Computer Science Department 39
Control coupling Occurs when one procedure calls another using a ‘flag’ or ‘command’ that explicitly controls what the second procedure does • To make a change you have to change both the calling and called method • The use of polymorphic operations is normally the best way to avoid control coupling • One way to reduce the control coupling could be to have a look-up table —commands are then mapped to a method that should be called when that command is issued UWO The Computer Science Department 40
Control Coupling: Selecting Different Behaviour A function expecting a parameter which selects for completely different behaviours Example 1: int test. Stack(int kind, Stack S) { if ( ((kind==1) && (S. num == 0)) || ((kind==2) && (S. num == MAX) ) ) return 1; else return 0; } What does test. Stack do? • Seems to do two completely different things kind is a “magic” parameter • Selects from one of the two behaviours • Can’t tell what value it should be without looking at code for test. Stack UWO The Computer Science Department 41
Control Coupling cont’d Better to have two functions and name them intuitively: int empty. Stack (Stack S) { if (S. num == 0) return 1; else return 0; } int full. Stack (Stack S) { if (S. num == MAXSTACK) return 1; else return 0; } Previous code worked fine (if called correctly) However, with new code: • It is clear from the function names what the functions do • Don’t have to guess at values of parameters UWO The Computer Science Department 42
Control Coupling: Another Example void print. Report (int which) { switch (which) { case 1: /*code for printing monthly financial report */ case 2: /*code for printing report on Web usage */ … } } Person coding a function which calls print. Report has to remember number, or go check print. Report code • Easier to remember function name than code number To avoid: • Break up functions doing two different things into individual ones with descriptive names UWO The Computer Science Department 43
Example of control coupling public routine. X(String command) { if (command. equals("draw. Circle") { draw. Circle(); } else { draw. Rectangle(); } } Question: What OO concept should we be using to avoid control coupling like the example above? UWO The Computer Science Department 44
Stamp coupling: Occurs whenever one of your application classes is declared as the type of a method argument • Since one class now uses the other, changing the system becomes harder —Reusing one class requires reusing the other • Two ways to reduce stamp coupling, —using an interface as the argument type —passing simple variables UWO The Computer Science Department 45
Coupling Error Stamp Coupling: Using Only a Piece A function using only a small part of a parameter Example: code for finding how much income tax to deduct from employee’s salary: int income. Tax. Payable(Person p) { … /* code which refers to only p. salary */ } • Function header leads us to believe that: —income. Tax. Payable uses all of p —We have to keep all of the Person fields in mind when debugging income. Tax. Payable Better: Question: How can we fix the above situation? int income. Tax. Payable(int salary) { … /* code which refers salary */ } • Call would be income. Tax. Payable (employee. salary) rather than income. Tax. Payable(employee) • Shows clearly that income. Tax. Payable is concerned only with the employee’s salary If the calling function can extract all that is needed for the called function, it should UWO The Computer Science Department 46
Example of stamp coupling public class Emailer { public void send. Email(Employee e, String text) {. . . } Using simple data types to avoid it: public class Emailer { public void send. Email(String name, String email, String text) {. . . } UWO The Computer Science Department 47
Example of stamp coupling Using an interface to avoid it: public interface Addressee { public abstract String get. Name(); public abstract String get. Email(); } public class Employee implements Addressee {…} public class Emailer { public void send. Email(Addressee e, String text) {. . . } UWO The Computer Science Department 48
Data coupling Occurs whenever the types of method arguments are either primitive or else simple library classes • The more arguments a method has, the higher the coupling —All methods that use the method must pass all the arguments • You should reduce coupling by not giving methods unnecessary arguments • There is a trade-off between data coupling and stamp coupling —Increasing one often decreases the other UWO The Computer Science Department 49
Routine call coupling Occurs when one routine (or method in an object oriented system) calls another • The routines are coupled because they depend on each other’s behaviour • Routine call coupling is always present in any system. • If you repetitively use a sequence of two or more methods to compute something —then you can reduce routine call coupling by writing a single routine that encapsulates the sequence. UWO The Computer Science Department 50
Routine call coupling, what can we do? Assume we have methods: aaa, bbb, ccc, and ddd, what could we do to help with the routine call coupling below? private int aaa( …) { …//more code ccc(); ddd(); ccc(); …//more code } private int bbb( …) { ccc() ddd(); ccc(); …//more code ccc(); ddd(); ccc(); …//more code } UWO private int eee() { ccc() ddd(); ccc(); } private int aaa( …) { …//more code eee(); …//more code } private int bbb( …) { eee() …//more code eee(); …//more code } The Computer Science Department 51
Type use coupling Occurs when a module uses a data type defined in another module • It occurs any time a class declares an instance variable or a local variable as having another class for its type. • The consequence of type use coupling is that if the type definition changes, then the users of the type may have to change • Always declare the type of a variable to be the most general possible class or interface that contains the required operations UWO The Computer Science Department 52
Inclusion or import coupling Occurs when one component imports a package • (as in Java) or when one component includes another • (as in C++). • The including or importing component is now exposed to everything in the included or imported component. • If the included/imported component changes something or adds something. —This may raises a conflict with something in the includer, forcing the includer to change. • An item in an imported component might have the same name as something you have already defined. UWO The Computer Science Department 53
External coupling When a module has a dependency on such things as the operating system, shared libraries or the hardware • It is best to reduce the number of places in the code where such dependencies exist. • The Façade design pattern can reduce external coupling UWO The Computer Science Department 54
Questions Categorize the following aspects of a design by the types of coupling they exhibit: • Class Course. Section has public class variables called min. Class. Size and max. Class. Size. These are changed from time to time by the university administration. Many methods in classes Student and Registration access these variables. • A user interface class imports a large number of Java classes, including those that draw graphics, those that create UI controls and a number of other utility classes. • A system has a class called Address. This class has 4 public variables constituting different parts of an address. Several different classes, such as Person and Airport manipulate instances of this class, directly modifying the fields of address. Also, many methods declare one of their arguments to be an Address UWO The Computer Science Department 55
Code Without Coupling Errors Characteristics of code without coupling errors: • Functions have low number of parameters • Each parameter has an intuitive name and meaning • Function uses all and only the data in the parameters This is “data coupling”: a good thing We sometimes say that: • Functions with coupling errors have high coupling because they are very dependant on one another • Functions without coupling errors have low coupling because they are relatively independent We therefore want low coupling between functions UWO The Computer Science Department 56
Code Without Cohesion Errors Characteristics of code without cohesion errors: • Functions are relatively small • Function names have clear intuitive meaning • Functions actually do all and only what their names suggest Referred to as “functional cohesion”: a good thing We sometimes say that: • Functions with cohesion errors have low cohesion, they don’t hang together very well • Functions without cohesion errors have high cohesion, they hang together well We want code with: • Low coupling between functions • High cohesion within function UWO The Computer Science Department 57
Detailed Design • • Decomposing Functions Coupling errors Cohesion errors Example of breaking up a function
Decomposing Functions One of the main problems we face: How do you break up the task of coding a large system into smaller tasks? We want to end up with functions (methods, procedures, etc) which are • Conceptually simple: —So we can keep the main concepts in mind • Conceptually separate from others —So we don’t have to think too much about other functions when designing/writing this one If done this way: • Each module can be coded more easily • Modules can be coded either —One by one by the same person, OR —Simultaneously by more than one person UWO The Computer Science Department 59
Characteristics of Ideal Functions We can identify some characteristics that functions should ideally have: • Functions should not be too long —Long functions tend to be harder to debug, since we can’t easily find where in the function something is done —How long is too long? - Depends on the functions - 2 pages (120 lines) is almost certainly too long - More than this only justified if function has some simple high-level structure, e. g. a big switch statement • Functions should have a clear unifying concept —This leads to a clear function name which: - Describes all and everything the function does - Does not conceal any of the task of the function —Allows us to know exactly what function to go to when debugging UWO The Computer Science Department 60
Characteristics of Ideal Function cont’d • Functions should have relatively few parameters —Functions with a large number of parameters are very picky to call correctly —Also, functions with a large number of parameters are usually trying to do too many things —How many parameters is too many? - Depends on the function - 8 parameters is almost certainly too many • Parameters should have a clear purpose in the function —Otherwise, hard to tell how to call the function just from the header and comments —Parameters with a clear purpose can be given parameter names which describe their exact roles in the function UWO The Computer Science Department 61
Straying from the Ideal Code can usually get away from these ideals for various reasons • Usually as a result of problems we encounter in coding Example: function can’t do everything we wanted it to do without an extra parameter • Typical solution: —Slap on the extra parameter —If calling function needs the parameter to be able to pass it on to this one, then slap it on there too • Another simple solution: —Define a global variable —Functions now harder to debug since global variable linkage is hidden Example: function needs more code than we expected • Typical simple solution: just let the function grow and grow Example: we realize we have to break up a function • Typical simple solution: break it up into 2 or 3 pieces, without a clear purpose to any one piece UWO The Computer Science Department 62
Example of a Poorly Designed Function See program filesplt. c on the Class notes web page • Public domain Linus program which can: —Split a file into smaller files (Why do you think this program was written? Who might use it? ) —Rejoin pieces • Pieces of file myfile. dat (e. g. ) are put in files name myfile. 001, myfile. 002, etc. • Information for reconstructing original file put in file named myfile. 000, including original length Consider function join (lines 175 -464) • Joins pieces of a file together again (reconstructs file) • Header: void join (struct easy *way); • Obscure struct and parameter names, but not many parameters • However, 289 lines (about 5 pages) – way too long Code should have been split up in some intelligent way • We will get back to this soon UWO The Computer Science Department 63
Ultimate Result of Poor Design: Code Meltdown Code can “melt down” into jumbled mess, making it: • Difficult to debug and add features to • Difficult to even trace what is happening We can avoid code meltdowns by acting proactively Build high-level and detailed design in which: • Tasks already broken up into reasonable-sized subtasks • Functions are conceptually simple • Functions are conceptually separate from others While coding, if we find that some code is melting down: • Don’t just make a quick fix • Step back and redesign (“refactor”) that part • May be able to salvage some code in new design Key concepts in preventing and correcting code meltdown: • Coupling • Cohesion UWO The Computer Science Department 64
Cohesion Errors We will look at several kinds of errors in cohesion: • Function with no real unifying concept (no functional cohesion, only coincidental cohesion) WORST! • Function performs several related but distinct actions (logical cohesion) • Functions which perform a series of actions related only by the time we need to do them (temporal cohesion) Often arise from the need to break up a large function into several or many small ones UWO The Computer Science Department 65
Breaking up a Function: Example Consider function join in filesplt again • How to break it up? Algorithm: • Allocate (possibly large) buffer (lines 196 -210) • Eliminate extension of file name (212 -224) • Extract information from file fname. 000: original file name, length, etc. —Try to open the file (228 -264) —If we can open, extract all the information (265 -315) • Write the rejoined file —Open the file which will contain the rejoined data (316 -362) —For each file containing a piece of the data: - Copy that piece into the output file, maintaining length, etc. (364407) —Close the output file (409 -410) —Verify that length, etc. agrees with original (415 -446) —Write out a report about what has happened (449 -462) UWO The Computer Science Department 66
Some Bad Ways of Breaking Up join One bad way: • Put lines 196 -315 in one functions (about 2 pages long) • Put rest of lines (316 -462) in another function (a little over 2 pages long • First function has no clear unifying concept (allocates buffer, eliminates extension, extracts info from fname. 000) —Cohesion error Procedural Cohesion (we can do better!) • Second function has clear unifying concept (writes rejoined file), but still too long Other bad ideas in breaking up the function: • Pass each of the 6 pieces of information extracted from the. 000 file back to join as a separate parameter —Too many parameters Data Coupling Error • Pass entire way structure to called functions —Too much irrelevant data in way Stamp Coupling Error UWO The Computer Science Department 67
One Possible Good Way of Breaking Up join function pseudocode • Allocate buffer in buf (allocate. Buffer) • Let basename = filename with extension (extract. Base. Name) • Extract information from. 000 file (extract. Info) • If previous operation succeeded: —If output file specified, open output file —Otherwise, open original filename —Rejoin file from pieces and verify (rejoin. Verify. File) Header for called functions • char *allocate. Buffer() • char *extract. Base. Name(char *filename) • void extract. Info (char *basename, File. Info *file. Info, int *success); • void rejoin. Verify. File(char *basename, File. Info *file. Info, char *buf, FILE *output. File); UWO The Computer Science Department 68
Breaking Up join cont’d Pseudocode for rejoin. Verify. File: • Let fnumber = 1, success = 1 • While fnumber <= num. Files and still success: —Construct input. Filename using basename and fnumber (construct. Filename) —Try opening input. File (try. Open) —If open successful, - Copy bytes from input. File to output. File, updating length, etc. (copy. Bytes) - Increment fnumber —Else, let success = 0 • If success, verify that length, etc. is consistent with file. Info (verify. Length. Etc) • Write report Headers for called functions: • char *construct. Filename (char *base. Name, int fnumber); • FILE *try. Open(char *filename, int *success); • void copy. Bytes(FILE *in. File, FILE *out. File, int *length, int The Computer Science Department *checksum); UWO 69
Breaking Up join cont’d If we did things as suggested above: • 9 functions instead of 1 • Each function has clear purpose, parameters • No function would be over a page • Would need an extra definition for the File. Info type —However, this type encapsulates a lot of information —Very useful, promotes low coupling, high cohesion —USED MAINLY FUNCTIONAL COHESION! Your mileage may vary • Feel free to dispute the choices made above • Many other ways of breaking up would be equally valid • Leaving it as it is would certainly cause debugging problems UWO The Computer Science Department 70
Design Principle 4: Keep the level of abstraction as high as possible Ensure that your designs allow you to hide or defer consideration of details, thus reducing complexity • A good abstraction is said to provide information hiding • Abstractions allow you to understand the essence of a subsystem without having to know unnecessary details © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 71
Abstraction and classes Classes are data abstractions that contain procedural abstractions • Abstraction is increased by defining all variables as private. • The fewer public methods in a class, the better the abstraction • Superclasses and interfaces increase the level of abstraction • Attributes and associations are also data abstractions. • Methods are procedural abstractions —Better abstractions are achieved by giving methods fewer parameters © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 72
Design Principle 5: Increase reusability where possible Design the various aspects of your system so that they can be used again in other contexts • Generalize your design as much as possible • Follow the preceding three design principles • Design your system to contain hooks • Simplify your design as much as possible © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 73
Design Principle 6: Reuse existing designs and code where possible Design with reuse is complementary to design for reusability • Actively reusing designs or code allows you to take advantage of the investment you or others have made in reusable components —Cloning should not be seen as a form of reuse © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 74
Design Principle 7: Design for flexibility Actively anticipate changes that a design may have to undergo in the future, and prepare for them • Reduce coupling and increase cohesion • Create abstractions • Do not hard-code anything • Leave all options open —Do not restrict the options of people who have to modify the system later • Use reusable code and make code reusable © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 75
Design Principle 8: Anticipate obsolescence Plan for changes in the technology or environment so the software will continue to run or can be easily changed • Avoid using early releases of technology • Avoid using software libraries that are specific to particular environments • Avoid using undocumented features or little-used features of software libraries • Avoid using software or special hardware from companies that are less likely to provide long-term support • Use standard languages and technologies that are supported by multiple vendors © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 76
Design Principle 9: Design for Portability Have the software run on as many platforms as possible • Avoid the use of facilities that are specific to one particular environment • E. g. a library only available in Microsoft Windows © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 77
Design Principle 10: Design for Testability Take steps to make testing easier • Design a program to automatically test the software —Discussed more in Chapter 10 —Ensure that all the functionality of the code can by driven by an external program, bypassing a graphical user interface • In Java, you can create a main() method in each class in order to exercise the other methods © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 78
Design Principle 11: Design defensively Never trust how others will try to use a component you are designing • Handle all cases where other code might attempt to use your component inappropriately • Check that all of the inputs to your component are valid: the preconditions —Unfortunately, over-zealous defensive design can result in unnecessarily repetitive checking © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 79
Design by contract A technique that allows you to design defensively in an efficient and systematic way • Key idea —each method has an explicit contract with its callers • The contract has a set of assertions that state: —What preconditions the called method requires to be true when it starts executing —What postconditions the called method agrees to ensure are true when it finishes executing —What invariants the called method agrees will not change as it executes © Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 80
- Slides: 80