CSC/ECE 517 Fall 2011/ch1 1e sm

From Expertiza_Wiki
Jump to navigation Jump to search

This article briefs about how Object-oriented Programming came into being after Structured Programming prevailed for years and it compares and contrasts the various aspects of these two programming approaches. It sheds some light on the popular belief that Object-oriented technology will alleviate some of the problems associated with structured approaches.

Evolution from Structured to Object oriented Programming

Programmers since the 1970s have embraced a style called structured programming. As with earlier "spaghetti code," computer programmers still used such concepts as variables, assignments to variables, expression construction, and function evaluation. Typically, those programmers spent long hours designing, coding, and debugging programs. Structured techniques, such as the use of subroutines rather than GOTOs, resulted in improved development time lines and increased supportability. Although improved over prior coding techniques, structured programmers found that they usually could not reuse routines already coded for earlier programs. In 1967 the first Object oriented Programming language, SIMULA-67, was introduced which had several unique ways of coding subroutines with improved potential for reuse. Current Object oriented Programming languages such as Java (derived from C++) and Smalltalk share commonalities with traditional structured programming languages such as C and COBOL while adding in the ideas first developed in the 60s. Despite the many commonalities, object-oriented programming is significantly different from structured programming.

Structured programming is suitable for small programs but for large programs, structured programming can produce cumbersome code with large amounts of data. With structured programming in large programs, for a small change, multiple subprograms will have to be changed. On the other hand, object-oriented approach is more flexible, by separating a program into a network of subsystems, with each controlling their own data, algorithms, or devices across the entire program.

The Object-Oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program. The data is accessed by calling specially written functions, commonly called methods. The programming construct that combines data with a set of methods for accessing and managing those data is called an object.

An object-oriented program will usually contain different types of objects, each type corresponding to a particular kind of complex data to be managed or perhaps to a real-world object or concept. An object-oriented program may thus be viewed as a collection of interacting objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform. Object-Oriented programming can lessen the gap between the programmer models and the application domain being modeled.<ref>Structured Programming</ref>

Comparison

Abstraction

In structured programming, data and functions (or procedures) are separate. The data (e.g., employees, orders, or sales records) is essentially passed to functions (e.g., print, display, add, change, and delete routines) that act on the data as required. Thus the functions can work on data from different parts of the program. If we do not know what data a function might manipulate and when, any changes we make to that function could affect a program in unpredictable ways. This makes the task of modifying and fixing the code harder.

Object oriented programming can partially solve this problem by organizing data, and all the subprograms that manipulate that data, into a single location, or an object. In other words this means that the data and functions are integrated into data structures called classes. Encapsulation is used to package data with the functions that act on the data. The declaration of such an encapsulated unit is called a class, which refers to an abstract view of objects in the real world. Object-oriented programs typically restrict the programmer from haphazard access to the data. If a programmer using an object wishes to, for example, display or change the data, the only way of doing so is via a controlled access mechanism (a method of the class). A programmer writing a control routine in the main part of a program using Object-oriented Programming techniques simply sends a message to the object asking it to print, display, or change its data. All of the methods written with the class have open access to the data associated with an object of that class, but no part of a program constructed in the future, outside of the object, can change the data thereby possibly introducing mistakes or errors in the program. As Clarkson put it, "objects manipulate themselves; nothing reaches inside and stirs their contents around". These features allow us to easily modify and fix the code.<ref>Beginning Programming All-In-One Desk Reference For Dummies</ref>

The following is a simple example that demonstrates encapsulation in Object oriented programming:

public class Box {
private int length;
private int width;
private int height;
public int getLength() {
     return length;
}
public void setLength(int length) {
     this.length = length;
}
public int getWidth() {
     return width;
}
public void setWidth(int width) {
     this.width = width;
}
public int getHeight() {
     return height;
}
public void setHeight(int height) {
     this.height = height;
}
}

Reusability

