CSC/ECE 517 Fall 2011/ch1 1e sm: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(87 intermediate revisions by 2 users not shown)
Line 1: Line 1:
This article briefs about how [http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented Programming] came into being after [http://en.wikipedia.org/wiki/Structured_programming 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.<br>


This article briefs about how [http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented Programming] came into being after [http://en.wikipedia.org/wiki/Structured_programming 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.
== <b>Evolution from Structured to Object oriented Programming</b> ==


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, [http://en.wikipedia.org/wiki/Simula 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 [http://en.wikipedia.org/wiki/Smalltalk Smalltalk] share commonalities with traditional structured programming languages such as [http://en.wikipedia.org/wiki/C_%28programming_language%29 C] and [http://en.wikipedia.org/wiki/COBOL COBOL] while adding in the ideas first developed in the 60s. Despite the many commonalities, object-oriented programming is significantly different from structured programming.


==The Journey of Language Evolution==
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.
[[File:lanevo.png|600px|thumb|right|Language Evolution]]
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.  


<p>During the early days of programming language development, [http://en.wikipedia.org/wiki/Assembly_language assembly languages] dealt with code based on machine instructions ([http://en.wikipedia.org/wiki/Operator_(programming operators]) that manipulated the contents of memory locations ([http://en.wikipedia.org/wiki/Operands operands]). The level of control and [http://en.wikipedia.org/wiki/Data_abstraction data abstraction] achieved was very low. When the first higher-level languages appeared, the operators turned into [http://en.wikipedia.org/wiki/Statement_(programming) statements] and operands into [http://en.wikipedia.org/wiki/Variable_(computer_science) variables] and [http://en.wikipedia.org/wiki/Data_structures data structures]. These languages consisted of a collection of variables that represented some [http://en.wikipedia.org/wiki/Data_(computing) data] and a set of [http://en.wikipedia.org/wiki/Procedure_(computer_science) procedures] that manipulated those variables. The majority of traditional programming languages supported [http://en.wikipedia.org/wiki/Abstract_data_types abstract data types]. Thus there is no way to express the commonality between two abstract data types that are similar but not identical, in these languages that support only abstract data types. The [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented paradigm] went a step ahead by allowing the similarities and differences between abstract data types to be expressed through [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) inheritance], which is a key defining feature of the object-oriented paradigm.</p>
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>[http://en.wikipedia.org/wiki/Structured_programming Structured Programming]</ref>


== <b>Comparison</b> ==


<p>Thus the assembly languages were followed by [http://en.wikipedia.org/wiki/Procedural_programming procedural languages] such as [http://en.wikipedia.org/wiki/Fortran FORTRAN], [http://en.wikipedia.org/wiki/Algol Algol].. Procedural languages were then followed by structured programming languages. [http://en.wikipedia.org/wiki/Edsger_W._Dijkstra Dijkstra], Jacopini and Naur were the forefathers of structured programming. Dijkstra first discovered that modularized, goto-less programs were more efficient. Jacopini drew the conclusion that any program that could be converted to one of the following structures could be considered as a structured program</p>
=== <b>[http://en.wikipedia.org/wiki/Abstraction_(computer_science) Abstraction]</b> ===


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. 


<b>a) Sequential/Concatenation</b>
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. [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 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>[http://books.google.com/books?id=A71tgIY4BoMC&pg=PT59&lpg=PT59&dq=Reusability+in+structured+and+Object+Oriented+Programming&source=bl&ots=YPROMVi6qs&sig=6OG-I4TIbuUN2UUgtD47Vu7SS-o&hl=en&ei=T4J_TuvJAYW-tgfckb#v=onepage&q&f=false Beginning Programming All-In-One Desk Reference For Dummies]</ref>


[[File:seq.jpg]]
The following is a simple example that demonstrates encapsulation in Object oriented programming:


<b>b) Alternation/Selection</b>
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;
}
}


[[File:alt.jpg]]
=== <b>[http://en.wikipedia.org/wiki/Reusability Reusability]</b> ===
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.


<b>c) Iteration/Repetition</b>
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.


[[File:iter.jpg]]
As an example of a Base class we can consider the following Bicycle class:


<p>Dijkstra related the structure of the program text to the structure of the computations. According to him, the [http://en.wikipedia.org/wiki/Flowchart flowchart] of a program which represents the dynamic execution of the program statements also represents the logic of the text. By relation the logic and the structure, we can understand the working of a program more clearly. Dijsktra’s primitive structures – sequential, if-then statements (similar to alternation) and while-do, repeat-until(similar to iteration) are more or less the same as Jacopini’s base diagrams depicted above.
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;
    }
       
}


Dijkstra next came up with a general process flow for all programs:</p>
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
1.Read data<br>
2.Calculate Solution<br>
3.Print Results<br>


<p>These steps are repeated until the [http://en.wikipedia.org/wiki/Computer_program program] is converted to a form which can be easily compiled and executed. He proposed a “[http://en.wikipedia.org/wiki/Top-down_design top-down]” design to help establish correctness based on a block structured format. Programs with a block structure enabled several programmers to work concurrently and also enabled easier [http://en.wikipedia.org/wiki/Software_testing testing] and [http://en.wikipedia.org/wiki/Verification_and_Validation_(software) validation]</p>
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;
    } 
}


<p>[http://en.wikipedia.org/wiki/Simula Simula] was the first programming language that had [http://en.wikipedia.org/wiki/Object_(computer_science) objects] and [http://en.wikipedia.org/wiki/Class_(computer_programming) classes] as central concepts. It was the first language to introduce the concept of class and to allow inheritance to be expressed, and it should be recognized as the “mother” of a few object-oriented programming languages. Besides, because object-oriented concepts have also arisen from the [http://en.wikipedia.org/wiki/Artificial_intelligence artificial intelligence] community, it is not surprising that [http://en.wikipedia.org/wiki/Lisp_(programming_language) Lisp] has influenced a number of object oriented languages. The prominence of the object-oriented paradigm has influenced the design of other programming languages. There are languages that incorporate object-oriented constructs into the popular [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal] and Modula-2, resulting in the hybrid languages [http://en.wikipedia.org/wiki/Objective-C Objective-C], [http://en.wikipedia.org/wiki/C%2B%2B C++], ObjectPascal and Modula-3.Other languages influenced basically by Simula and [http://en.wikipedia.org/wiki/CLU_(programming_language) CLU], such as [http://en.wikipedia.org/wiki/BETA_programming_language Beta] and [http://en.wikipedia.org/wiki/Eiffel_(programming_language) Eiffel] have also appeared and are believed to give good support for the object-oriented paradigm. Although Eiffel and [http://en.wikipedia.org/wiki/Smalltalk Smalltalk] seem to be coherent object-oriented languages with integrated programming environments, C++ has become the most used object-oriented programming language, due to the influence of [http://en.wikipedia.org/wiki/Unix UNIX] and the popularity of the C language from which C++ derived. Finally, [http://en.wikipedia.org/wiki/Java_(programming_language) Java] should look familiar to C and C++ programmers because Java was designed with similar but cleaner constructs; it also provides a more robust library of classes. The dependency graph over time is as shown in the above figure.</p>
There are some other added benefits of reusability such as:


== Comparison ==
* <b>Reliability</b>: 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.


=== <b>[http://en.wikipedia.org/wiki/Debugging Debugging]</b> ===
* <b>Efficiency</b>: The component developers are likely to be experts in their field and will have used the best possible algorithms and data structures.
In structured programming debugging of code gets harder as the size of the program increases.<br>


In Object Oriented programming debugging of code is easy as we deal with classes and the readability of the code is improved. The other features that aid in debugging are its Modularity and Independence.
* <b>Time Savings</b>: By relying upon existing components there is less software to develop and hence applications can be built quicker.
=== <b>[http://en.wikipedia.org/wiki/Reusability Reusability]</b> ===
Reusability, the ability of software elements to serve for the construction of many different applications, is the main platform of object-oriented programming. Rather than starting from scratch with each new application, a programmer will consult [http://en.wikipedia.org/wiki/Library_(computing) libraries] of existing components to see if any are appropriate as starting points for the design of a new application. These components will exist in libraries as class definitions. A programmer will select an appropriate class definition from a library and then create a subclass for the application. The subclass will inherit the methods and properties of the library class, add some new ones of its own and possibly redefine the actions of others. The popularity of OOP stems from the support it gives to a software development process that relies upon pre-existing reusable software components. Reusability is particularly useful for developing graphical user interfaces.<br>


Code Reusability in Structured programming is in the form of subroutines which can be called multiple times. But these can be used only within a single application.
* <b>Decreased maintenance effort</b>: 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.


====<b>Added benefits of Reusability</b>====
* <b>Consistency</b>: 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.


<b>Reliability</b>: Components built by specialists in their field are more likely to be designed correctly and reliably. The reuse of these components across many applications will have given the developers of the components ample feedback to deal with any bugs and deficiencies.
* <b>Investment</b>: 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.


<b>Efficiency</b>: The component developers are likely to be experts in their field and will have used the best possible algorithms and data structures.
=== Focus ===


<b>Time Savings</b>: By relying upon existing components there is less software to develop and hence applications can be built quicker.
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.
 
<b>Decreased maintenance effort</b>: Using someone else’s 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.
 
<b>Consistency</b>: 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.
 
<b>Investment</b>: 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.
 
=== Concurrency ===
 
As far as concurrency is concerned; objects can be viewed as concurrent agents that interact by message passing, thus emphasizing the role of entities such as actors and servers in the structure of a real-world application. This provides programmers with powerful constructs that allow objects to run concurrently. Concurrency adds the idea of simultaneously executing objects and exploiting parallelism. Languages to which this applies include: Actor, ABCL, POOL-T, Orient84 and ConcurrentSmalltalk.
 
The way Structured Programs are executed, they degree of concurrency provided is not as much as is provided by Object Oriented Programs.
 
=== Focus ===


Structured programming is based around data structures and functions. Functions are where the actual computation takes place and the data structures hold the data values that the functions act upon and use in their computations.
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:


Object oriented programming, on the other hand, focuses on data. Instead of requiring us to answer questions such as "what we want to do and what do we need to do that", we require to answer questions such as "what kind of things do we want to have and what can those things do for us". Instead of designing our functions first and then coming up with data structures to support them, we design types first and then come up with the operations needed to work with them.
"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>[http://bulletin.sigchi.org/1997/october/papers/ross/ Structured Programmers Learning Object-Oriented Programming]</ref>


=== [http://en.wikipedia.org/wiki/Polymorphism_(computer_science) Polymorphism] ===
=== [http://en.wikipedia.org/wiki/Polymorphism_(computer_science) Polymorphism] ===


Polymorphism is the mechanism by which a function can be implemented in different ways. More generically, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.
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, if we consider a simple drawing program where we have a set of shapes (circles, rectangles, etc.) that share certain things in common (they all have a location, size, and color) but are different in other ways (how they look or whether they can be rotated).
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.  


In a structured program, we would write a function to draw a shape, containing logic like "if the shape is a circle, do ABC; if it’s a rectangle, do XYZ" and so on.
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.


But in an Object Oriented program, we would simply tell the shape to draw itself, and the shape would know, based on its own type, what to do: we write a specialized drawing function when we define each shape, and when we send a "draw" message to any shape, it automatically calls the one for the correct shape type. Polymorphism eliminates the need for us to check what kind of shape it is: we just have to know that shapes can draw themselves, and let the shape worry about how it actually happens.
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.


=== Encapsulation ===
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 = "";
  }
}


Encapsulation is the phenomenon of hiding internal details of an object. Encapsulation gives an object the ability to hide some of its data and methods and expose others which are required, by virtue of which these data and methods are well protected and not randomly accessed by other code.
== Analysis and Design Differences ==


For example, all shapes have a location and a size, but the best representation might be different. A circle only needs three numbers (center X, center Y, and radius) but a rectangle needs four (top, bottom, left, right).
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.


Structured programming encourages code everywhere to deal directly with the innards of data structures, so most likely we need to use the same representation for all shapes in order to avoid checking the type every time we want to measure a shape, even though that representation is wasteful for circles.
== What is a better choice ==
 
Object oriented programming addresses that problem two ways: first, encapsulation says that the internal representation of a shape is off-limits to anyone else, so if you want to know how big a shape is, you have to call its getSize() method instead of reading its size directly out of memory. Second, polymorphism allows different shapes to implement their getSize() methods differently, allowing circles to use a more efficient version while presenting the same interface to the outside world.
 
=== Inheritance ===
 
Inheritance is the mechanism by which the behaviour of a class can be reused in the definition of new classes. Subclasses of a class inherit the operations of their parent class and may add new operations and new instance variables.
 
This makes it easy to extend existing structures to produce new structures with slightly different behavior. For example, a filled circle is mostly the same as a regular circle, but it draws itself differently and also has a fill color.
 
In a structured program, we handle filled circles by adding a fill color to allshapes and a flag that indicates whether the shape is filled or not, and the fill color would simply go unused (wasting memory) in unfilled shapes.
 
In an object-oriented program, we can make FilledCircle a subclass of Circle, inheriting all the existing circle behavior, and then replace the draw() method and add a place to store the fill color. Then if we changed something about Circle later, the change would automatically propagate to FilledCircle, while changes we made to FilledCircle would not affect any other shapes.
 
 
=== What is a better choice/Scalability/Design vs Language ===




Line 111: Line 160:
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.
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.


Structured programming is generally preferred when we need to write small programs where as Object Oriented Programming is preferred when we need to write huge software and thus it is scalable.
The differences between Structured and Object-oriented Programming are briefed below:<ref>[http://www.buyya.com/java/Chapter1.pdf Software Development and Object-Oriented Programming Paradigms]</ref>
 
{| class="wikitable"
|-
!
! <b>Structured Programming</b>
! <b>Object-Oriented Programming</b>
|-
| <b>Approach</b>
| Top-down approach is followed
| Bottom-up approach is followed
|-
| <b>Focus</b>
| Focus is on algorithm and control flow.
| Focus is on object model.
|-
| <b>Program Organization</b>
| Program is divided into a number of sub modules, or functions, or procedures.
| Program is organized by having a number of classes and objects.
|-
| <b>Design</b>
| Functions are independent of each other.
| Each class is related in a hierarchical manner.
|-
| <b>Function Call</b>
| No designated receiver in the function call.
| There is a designated receiver for each message passing.
|-
| <b>Data/methods</b>
| Views data and functions as two separate entities.
| Views data and function as a single entity.
|-
| <b>Maintenance</b>
| Maintenance is costly.
| Maintenance is relatively cheaper.
|-
| <b>Reusability</b>
| Software reuse is not possible.
| Helps in software reuse.
|-
| <b>Passing Arguments</b>
| Function call is used.
| Message passing is used
|-
| <b>Abstraction</b>
| Function abstraction is used.
| Data abstraction is used.
|-
| <b>Algorithm/Data</b>
| Algorithm is given importance.
| Data is given importance.
|-
| <b>Domain</b>
| Solution is solution-domain specific.
| Solution is problem-domain specific.
|-
| <b>Encapsulation</b>
| No encapsulation. Data and functions are separate.
| Encapsulation packages code and data altogether. Data and functionalities are put together in a single entity.
|-
| <b>Programmer</b>
| Relationship between programmer and program is emphasized.
| Relationship between programmer and user is emphasized.
|-
| <b>Technique</b>
| Data-driven technique is used.
| Driven by delegation of responsibilities.
|}


='''References'''=
<references>
</references>


== References ==
<br>
== <b>Further Reading</b> ==


1.Leonard H.Weiner(1978-02-01) [http://dl.acm.org.prox.lib.ncsu.edu/citation.cfm?id=990555.990636&coll=DL&dl=GUIDE&CFID=270598&CFTOKEN=91997490  "The roots of structured programming"]
1. Peter Wegner, [http://dl.acm.org/citation.cfm?id=383004 "Concepts and paradigms of object-oriented programming"]


2.Edsger Dijkstra, [http://dl.acm.org.prox.lib.ncsu.edu/citation.cfm?id=1243380.1243381&coll=DL&dl=GUIDE&CFID=270598&CFTOKEN=91997490 "Notes on Structured Programming"]
2. Luiz Fernando Capretz, [http://dl.acm.org/citation.cfm?id=638778 "A brief history of the object-oriented approach"]


3.Peter Wegner, [http://dl.acm.org/citation.cfm?id=383004 "Concepts and paradigms of object-oriented programming"]
3. [http://www.educational-computing.co.uk/OOPSample.doc OOP Sample]


4.Luiz Fernando Capretz, [http://dl.acm.org/citation.cfm?id=638778 "A brief history of the object-oriented approach"]
4. http://askville.amazon.com/Compare-Contrast-Structured-programming-Object-Oriented/AnswerViewer.do?requestId=2470573


5. [http://www.educational-computing.co.uk/OOPSample.doc OOP Sample]
5. Leonard H.Weiner(1978-02-01) [http://dl.acm.org.prox.lib.ncsu.edu/citation.cfm?id=990555.990636&coll=DL&dl=GUIDE&CFID=270598&CFTOKEN=91997490  "The roots of structured programming"]


6. http://askville.amazon.com/Compare-Contrast-Structured-programming-Object-Oriented/AnswerViewer.do?requestId=2470573
6. Edsger Dijkstra, [http://dl.acm.org.prox.lib.ncsu.edu/citation.cfm?id=1243380.1243381&coll=DL&dl=GUIDE&CFID=270598&CFTOKEN=91997490 "Notes on Structured Programming"]

Latest revision as of 03:30, 26 September 2011

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"