1 / 53

COSC3557: Object-Oriented Programming

COSC3557: Object-Oriented Programming. Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University. Lecture 10. Frameworks and Object Interconnections Ref. : Chapters 21 & 23. Framework. What is a Framework?.

Download Presentation

COSC3557: Object-Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University

  2. Lecture 10 • Frameworks and Object Interconnections • Ref. : Chapters 21 & 23

  3. Framework

  4. What is a Framework? • In software development, a framework is a defined support structure in which another software project can be organized and developed. A framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. • Frameworks are designed with the intent of facilitating software development, by allowing designers and programmers to spend more time on meeting software requirements rather than dealing with the more tedious low level details of providing a working system. • For example, a team using Apache Struts to develop a banking web site can focus on how account withdrawals are going to work rather than how to control navigation between pages in a bug-free manner. • However, there are common complaints that using frameworks adds to "code bloat", and that a preponderance of competing and complementary frameworks means that one trades time spent on rote programming and design for time spent on learning frameworks. • Outside of computer applications, a framework can be considered as the processes and technologies used to solve a complex issue. It is the skeleton upon which various objects are integrated for a given solution.

  5. The Tension between Reuse and Specialization • A truly general purpose tool cannot contain features specific to any one application • Solving most problems requires application specific features • How do you bridge the gap between general purpose and application independent tools and an application that will solve a real problem?

  6. Reuse of Code, Reuse of Concept • The solution comes from the two ways we have been using inheritance from the beginning of the book. • Reuse of code. Certain methods, call foundation methods, are defined in a general purpose class. These provide functionality that is common to many applications. • Reuse of concepts. Other methods, called specialization methods, are defined in a parent class, but overridden in child classes. These provide the means to specialize an application to a new situation.

  7. A Simple Example, a GUI System • A simple example might be a framework for user interfaces: • Class Window: methods • foundation: setTitle, setWindowSize, moveWindowTo, addMenu, repaint • specialization: mouseDown, keyPress, paint • class Childwindow: methods • paint, mouseDown, keyPress • The foundation method are applicable to any type of window. The deferred specialization methods are appropriate only to one type of application.

  8. Deferred Methods, Two Views of the Same Thing • By working with deferred methods, the application class views the application in one way, and the child class in another.

  9. Reuse of High Level Abstractions • Software frameworks provide a different type of reuse: • Conventional libraries of procedures provide a means for reuse of low level abstractions (I/O libraries, math functions, and so on). • Software frameworks provide a means for reuse of high level abstractions, and still allow them to be specialized for new situations.

  10. An Example of a Low Level Abstraction • Suppose we want to sort employee records. We could write the following. • class Employee { • public: • string name; • int salary; • int startingYear; • }

  11. Sorting Employee Records • void sort (Employee * data[ ], int n) { • for (int i = 1; i < n; i++) { • int j = i-1; • while (j >= 0 && • v[j+1]->startingYear < v[j]->startingYear) { • // swap elements • Employee * temp = v[j]; • v[j] = v[j+1]; • v[j+1] = temp; • j = j - 1; • } • } • } • But what happens if we want to change it?

  12. Types of Reuse • We can reuse the idea of a merge sort, but cannot reuse the binary without modifications to the original source code. • Might want to sort on salary, instead of starting year • Might want to do comparisons of string (e.g., name), not integers • Might want to sort a different type of structure • To create an object-oriented software framework, we must first ask ourselves what are the likely sources of change?

  13. A Sorting Framework • class InsertionSorter { • public: • void sort () { • int n = size(); • for (int i = 1; i < n; i++) { • int j = i - 1; • while (j >= 0 && lessThan(j+1, j)) { • swap(j, j+1); • j = j - 1; • } • } • } • private: • virtual int size() = 0; // abstract methods • virtual boolean lessThan(int i, int j) = 0; • virtual void swap(int i, int j) = 0; • } • The part that is common in made into a foundation method, the part that changes are made into deferred methods.

  14. Specializing the Sorting Framework • To apply the framework to a new problem, we subclass and override the deferred methods: • class EmployeeSorter : public InsertionSorter { • public: • EmployeeSorter (Employee * d[], int n) • { data = d; sze = n; } • private: • Employee * data[]; • int sze = n; • virtual int size () { return sze; } • virtual bool lessThan (int i, int j) • { return data[i]->startingYear < data[j]->startingYear; } • virtual void swap (int i, int j) { • Employee * temp = v[i]; • v[i] = v[j]; • v[j] = temp; • } • } • We can now reuse the high level algorithm without making any change to the original source code!

  15. An Upside Down Library ConventionalProgram Program built usingA Framework

  16. Not Just One Class • A framework is not always just one class. Often, a framework is a collection of many classes. For example, a typical GUI framework might have • Window classes • Button or scroll bar classes • Text box classes • All can be specialized by the combination of foundation methods for overall structure, and deferred methods for specialization.

  17. Flexibility and Rigidity • A framework can be tremendously helpful in allowing a programmer to rapidly create new application, but only when the application fits into the general structure envisioned by the creator of the framework. • If an application falls outside that framework, then it can be very difficult to overcome the framework. • For example, if the designer of the framework has not encapsulated the right sources of variation in a method, or has forgotten to declare a method as virtual, then it can be very difficult to work with.

  18. An Example Framework, The Java Applet API • The Java Applet API is one simple example of a software framework. • init() Invoked when the applet is initialized • start() Invoked to start the application • paint(Graphics) Invoked to repaint the window • stop() Invoked when the applet is halted • destroy() Invoked when the applet is terminated • Lots of other classes for constructing buttons and menus, and so on. • //HelloApplet.java, app.html

  19. A Generalized Event Driven Simulation Framework • A generalized discrete event-driven simulation can be formed based around the class Event: • class Event { • public: • Event (unsigned int t) : time(t) { } • const unsigned int time; • virtual void processEvent () = 0; • }; • class eventComparison { • public: • bool operator () (Event * left, event * right) • { return left->time > right->time; } • }; • An event is an action that will take place at a specific time.

  20. The Simulation Class • class Simulation { • public: • Simulation () : eventQueue(), currentTime(0) { } • void scheduleEvent (event * newEvent) { eventQueue.push (newEvent); } • void run(); • unsigned int currentTime; • protected: • priority_queue<vector, eventComparison> eventQueue; • }; • void Simulation::run() { • // execute events until event queue becomes empty • while (! eventQueue.empty()) { • Event * nextEvent = eventQueue.top(); • eventQueue.pop(); • currentTime = nextEvent->time; • nextEvent->processEvent(); • delete nextEvent; • } • }

  21. A Framework Example: Eclipse SWT SWT Programming with Eclipse http://www.developer.com/java/other/article.php/10936_3330861_1

  22. import org.eclipse.swt.layout.RowLayout; • import org.eclipse.swt.widgets.Display; • import org.eclipse.swt.widgets.Shell; • public class SliderExample • { public static void main(String args[]) • { • Display display = new Display(); • Shell shell = new Shell(display); • shell.setLayout( new RowLayout()); • // ------------------------ • // Your code comes to here. • // ------------------------ • shell.pack(); • shell.open(); • while( !shell.isDisposed()) • { • if(!display.readAndDispatch()) • display.sleep(); • } • display.dispose(); • } • }

  23. Summary of Framework • A framework is a way of organizing classes so as to solve a class of related problems • The framework balances software reuse and the ability to specialize a tool to a new application • The framework achieves this by combining inheritance of code and inheritance of concept (overriding). • Frameworks can be developed for any application where you can extract and generalize the ways in which code will change. • Frameworks are great if your new application fits the scheme of the designed, but very inflexible if it does not.

  24. Object interconnections

  25. Connections • The Bane of Large Scale Programming • Difficulties in developing large scale programs are often not so much a matter of algorithmic complexity as they are of communication complexity. • If several programmers are working together on a project, need to control the amount of information one programmer must have about the code being developed by a second programmer.

  26. Visibility • Visibility is an attribute of names. • Names of variables, functions, fields, whatever. • If you can't name something, you can't manipulate it. • Languages already have a variety of mechanisms for the control of name visibility. • OOP languages introduce a few new twists.

  27. Dependency • Dependency describes the degree to which one software component relies on another component to perform its responsibilities. • A high degree of dependency obviously limits code reuse - moving one component to a new project.

  28. Coupling and Cohesion • Ideas from the Software Engineering Community, pre-dating OOP. • Coupling refers to the extent to which one component uses another to perform actions. Generally a goal is to reduce coupling between software. • Cohesion refers to the extent to which the actions of a component seem to be tied together in purpose. Generally a goal is to increase cohesion within a software component.

  29. Varieties of Coupling • Arranged from Bad to Better • Internal data coupling • Global data coupling • Control (or sequence) coupling • Component coupling • Parameter coupling • Subclass coupling

  30. Internal Data Coupling class Person { public: Person () { name = "Larry"; } string name; }; • class SneekyModifier { • public: • void sneeky () { • // change my friends name • myFriend->name = "Lucy"; • } • Person * myFriend; • }; • This is bad because it makes it difficult to understand a single class in isolation. • Can be mitigated by always making your data areas private or protected, and not exposing pointers to these areas.

  31. Global Data Coupling • double todaysDow; • class One { • public: • void setDow () { • todaysDow = 9473; • } • }; • Two or more classes that interact through a common global variable. Again, makes it difficult to understand a single class in isolation. • Can be mitigated by making a class that ``manages'' the global area, thereby reducing global coupling to component coupling. class Two { public: void printDow () { cout << "Today the Dow hit " << todaysDow; } };

  32. Control, or Sequence Coupling • A form of coupling in which one component affects the sequence of execution in another • Solutions: • having the callers of the routine directly call the methods called in the second routine • the use of polymorphic operations • using a look-up table that maps a command to a method that should be called when that command is issued

  33. A Control Coupling Example • public routineX(Stringcommand){//routineX will have to change whenever any of its //callers adds a newcommandif (command.equals("drawCircle"){drawCircle();}else{drawRectangle();}}

  34. Component Coupling • Occurs when one class holds an instance of another class. • class Set { • ... • private: • List data; • } • Ideally, connection is one way. Held component has no knowledge of the holder. • This is a very weak and benign connection. (Weak is good, remember).

  35. Parameter Coupling • Parameter coupling occurs when one object knows of another only through being passed as a parameter or a return value. • Another very weak (and therefore good) type of coupling. • class MyClass { • public: • void doSomething (Set aSet) { • ... • } • }

  36. Subclass Coupling • Subclass coupling describes the relationship between a parent class and a child class. • Ideally the parent has no strong connection to the child, so the connection is one way. Can understand the parent in isolation from the child. • class Parent { • ... • } • class Child extends Parent { • ... • } • A very weak form of coupling. Which makes it a good design choice.

  37. Varieties of Cohesion • Also arranged from bad to better: • Coincidental cohesion: no apparent reasons • Logical cohesion: only logically connected • Temporal cohesion: • aspects of a system are grouped together which are used during the same phase of execution of a program, i.e. execute close together in time • Communication cohesion: • procedures that access the same data are kept together • Sequential cohesion: • a series of procedures, where one provides input to the next, are kept together • Functional cohesion: • modules which together perform a function (a computation that returns a result and has no side effects) are kept together, and everything else is kept out • Data cohesion: when a class is used

  38. Limiting Coupling - the Law of Demeter • The Law of Demeter is an attempt to limit the way in which one component can interact with another component. • Law of Demeter. In any Method M attached to a class C, only methods defined by the following classes may be used: • The instance variable classes of C. • The argument classes of method M (including C); note that global objects or objects created inside the method M are considered arguments to M.

  39. Law of Demeter (weak form). • Inside a method, it is only permitted to access or send messages to the following objects: • The arguments associated with the method being executed (including the self object). • Instance variables for the receiver of the method. • Global variables. • Temporary variables created inside the method.

  40. Law of Demeter (strong form). • Inside a method, it is only permitted to access or send messages to the following objects: • The arguments associated with the method being executed (including the self object). • Instance variables defined in the class containing the method being executed. • Global variables. • Temporary variables created inside the method.

  41. What is ruled out • Basically, what is ruled out by the law of Demeter is one object going in and directly manipulating the internal data values of another object. • Instead, all access to data values in another component should be made through procedures - thereby reducing data coupling to the weaker parameter coupling.

  42. Public, Subclass and Private Faces • We have several times noted that object have a public and private face - inheritance introduces a third alternative, the subclass face. • Public features are those aspects that users of the software component may have access to. • Private features are those aspects that the implementor of the software component must not have access to. • Protected features are those aspects that implementors of child classes can have access to. • There are two types of clients for the class developer. These are user clients (those who use an instance of the class), and subclass clients (those who will subclass from the class).

  43. Control of Visibility • The public/protected/private modifiers are the primary way to control visibility in most OO languages, the there are other mechanisms as well. • Friends in C++ • Inner classes in Java and C++ • Private Inheritance in C++ • Name Spaces, Units or Packages

  44. Friends in C++ • In C++ a friend (class or method) is allowed access to all parts of a class. • #include <iostream.h> • #include <string.h> • class Student; class Employee • { char id[8]; // ID number • float payRate; // pay rate • public: • Employee( char * idVal ) • { • strcpy( id, idVal); • id[7] =0; • payRate = 0.24f; • }; • friend class Student; • }; • //Friendship is something that is given away, not something that is taken.

  45. Example of Friend in C++ class Student { char id[8]; // ID number public: Student() { id[0] = '\0'; }; void getE1() {Employee e("xxxxxxx"); cout <<e.id<<endl <<e.payRate<<endl; } void getE2(Employee & e) {cout <<e.id<<endl <<e.payRate<<endl; } void main() { Employee E( "333445555" ); Student S; S.getE1(); S.getE2(E); }//ex9cfriend.cpp

  46. Properties of Friends • Not symmetrical • When c2 is a friend of c1, but c1 is not definitely a friend of c2, it depends on whether you define the friendship explicitly. • Not transitive • When c2 is a friend of c1 and c3 is a friend of c2, but c3 is not definitely a friend of c1, it depends on whether you define the friendship explicitly.

  47. Properties of Friends • Not inherited • A friend of a base class is not inherited by the derived classes.(Friend in Derived class, 6.1.6) • The friends of parents are not definitely friends of children.

  48. Eg: class Employee{ public: friend float CalcPay(Employee &E); //.. } class SalariedEmployee: public Employee{//... } //Here, the function CalcPay() can not access the private members of SalariedEmployee!!!

  49. Be careful to Friends • Friend make less coupled classes tightly coupled, which may results in many problems for error hunting and modularity. • Friend is the “killer” to encapsulation and information hiding. • Suggestion: Do not use “friend” if not necessary.

  50. Inner Classes • Inner classes in Java and, to a lesser extent, nested classes in C++ and C# are allowed to access the data areas in the surrounding class. • class AcontainerClass { • ... • // return an enumerator • public Enumeration elements() • { return new MyEnumeration(); } • ... • // inner class is allowed to see • // all aspects of surrounding class • private class MyEnumeration implements Enumeration { • ... • public boolean hasMoreElements () { ... } • public Object nextElement() { ... } • } • } • Uses a lot for event listeners in Java, among other things.

More Related