Reusability is achieved in Object Oriented programming through Inheritance. Inheritance is when one class inherits, or absorbs, the same fields and methods of another class, and adds necessary methods and fields to the new class. This lets developers maximize the use of application objects. In inheritance mechanism, data structures and behaviors are inherited. Without inheritance, every subclass would have to write the exact same fields and methods (because that class requires those fields and methods), which is time consuming and inefficient. Developers can implement inheritance in two modes: single and multiple. Single inheritance allows the inheritance of information from a single object/class, whereas multiple inheritance allows objects to inherit information from two objects/classes simultaneously. The more software you can borrow from others and incorporate in your own programs, the less you have to do yourself. There's more software to borrow in an object-oriented programming environment, because the code is more reusable. Collaboration between programmers working in different places for different organizations is enhanced, while the burden of each project is eased. Classes and frameworks from an object-oriented library can make inheritance possible.

In structured programming, subroutines are written for and can be used only to perform a specific task. They cannot be reused when the task at hand is different or an extension of the functionality for which that particular function was written.

As an example of a Base class we can consider the following Bicycle class:

public class Bicycle {
        
    public int cadence;
    public int gear;
    public int speed;
        
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }   
    public void setCadence(int newValue) {
        cadence = newValue;
    }   
    public void setGear(int newValue) {
        gear = newValue;
    }   
    public void applyBrake(int decrement) {
        speed -= decrement;
    }    
    public void speedUp(int increment) {
        speed += increment;
    }
       
}

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:

public class MountainBike extends Bicycle 
{      
    public int seatHeight;
    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }   
    public void setHeight(int newValue) {
        seatHeight = newValue;
    }   
}

There are some other added benefits of reusability such as:

  • Reliability: The increased reusability of object-oriented code also increases its reliability. A class taken from a library is likely to have found its way into a variety of different applications and situations. The more the code has been used, the more likely it is that problems will have been encountered and fixed. Bugs that would have seemed strange and hard to find in your program might already have been tracked down and eliminated.
  • Efficiency: The component developers are likely to be experts in their field and will have used the best possible algorithms and data structures.
  • Time Savings: By relying upon existing components there is less software to develop and hence applications can be built quicker.
  • Decreased maintenance effort: Using others' components decreases the amount of maintenance effort that the application developer needs to expend. The maintenance of the reused components is the responsibility of the component supplier.
  • Consistency: Reliance on a library of standard components will tend to spread a consistency of design message throughout a team of programmers working on an application. The library is the basis of a standard that will lend coherency and conformity to the design process.
  • Investment: Reusing software will save the cost of developing similar software from scratch. The investment in the original development is preserved if the developed software can be used in another project. The most reusable software tends to be that produced by the best developers. Reusing software is thus a way of preserving the knowledge and creations of the best developers.

Focus

Another major difference is that in structured programming functions are the primary focus of design. Data is of secondary importance. The structured programming approach results in many different parts of a program which have access to the data. The main control routine and any sub-routine may be coded to access the data directly, change it, and inadvertently introduce mistakes. If one programmer changes the representation of the data in the computer's memory by re-arranging fields within a record, other sub-routines in the program may need to be re-written and must then be re-tested to account for this change.

The Object-oriented Programming approach reverses the emphasis of data and functions used in structured programming. In Object-oriented Programming, programs pass messages to object methods that are conceptually packaged with an object's data. Object-oriented programming requires the analyst, designer and programmer to focus on objects rather than actions. This is a fundamental change from structured tools that focused on desired program actions with data playing a role in the shadows. Rosson and Alpert contrast the differences between conventional structured programming languages and OOP this way:

"Rather than invoking procedures to act on passive data, messages evoke object activity: A message sent to an object is a specification of some action, a request for the object to exhibit some behavior, or to supply some information. The action taken by the object is a function of its interpretation of the message and its internal state."<ref>Structured Programmers Learning Object-Oriented Programming</ref>

Polymorphism

Polymorphism allows an object to be processed differently by data types and/or data classes. More precisely, it is the ability for different objects to respond to the same message in different ways. It allows a single name or operator to be associated with different operations, depending on the type of data it has passed, and gives the ability to redefine a method within a derived class.

For example, given the student and business subclasses of customer in a banking system, a programmer would be able to define different getInterestRate() methods in student and business to override the default interest getInterestRate() that is held in the customer class.

Also, in OOP, polymorphism permits the program to decide at run-time which of like-named methods derived from the same base class is the appropriate one to execute. Using this technique, also referred to as late-binding, a program coded to land "flying vehicles" can correctly land such flying vehicles as airplanes and helicopters without the need for traditional if-else or switch-case logic.

Polymorphism cannot be implemented in structured programming. Considering the same customer class example mentioned above, in structured programming, we would have to implement two different methods for computing the interest, one for the student and another for the businessman.

The following is an example of polymorphism exhibited in the constructors of a class

public class Website {

 String name;
 String url;
 String description;
 
 public Website(String n, String u, String d) {
   name = n; 
   url  = u;
   description = d;
 }

 public Website() {
   name = ""; 
   url  = "";
   description = "";
 }

}

Analysis and Design Differences

In structured programming, while analysis starts with a consideration of real-world problems, the real-world focus is lost as requirements are transformed into a series of data flow diagrams which is the intermediate step before the design stage. When program design takes place, the process has distanced itself from the real world. The design stage culminates in the creation of structure charts and detailed logic diagrams. By the time the programming team goes to work, they are no longer focused on the real-world objects being emulated.

In contrast, using object-oriented analysis, design, and programming techniques, the focus remains on the real-world objects throughout the development cycle. There is an overlap between each of the three development steps. The analyst and the programmer are both interested in development of usable (and reusable) objects. These programming objects (referred to as class declarations), once tested and made available to other programmers, do not have to be retested and redesigned every time changes are made to the data layout.

What is a better choice

Whether we use object oriented or structured programming depends partly on our choice of language, but also on our design. For example, the C language doesn’t offer any features for object oriented programming, but with enough discipline we can still write object-oriented code in C, such as the GTK windowing library. On the other hand, we can write a Java program that completely fails to take advantage of Java’s OOP features, by putting all of our code in a single class and using classes with public members just as we would use structs in C.

The differences between Structured and Object-oriented Programming are briefed below:<ref>Software Development and Object-Oriented Programming Paradigms</ref>

Structured Programming Object-Oriented Programming
Approach Top-down approach is followed Bottom-up approach is followed
Focus Focus is on algorithm and control flow. Focus is on object model.
Program Organization Program is divided into a number of sub modules, or functions, or procedures. Program is organized by having a number of classes and objects.
Design Functions are independent of each other. Each class is related in a hierarchical manner.
Function Call No designated receiver in the function call. There is a designated receiver for each message passing.
Data/methods Views data and functions as two separate entities. Views data and function as a single entity.
Maintenance Maintenance is costly. Maintenance is relatively cheaper.
Reusability Software reuse is not possible. Helps in software reuse.
Passing Arguments Function call is used. Message passing is used
Abstraction Function abstraction is used. Data abstraction is used.
Algorithm/Data Algorithm is given importance. Data is given importance.
Domain Solution is solution-domain specific. Solution is problem-domain specific.
Encapsulation No encapsulation. Data and functions are separate. Encapsulation packages code and data altogether. Data and functionalities are put together in a single entity.
Programmer Relationship between programmer and program is emphasized. Relationship between programmer and user is emphasized.
Technique Data-driven technique is used. Driven by delegation of responsibilities.

References

<references> </references>


Further Reading

1. Peter Wegner, "Concepts and paradigms of object-oriented programming"

2. Luiz Fernando Capretz, "A brief history of the object-oriented approach"

3. OOP Sample

4. http://askville.amazon.com/Compare-Contrast-Structured-programming-Object-Oriented/AnswerViewer.do?requestId=2470573

5. Leonard H.Weiner(1978-02-01) "The roots of structured programming"

6. Edsger Dijkstra, "Notes on Structured Programming"