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

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(187 intermediate revisions by 2 users not shown)
Line 1: Line 1:
CSC/ECE 517 Fall 2011/ch1 1e dm
"'''Block Structured vs Object-Oriented Programming Languages'''"
----
----
='''Introduction'''=
='''Introduction'''=
This wiki article describes the [http://en.wikipedia.org/wiki/Block_(programming) block structured] and [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented] languages. It also highlights their advantages and limitations along with providing the comparison between them.  
The usage of programming paradigms like block structured and object oriented have their own advantages and disadvantages. A block structured programming language is written out in a sequence of statements which do not redirect to any other area in the program. In contrast, object-oriented programming languages usually consist of a set of reusable modular components which can redirect to various points of execution in the program.  


This wiki article provides a comprehensive comparison of [http://en.wikipedia.org/wiki/Block_(programming) block structured] and [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented] languages, by describing their fundamental characteristics and highlighting their advantages and limitations. It explains why object oriented is better than block structured languages along with discussing the application of block structured concept in the object oriented programming.


='''Block Structured Languages'''=
='''Block Structured Languages'''=
[http://en.wikipedia.org/wiki/Block_(programming) Block structured languages] are a class of high-level languages in which a program is made up of blocks. A block is a section of code which can be grouped together. Blocks consist of one or more declarations and statements. A block structured programming language uses and permits the creation of blocks and may also include nested blocks as components. The major function of using blocks is to enable the groups of statements within the block to be treated as if they were a single statement.  
[http://en.wikipedia.org/wiki/Block_(programming) Block structured languages] are a class of high-level languages in which a program is made up of blocks. A [http://en.wikipedia.org/wiki/Block_(programming) block] is a section of code which can be grouped together. Blocks consist of one or more declarations and statements. A block structured programming language uses and permits the creation of blocks and may also include nested blocks as components. The major function of using blocks is to enable the groups of statements within the block to be treated as if they were a single statement.  


Structured programming is a technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure without unconditional branches to higher levels of the structure. A structured program is decomposed into a hierarchy of processes. A process in this context is a body of code, typically a function or subroutine, that takes some input and manipulates it to produce an output. A process may be composed of other, more specialized processes, i.e., it may be a function that calls other functions. Structured Programming uses three types of control flow: sequential, test, and iteration.
[http://en.wikipedia.org/wiki/Block_(programming) Block structured programming] is related to [http://en.wikipedia.org/wiki/Structured_programming structured programming], which is a technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure without unconditional branches to higher levels of the structure. A structured program is decomposed into a hierarchy of [http://en.wikipedia.org/wiki/Process_(computing) processes]. A process in this context is a body of code, typically a function or subroutine, that takes some input and manipulates it to produce an output. A process may be composed of other, more specialized processes, i.e., it may be a function that calls other functions. Structured Programming uses three types of [http://en.wikipedia.org/wiki/Control_flow control flow]: sequential, test, and iteration.


Examples of block structured programming languages are ALGOL, FORTAN, Pascal, C, Python, Lisp.
The three fundamentals of structured programming are:
*Sequence: A sequence refers to an ordered execution of statements where each step in the sequence must logically progress to the next step without any undesirable effects.
*Selection: A selection allows either one or a number of statements to be executed in the program. The keywords used for selection are [http://en.wikipedia.org/wiki/Conditional_statement if..then..else], [http://en.wikipedia.org/wiki/Switch_statement switch] and [http://en.wikipedia.org/wiki/Switch_statement case].
*Repetition: A repetition is the process in which a statement is executed until the program reaches a certain state or where all the operations have already been applied to the element. Hence, repetition identifies the continuation of the operation and when it should stop. The keywords used for repetition are [http://en.wikipedia.org/wiki/For_loop for], [http://en.wikipedia.org/wiki/While_loop while], [http://en.wikipedia.org/wiki/Do_while_loop repeat] and [http://en.wikipedia.org/wiki/Do_while_loop do..until].  


The four fundamentals of object oriented programming languages are Polymorphism, Inheritance, Encapsulation and Abstraction.
Examples of block structured programming languages are [http://en.wikipedia.org/wiki/ALGOL ALGOL], [http://en.wikipedia.org/wiki/Fortran FORTAN], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Python_(programming_language) Python], [http://en.wikipedia.org/wiki/Lisp Lisp], [http://en.wikipedia.org/wiki/Ada_(programming_language) Ada], [http://en.wikipedia.org/wiki/PL_SQL PL/SQL].


==Characteristics==
==Characteristics==
*It takes on the top-to-bottom approach.
*Takes on the [http://en.wikipedia.org/wiki/Top-down_design top-to-bottom approach]. A top-down approach is the breaking down of a system into compositional sub-systems, where each sub-system is then defined in further detail. This could be in the form of greater detail, additional subsystem levels, or until the entire system is reduced to base elements.  
*It is based around data structures and subroutines.
*Based around [http://en.wikipedia.org/wiki/Data_structures data structures] and [http://en.wikipedia.org/wiki/Subroutines subroutines].  
*It uses single entry and exit block.
*Uses single entry and exit block.
*The names of variables and other objects such as procedures which are declared in outer blocks are visible inside other inner blocks, unless they are shadowed by an object of the same name.
*The names of variables and other objects such as procedures which are declared in outer blocks are visible inside other inner blocks, unless they are shadowed by an object of the same name.
*It splits the tasks into modular forms.  
*Splits the tasks into modular forms.
 
This is a sample code in C which shows the implementation of a [http://en.wikipedia.org/wiki/Stack_(data_structure) stack].
 
<code>
define MAXSIZE 200
int storage[MAXSIZE];
int top; //index pointing to the top of stack
void main()
{
    void push(int);
    int pop();
    int choice=1,i,num;
    clrscr();
    while(choice ==1) {
        printf("MAIN MENU: 1.Add element to stack 2.Delete element from the stack\n");
        scanf("%d",&choice);
        switch(choice) {
          case 1:
            printf("Enter the data... ");
            scanf("%d",&num);
            push(num);
            break;
          case 2:
            i=pop();
            printf("Value returned from pop function is %d ",i);
            break;
          default:
            printf("Invalid Choice . ");
        }
        printf("Do you want to do more operations on Stack ( 1 for yes, any other key to exit) ");
        scanf("%d" , &choice);
    } //end of outer while
} //end of main
void push(int y) {
    if(top>MAXSIZE) {
      printf("STACK FULL");
      return;
    }
    else{
      top++;
      storage[top]=y;
    }
}
int pop(){
    int a;
    if(top<=0) {
      printf("STACK EMPTY");
      return 0;
    }
    else {
      a=storage[top];
      top--;
    }
    return(a);
}
</code>


==Advantages==
==Advantages==
*Splitting of tasks into blocks/modules makes the program simpler and easier to read with less lines and codes.
*Straightforward coding: Writing of classes and complex functions is not necessary to write a simple piece of code, which executes a specific set of commands.
*In a solution space where there are widely varying spatial and temporal scales one can
*Structuring: Splitting of tasks into blocks/modules makes the program simpler and easier to read when there are less lines.  
*Put more grid where the solution is more interesting.
*Easy Debugging: The blocks/modules are easier to debug and refactor.
*Leave the solution coarse where the solution is not interesting.
*Visibility: It provides restricted visibility for local identifiers.<ref name="block">David R. Hanson (1980), "Is Block Structure Necessary?".</ref>
*Can save an order of magnitude in memory.
*Storage: Provides efficient use of storage and hence can save an order of magnitude in memory.
*Block structured programming provides the protection of data that is exclusive to one set of modules within a program from compromise by other modules.<ref name="pascal">[http://pascal-central.com/ppl/chapter2.html Pascal Programming Language]</ref>
*Can save an order of magnitude in run time.
*Can save an order of magnitude in run time.
*Numerical accuracy improves with more grid where gradients are strongest.
*Being block-structured allows Fortran to be used for array operations.
*Being block-structured allows Fortran to be used for array operations.
*Overhead involved involved in coarse-fine interactions can be amortized over larger array calculations.
*Overhead involved in coarse-fine interactions can be [http://en.wikipedia.org/wiki/Amortized_analysis amortized] over larger array calculations.
*Numerical accuracy is improved if the coarse-fine interface is kept to a codimension smaller than the solution.


==Limitations==
==Limitations==
*Communication patterns between levels can be complex.
*Limited Use: Block structured programming uses a modular design which is not suitable for all sorts of problem solutions and hence its usage is pretty limited.  
*Algorithm complexity can be substantial.
*Redundancy: Block structured programming allows a lot of repetition of code since the code is written and executed sequentially, which leads to redundancy of code.
*No data abstraction or information hiding supported.
*Data Corruption: Block structured programming does not support [http://en.wikipedia.org/wiki/Abstraction_(computer_science) data abstraction] or [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) information hiding]. Hence it could lead to data corruption.
 
*Readability: Block structured programming is harder to understand and harder to modify when the code becomes considerable large.
*Separate Compilation: Block structured programming does not preclude separate compilation. The procedures depend on the environment in which they are nested, and hence only the outermost procedures could be suitable for separate compilation.<ref name="block"/>
*Implementation: Block structured programming though simple to implement, poses difficulties when addressing non-local variables.
*Communication patterns: Block structured programming may offer complex communication patters between different levels.
*Complexity: Block structured programming may have a substantial algorithm complexity.<ref name="advblock">[https://commons.lbl.gov/display/~dtgraves@lbl.gov/Advantages+and+disadvantages+of+block-structured+AMR Advantages of block structured languages]</ref>


='''Object Oriented Languages'''=
='''Object Oriented Languages'''=
[http://en.wikipedia.org/wiki/Object-oriented_programming Object oriented programming] is an approach to programming in which each data item with the operations used on it is designated as an object; the routines used to operate on the data item are called methods; and objects are grouped in a hierarchy of classes, with each class inheriting characteristics from the class above it.
[http://en.wikipedia.org/wiki/Object-oriented_programming Object oriented programming] is an approach to programming in which each data item with the operations used on it is designated as an [http://en.wikipedia.org/wiki/Object_(computer_science) object]; the routines used to operate on the data item are called [http://en.wikipedia.org/wiki/Method_(computer_programming) methods]; and objects are grouped in a hierarchy of [http://en.wikipedia.org/wiki/Class_(computer_science) classes], with each class inheriting characteristics from the class above it.


Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.
The four fundamentals of object oriented programming languages are [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism], [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance], [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation] and [http://en.wikipedia.org/wiki/Abstraction_(computer_science) Abstraction].


Examples of object oriented programming languages are C++, Java, Smalltalk, Ruby.
Examples of object oriented programming languages are [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Smalltalk Smalltalk], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].


==Concepts==
==Concepts==


[http://en.wikipedia.org/wiki/Object_(computer_science) Objects/Class:]
*[http://en.wikipedia.org/wiki/Object_(computer_science) Objects:] Object is the basic unit of object oriented programming. Data and function that operate on data can be bundles as a unit which is called as object.  
This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object.


[http://en.wikipedia.org/wiki/Class_(computer_science) Classes:]
*[http://en.wikipedia.org/wiki/Class_(computer_science) Classes:] Classes are the data types on which objects are created. This concept is similar to that of structures in [http://en.wikipedia.org/wiki/C_(programming_language) C]. Memory is allocated to the class only when an object is created.  
The concept of class is similar to the concept of structure in C. In other words classes are the data types on which objects are created. So while a class is created no memory is allocated only when an object is created memory gets allocated.


[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance:]
*[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance:] Inheritance is the way to reuse and compartmentalize the code by creating collections of [http://en.wikipedia.org/wiki/Object_(computer_science) objects] that can be based on previously created objects with slightly different or different properties and behaviour. A superclass, base class, or parent class is a [http://en.wikipedia.org/wiki/Class_(computer_science) class] from which other classes are derived. The classes that are derived from a superclass are known as child classes, derived classes, or subclasses.
As the name suggests Inheritance is the process of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as derived class. This is a very important concept of object oriented programming since this feature helps to reduce the code size.


[http://en.wikipedia.org/wiki/Abstraction_(computer_science) Data Abstraction:]
*[http://en.wikipedia.org/wiki/Abstraction_(computer_science) Data Abstraction:] Data abstraction makes it possible to represent the needed information in program without presenting the details. It is also possible to create user defined [http://en.wikipedia.org/wiki/Data_type data types] and thus increase the power of programming language.
By this feature of object oriented programming it is possible to represent the needed information in program without presenting the details. Also by the feature of data abstraction it is possible to create user defined data types and thus increase the power of programming language.


[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Data Encapsulation:]
*[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Data Encapsulation:] Data Encapsulation is the process of combining [http://en.wikipedia.org/wiki/Data_(computing) data] and [http://en.wikipedia.org/wiki/Function_(computer_science) functions] into a single unit called [http://en.wikipedia.org/wiki/Class_(computer_science) class]. Using this method, one cannot access the data directly, and is accessible only through functions present in a class. It thus gives rise to the concept of data hiding. It thus means that the internal representation of an [http://en.wikipedia.org/wiki/Object_(computer_science) object] is generally hidden from view outside of the object's definition.
Data Encapsulation is the process of combining data and functions into a single unit called class. By this method one cannot access the data directly. Data is accessible only through the functions present inside the class. Thus Data Encapsulation gave rise to the important concept of data hiding.


[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism:]
*[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism:] Polymorphism is the ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions. It thus uses a single function or an operator which functions in many different ways depending upon the specific usage. The purpose of polymorphism is to implement a style of programming called message-passing, in which objects of various types define a common interface of operations for users. The primary usage of polymorphism is the ability of [http://en.wikipedia.org/wiki/Object_(computer_science) objects] belonging to different types to respond to [http://en.wikipedia.org/wiki/Method_(computer_science) method], [http://en.wikipedia.org/wiki/Field_(computer_science) field], or [http://en.wikipedia.org/wiki/Property_(computer_science) property] calls of the same name, each one according to an appropriate type-specific behaviour. Polymorphism is not the same as [http://en.wikipedia.org/wiki/Method_overloading method overloading] or [http://en.wikipedia.org/wiki/Method_overriding method overriding] [5].  
The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism. Poly refers many. That is a single function or an operator functioning in many ways different upon the usage is called polymorphism.


Overloading:
*[http://en.wikipedia.org/wiki/Method_overloading Overloading:] Overloading is a specific branch of [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism], where the existing [http://en.wikipedia.org/wiki/Operator_(programming) operator] or [http://en.wikipedia.org/wiki/Function_(computer_science) function] is made to have different implementations depending on their arguments. The purpose of overloading is to allow developers to define/redefine the operators as required.  
The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type it is said to be overloaded.


Reusability:
Thus the object oriented programming features helps the program ad there by users of the application to achieve increased performance, it saves time of developing the application, give optimized code for the application, helps in gaining secured applications and there by helps in easier maintenance.
That is object oriented programming has the feature of allowing an existing class which is written and debugged to be used by other programmers and there by provides a great time saving and also code efficiency to the language. Also it is possible to a have the existing class and adds new features to the existing class as pet the programmer’s choice.


Thus the object oriented programming features helps the program ad there by users of the application to achieve increased performance, it saves time of developing the application, give optimized code for the application, helps in gaining secured applications and there by helps in easier maintenance.
This a sample code in Java which shows the implementation of a [http://en.wikipedia.org/wiki/Stack_(data_structure) stack].


==Characteristics==
<code>
*This type of programming uses sections in a program to perform certain tasks.
public class Stack {
*Object Oriented Programming (OOP) models real world object (attributes and behavior).
    private int top;
*OOP encapsulates data and functions.
    private int[] storage;
*Objects have the property of information hiding.
    public Stack(int capacity) {
*Objects communicate through messages (via interface).
      if (capacity <= 0)
*Objects allow inheritance and polymorphism.
      System.out.println("Stack's capacity must be positive");
*It splits the program into objects that can be reused into other programs.
      storage = new int[capacity];
*They are small programs that can be used in other software.
      top = 1;
*Each object or module has the data and the instruction of what to do with the data in it. This can be reused in other software .
    }
*An object-oriented program is decomposed into a network of collaborating objects. An object represents a thing or concept and has a known set of behaviors that may be invoked by other objects. For any activity of the program, an object responsible for that activity may interact with other objects by invoking their behaviors, or "methods", until the activity is complete.
    public void push(int value) {
      if (top == storage.length)
          System.out.println("Stack's underlying storage is overflow");
      else {
          top++;
          storage[top] = value;
      }
    }
    public int pop() {
      int a;
      if (top == -1) {
        System.out.println("Stack is empty");
        return -1;
      }
      a=storage[top];
      top-;
      return a;
    }
    public static void main(String args[]){
      Stack myStack = new Stack(200);
      int choice=1,i,num;
      clrscr();
      while(choice ==1) {
        printf("MAIN MENU: 1.Add element to stack 2.Delete element from the stack\n");
        scanf("%d",&choice);
        switch(choice) {
          case 1:
              printf("Enter the data... ");
              scanf("%d",&num);
              myStack.push(num);
              break;
          case 2:
              i=myStack.pop();
              printf("Value returned from pop function is %d ",i);
              break;
          default:
              printf("Invalid Choice . ");
        }
        printf("Do you want to do more operations on Stack ( 1 for yes, any other key to exit) ");
        scanf("%d" , &choice);
      } //end of outer while
    } //end of main
}
</code>


==Advantages==
==Advantages==
*Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear.  
*Simplicity: Object oriented programming models real world objects, thus reducing the complexity of the code. It also helps in giving a clear picture of the program structure.<ref name="advobject">[http://www.dba-oracle.com/t_object_oriented_approach.htm Advantages of object oriented languages]</ref> 
*Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.  
*Modularity: Object oriented programming uses each object to form a separate entity whose internal workings are decoupled from other parts of the system. Hence it helps to reduce large problems to smaller, more manageable problems.<ref name="advobject1">[http://wiki.answers.com/Q/Advantages_and_disadvantages_of_an_object-oriented_language_in_organization Advantages of object oriented languages]</ref>
*Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods. *Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.  
*Modifiability: Object oriented programming helps in making minor changes to the view or the business logic without affecting any other part of the program.  
*Maintainability: objects can be maintained separately, making locating and fixing problems easier.  
*Extensibility: Object oriented programming helps in adding new features or modify the existing features without affecting the entire program since the objects and classes are isolated from each other.
*Re-usability: objects can be reused in different programs.
*Maintainability: Object oriented programming uses objects which can be easily located and destroyed when the object is no longer in use.  
*Helps to reduce large problems to smaller, more manageable problems.
*Re-usability: Object oriented programming uses a modular approach where objects and classes can be reused in different programs. Thus less code needs to be written and reduces code redundancy.
*Framework: Object oriented programming provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.


==Limitations==
==Limitations==
*Over generalization
*Complexity: The writing of classes and functions becomes complex when one has to write a straightforward piece of code.
*Dynamic: Object oriented approach is well suited in case of a dynamic environment and not for a simple environment.
*Over generalization: One tends to overgeneralise the amount of development time and often less provision is provided for design processes which may result in incorrect designs.
*Artificial class relations
*Artificial class relations
*Unnecessary complications


='''Compare and Contrast'''=
='''Compare and Contrast'''=


The table provides a summary of the various features of block structured and object oriented programming as discussed above.
{| class="wikitable" border="1"
|-
! Point of Comparison
! Block Structured
! Object Oriented
|-
|
1. Definition
| Block Structured is a programming language in which sections of source code are executed as a single unit.<ref name="defblock">[http://encyclopedia2.thefreedictionary.com/block-structured Definition of Block Structured Programming]</ref>
| Object Oriented programming is a programming language which uses objects to design applications and computer programs.<ref name="defobject">[http://en.wikipedia.org/wiki/Object-oriented_programming Definition of Object Oriented Programming]</ref> These objects are data structures that use data fields and methods along with their interactions.
|-
|
2. Focus
| Task-centric
| Data-centric
|-
|
3. Approach
| Top-down approach
| Bottom-up approach
|-
|
4. Complexity
| Simpler to understand for smaller programs, gets complex to understand when the code becomes considerable large
| Can get complex if not used properly, by creating unnecessary abstraction
|-
|
5. Modularity
| Sequential approach, not very modular
| Each object forms a separate entity whose internal workings are decoupled from other parts of the system. Hence helps to reduce large problems to smaller, more manageable problems.
|-
|
6. Data Protection/Hiding
| Do not provide for data protection or hiding. Local variables may not be accessible outside a particular block, but, global variables are accessible everywhere and can be modified anywhere. There is no particular way to specify that an needs to be protected
| Provide for data protection/hiding by abstraction and encapsulation.
Encapsulation hides the internal representation of an object from view outside of the object's definition. Abstraction is the process of hiding away the implementation details.
|-
|
7. Code Reuse
| It is difficult to reuse work done for other projects. By starting with a particular problem and subdividing it into convenient pieces, top-down program design tends to produce a design that is unique to that problem.
| Rather than starting from scratch with each new application, a programmer can consult libraries of existing components to see if any are appropriate as starting points for the design of a new application.
|-
|
8. Declaring new data types
| Not supported very extensively, can create structures but not as efficient, since it is task-centric.
| Surrounded around the concept of creating new data types that are more natural and focusing on operations on these new data types.
|-
|
9. Efficiency
| More efficient for solving straightforward, simple problems
| More efficient for solving complex problems
|-
|
10. Maintenance
| Though block structured breaks up code into simpler blocks, it is difficult to maintain once there are many such blocks.
| Easier to maintain due to modular design provided by classes.
|-
|
11. Extensibility
| Less extensible since the all blocks affected would need to be reorganized to incorporate the new feature which may lead to data inconsistency
| More extensible since new features can be easily added due to its isolation of objects and classes
|-
|
12. Flexibility
| Is less flexible, since to make a single change it may require to change the code in many places since it inherently does not support a lot of code reuse
| More due to modular design and code reuse.
|-
|
13. Redundancy
| More redundancy due to lack of reuse of code
| Lesser redundancy, similar code is usually put together and resued.
|-
|
14. Examples
| ALGOL, C, Pascal, Fortan
| C++, Java, Ruby, Smalltalk
|-
|}
='''Why is Object Oriented better than Block Structured Programming?'''=
Block structured programming is a type of structured programming where the basic code is written in the form [http://en.wikipedia.org/wiki/Block_(programming) blocks]. Structured programming gained popularity in about 1970's <ref name="structured">[http://en.wikipedia.org/wiki/Structured_programming Structured Programming]</ref> and most of the [http://en.wikipedia.org/wiki/Procedural_programming_languages procedural programming languages] have incorporated features of block structured programming. The principle focus of using block structured programming paradigm was to incorporate the use of sequential lines of codes, known as blocks to follow the [http://en.wikipedia.org/wiki/Top-down_design top-down design] approach for the program.
The system is essentially broken down into sub-systems. Using top-down approach, first an overview of the system is formulated. It then specifies the first level sub-systems, but does not provide any details about the same. Each sub-system is then refined in more greater detail and if additional levels are to be needed, then those are described here. This is carried on till the entire system is reduced to its base elements. These made the blocks of code easily readable and understandable. It also helped in easy debugging of the blocks of code when the program size was reasonable.
Even though block structured programming was popular, but with the increase in the program size and complexity, problems started to arise. As discussed earlier, the major limitation of block structured programming was re-usability of code. The program though was divided into tasks, no provision for re-usability was provided. With the increase in program complexity, to effect a small change, code in multiple locations needed to be changed. For a large system, the organization is more of a network of structures, and insistence on hierarchical structuring for data and procedures can produce cumbersome code with large amounts of [http://en.wiktionary.org/wiki/tramp_data tramp data].<ref name="structured"/> It also does not have any support for information hiding or data abstraction. The major limitation is the concept of [http://en.wikipedia.org/wiki/Spaghetti_code spaghetti code]. Spaghetti code is code that has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other unstructured [http://en.wikipedia.org/wiki/Branch_(computer_science) branching] constructs.<ref name="spaghetti">[http://en.wikipedia.org/wiki/Spaghetti_code Spaghetti Code]</ref> It poses the problem that the code written today will not help to write any future code.
Hence, to overcome these limitations of block structured programming, the programming paradigm of [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented programming] came into existence. This paradigm introduced the concept of [http://en.wikipedia.org/wiki/Object_(computer_science) objects], which are the data structures containing data fields and methods along with their interactions, to design applications and programs.
Object oriented programming provides concepts like [http://en.wikipedia.org/wiki/Inheritance_(computer_science) inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism], [http://en.wikipedia.org/wiki/Abstraction_(computer_science data abstraction] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming data encapsulation]. These provide the main advantages for object oriented programming and thus help to overcome the limitations of block structured programming.
With the increase in program size and complexity, object oriented programming provides the feature of maintaining code in modules, which are isolated from each other and thus could be re-used through programs and also allows for easier modification and addition of new functionalities to an existing system with minimal changes. These advantages of object oriented programming make it more efficient and well structured than block structured programming.
We can also illustrate this in the form of an example. From the above implementations of a [http://en.wikipedia.org/wiki/Stack_(data_structure) stack] in block structured and object oriented languages we can see the following:
In object oriented implementation the variables storage and stack are in abstracted into a class. The variables are defined as private, thus there is no way to manipulate them other than the available methods. Some piece of code cannot erroneously manipulate the value of these variables. There is no such data protection/hiding in block structured programming. Also, it is possible to for a new class to extend the stack class and thus reuse the code, which again is not possible in block structured programming.
='''Block Structure in Object Oriented Programming'''=
Block structured programming is still used in object oriented programming. The basic fundamentals of block structured programming is the usage of [http://en.wikipedia.org/wiki/Block_(programming) blocks], which is a section of code grouped together. A [http://en.wikipedia.org/wiki/Block_(programming) block] consists of declarations and statements, where all the statements are executed as one single statement in a block.
Blocks are used in object creation and initialization, which can be easily encapsulated in a generic function which allows one to create new objects dynamically. The declaration of one object, A in another object, B, if inside a nested recursive declaration sequence (the declarations of the block that forms the body of the method), it creates a new object each time that method is called. Thus, it allows creation of objects dynamically, even though we create the objects by object declarations. We can use this concept of recursive declaration sequence to achieve [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) information hiding] which provides the ability to hide generic functions.<ref name="craig">Craig Chambers and Gary T. Leavens (December 1996, Revised April 1997), "BeCecil, A Core Object-Oriented Language with Block Structure and Multimethods: Semantics and Typing".</ref>
Example of a nested class in Java is shown below <ref name="nestedclasses">[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes Nested Classes]</ref> : 
<code>
public class OuterClass {
    private String outerInstanceVar;
    public class InnerClass {
        public void printVars() {
          System.out.println( "Print Outer Class Instance Var.:" + outerInstanceVar);
        }
    }
}
</code>
Blocks are also used in [http://en.wikipedia.org/wiki/Control_flow control flow statements] like [http://en.wikipedia.org/wiki/For_loop for] loop, [http://en.wikipedia.org/wiki/While_loop while] loop, [http://en.wikipedia.org/wiki/Do_while_loop do..while] loop and [http://en.wikipedia.org/wiki/Do_while_loop do..until] loop. The statements inside the loops are nothing but a block of executable statements, and these statements are executed as a single statements for every time the loop gets executed. Block structured programming identifies the blocks of code by embracing them within keywords or braces. Similarly, the loop constructs are embraced with braces, indicating a block of statements.
Example of a nested for loop and if loop construct in Java is shown below:
<code>
for(i = 0; i < n; i++) {
    for(j = 1; j < (n-i); j++) {
      if(a[j-1] > a[j]) {
          temp = a[j-1];
          a[j-1]=a[j];
          a[j]=temp;
      }
    }
}
</code>
Blocks are used to iterate over arrays or returning [http://en.wikipedia.org/wiki/Ruby_(programming_language)#Blocks_and_iterators closures] from a method in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]. A block is a closure in Ruby.<ref name="rubyblocks">[http://en.wikipedia.org/wiki/Ruby_(programming_language)#Blocks_and_iterators Ruby Programming Language - Blocks and Iterators]</ref>
Example of a block in Ruby is shown below <ref name="rubyguide">Dave Thomas, Chad Fowler and Andy Hunt, Programming Ruby 1.9: The Pragmatic Programmers’ Guide, ISBN: 1-934356-08-5.</ref> :
<code>
class BlockExample
    CONST = 0
    @@a = 3
    def return_closure
      a = 1
      @a = 2
      lambda { [ CONST, a, @a, @@a, yield ] }
    end
    def change_values
      @a += 1
      @@a += 1
    end
end
eg = BlockExample.new
block = eg.return_closure { "original" }
block.call # => [0, 1, 2, 3, "original"]
eg.change_values
block.call # => [0, 1, 3, 4, "original"]
</code>
There are many object oriented programming languages which use a block structure.
The more common programming languages like [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_(programming_language) Java] use block structures in [[http://en.wikipedia.org/wiki/Class_(computer_science) classes] and [http://en.wikipedia.org/wiki/Control_flow control structures] like the for loop, do..while, if..then..else and switch. [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] also uses blocks in iterations over arrays or hash.
The less common object oriented programming languages which supported block structure are: BeCecil is an object oriented language like [http://en.wikipedia.org/wiki/Cecil_(programming_language) Cecil], [http://en.wikipedia.org/wiki/CLOS CLOS] and [http://en.wikipedia.org/wiki/Dylan_(programming_language) Dylan], but along with the mechanisms of inheritance and information hiding, it is also block structured.<ref name="craig"/> The other main object oriented languages that allow full use of block structure are [http://en.wikipedia.org/wiki/Simula Stimula 67] and [http://en.wikipedia.org/wiki/BETA_programming_language Beta] <ref name="craig"/> where the block structure is present in the form of nested classes.<ref name="ole">Ole Lehrmann Madsen (November 1987), "Block Structure and Object Oriented Languages", DAIMI PB-230</ref>


='''Conclusion'''=
='''Conclusion'''=


[http://en.wikipedia.org/wiki/Structured_programming Structured programming] is essentially a forerunner of [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented programming]. Both the paradigms have their own advantages and limitations. But we can clearly deduce that the limitation of block structured programming are resolved by the advantages of object oriented programming.


='''References'''=
Object oriented programming provides a revolutionary new way of looking at computer programming. Historically, programs have been viewed as procedures (or we may think of these as "verbs") that operate on data. OOP takes the view that programs should start by thinking about the data (or "nouns") first.<ref name="glossary">[http://www.pdacortex.com/glossary.htm#O Glossary]</ref>


='''See Also'''=
*[http://en.wikipedia.org/wiki/Structured_programming Structured Programming]
*[http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming]
*[http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(object-oriented_programming) Comparison of Programming Languages]
*[http://en.wikipedia.org/wiki/Object_oriented_design Object Oriented Design]
*[http://en.wikipedia.org/wiki/Object-oriented_analysis Object Oriented analysis and design]
*[http://en.wikipedia.org/wiki/Block_(programming) Block]


='''See Also'''=


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


='''External Links'''=
='''External Links'''=
*[http://www.youtube.com/watch?v=Dw49WkGukMs&feature=feedwll&list=WL Video for Structured Programming]
*[http://www.brighthub.com/internet/web-development/articles/82024.aspx Comparison between Structured Programming and Object Oriented Programming]
*[http://download.oracle.com/javase/tutorial/java/concepts/index.html Object Oriented Concepts]
*[http://www.brighthub.com/internet/web-development/articles/73961.aspx Principles of Structured Programming]
*[http://tcts.fpms.ac.be/oobp/oobp.html Object Oriented Block Programming]

Latest revision as of 21:30, 25 September 2011

"Block Structured vs Object-Oriented Programming Languages"


Introduction

The usage of programming paradigms like block structured and object oriented have their own advantages and disadvantages. A block structured programming language is written out in a sequence of statements which do not redirect to any other area in the program. In contrast, object-oriented programming languages usually consist of a set of reusable modular components which can redirect to various points of execution in the program.

This wiki article provides a comprehensive comparison of block structured and object oriented languages, by describing their fundamental characteristics and highlighting their advantages and limitations. It explains why object oriented is better than block structured languages along with discussing the application of block structured concept in the object oriented programming.

Block Structured Languages

Block structured languages are a class of high-level languages in which a program is made up of blocks. A block is a section of code which can be grouped together. Blocks consist of one or more declarations and statements. A block structured programming language uses and permits the creation of blocks and may also include nested blocks as components. The major function of using blocks is to enable the groups of statements within the block to be treated as if they were a single statement.

Block structured programming is related to structured programming, which is a technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure without unconditional branches to higher levels of the structure. A structured program is decomposed into a hierarchy of processes. A process in this context is a body of code, typically a function or subroutine, that takes some input and manipulates it to produce an output. A process may be composed of other, more specialized processes, i.e., it may be a function that calls other functions. Structured Programming uses three types of control flow: sequential, test, and iteration.

The three fundamentals of structured programming are:

  • Sequence: A sequence refers to an ordered execution of statements where each step in the sequence must logically progress to the next step without any undesirable effects.
  • Selection: A selection allows either one or a number of statements to be executed in the program. The keywords used for selection are if..then..else, switch and case.
  • Repetition: A repetition is the process in which a statement is executed until the program reaches a certain state or where all the operations have already been applied to the element. Hence, repetition identifies the continuation of the operation and when it should stop. The keywords used for repetition are for, while, repeat and do..until.

Examples of block structured programming languages are ALGOL, FORTAN, Pascal, C, Python, Lisp, Ada, PL/SQL.

Characteristics

  • Takes on the top-to-bottom approach. A top-down approach is the breaking down of a system into compositional sub-systems, where each sub-system is then defined in further detail. This could be in the form of greater detail, additional subsystem levels, or until the entire system is reduced to base elements.
  • Based around data structures and subroutines.
  • Uses single entry and exit block.
  • The names of variables and other objects such as procedures which are declared in outer blocks are visible inside other inner blocks, unless they are shadowed by an object of the same name.
  • Splits the tasks into modular forms.

This is a sample code in C which shows the implementation of a stack.

define MAXSIZE 200
int storage[MAXSIZE];
int top;	//index pointing to the top of stack
void main()
{
   void push(int);
   int pop();
   int choice=1,i,num;
   clrscr();
   while(choice ==1) {
       printf("MAIN MENU: 1.Add element to stack 2.Delete element from the stack\n");
       scanf("%d",&choice);
       switch(choice) {
         case 1:
            printf("Enter the data... ");
            scanf("%d",&num);
            push(num);
            break;
         case 2: 
            i=pop();
            printf("Value returned from pop function is %d ",i);
            break;
         default:
            printf("Invalid Choice . ");
       }
       printf("Do you want to do more operations on Stack ( 1 for yes, any other key to exit) ");
       scanf("%d" , &choice);
   } //end of outer while
} //end of main
void push(int y) {
   if(top>MAXSIZE) {
      printf("STACK FULL");
      return;
   } 
   else{
      top++;
      storage[top]=y;
   }
}
int pop(){
   int a;
   if(top<=0) {
      printf("STACK EMPTY");
      return 0; 
   }
   else {
      a=storage[top];
      top--;
   }
   return(a);
}

Advantages

  • Straightforward coding: Writing of classes and complex functions is not necessary to write a simple piece of code, which executes a specific set of commands.
  • Structuring: Splitting of tasks into blocks/modules makes the program simpler and easier to read when there are less lines.
  • Easy Debugging: The blocks/modules are easier to debug and refactor.
  • Visibility: It provides restricted visibility for local identifiers.<ref name="block">David R. Hanson (1980), "Is Block Structure Necessary?".</ref>
  • Storage: Provides efficient use of storage and hence can save an order of magnitude in memory.
  • Block structured programming provides the protection of data that is exclusive to one set of modules within a program from compromise by other modules.<ref name="pascal">Pascal Programming Language</ref>
  • Can save an order of magnitude in run time.
  • Being block-structured allows Fortran to be used for array operations.
  • Overhead involved in coarse-fine interactions can be amortized over larger array calculations.

Limitations

  • Limited Use: Block structured programming uses a modular design which is not suitable for all sorts of problem solutions and hence its usage is pretty limited.
  • Redundancy: Block structured programming allows a lot of repetition of code since the code is written and executed sequentially, which leads to redundancy of code.
  • Data Corruption: Block structured programming does not support data abstraction or information hiding. Hence it could lead to data corruption.
  • Readability: Block structured programming is harder to understand and harder to modify when the code becomes considerable large.
  • Separate Compilation: Block structured programming does not preclude separate compilation. The procedures depend on the environment in which they are nested, and hence only the outermost procedures could be suitable for separate compilation.<ref name="block"/>
  • Implementation: Block structured programming though simple to implement, poses difficulties when addressing non-local variables.
  • Communication patterns: Block structured programming may offer complex communication patters between different levels.
  • Complexity: Block structured programming may have a substantial algorithm complexity.<ref name="advblock">Advantages of block structured languages</ref>

Object Oriented Languages

Object oriented programming is an approach to programming in which each data item with the operations used on it is designated as an object; the routines used to operate on the data item are called methods; and objects are grouped in a hierarchy of classes, with each class inheriting characteristics from the class above it.

The four fundamentals of object oriented programming languages are Polymorphism, Inheritance, Encapsulation and Abstraction.

Examples of object oriented programming languages are C++, Java, Smalltalk, Ruby.

Concepts

  • Objects: Object is the basic unit of object oriented programming. Data and function that operate on data can be bundles as a unit which is called as object.
  • Classes: Classes are the data types on which objects are created. This concept is similar to that of structures in C. Memory is allocated to the class only when an object is created.
  • Inheritance: Inheritance is the way to reuse and compartmentalize the code by creating collections of objects that can be based on previously created objects with slightly different or different properties and behaviour. A superclass, base class, or parent class is a class from which other classes are derived. The classes that are derived from a superclass are known as child classes, derived classes, or subclasses.
  • Data Abstraction: Data abstraction makes it possible to represent the needed information in program without presenting the details. It is also possible to create user defined data types and thus increase the power of programming language.
  • Data Encapsulation: Data Encapsulation is the process of combining data and functions into a single unit called class. Using this method, one cannot access the data directly, and is accessible only through functions present in a class. It thus gives rise to the concept of data hiding. It thus means that the internal representation of an object is generally hidden from view outside of the object's definition.
  • Polymorphism: Polymorphism is the ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions. It thus uses a single function or an operator which functions in many different ways depending upon the specific usage. The purpose of polymorphism is to implement a style of programming called message-passing, in which objects of various types define a common interface of operations for users. The primary usage of polymorphism is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behaviour. Polymorphism is not the same as method overloading or method overriding [5].
  • Overloading: Overloading is a specific branch of polymorphism, where the existing operator or function is made to have different implementations depending on their arguments. The purpose of overloading is to allow developers to define/redefine the operators as required.

Thus the object oriented programming features helps the program ad there by users of the application to achieve increased performance, it saves time of developing the application, give optimized code for the application, helps in gaining secured applications and there by helps in easier maintenance.

This a sample code in Java which shows the implementation of a stack.

public class Stack {
   private int top;
   private int[] storage;
   public Stack(int capacity) {
      if (capacity <= 0)
      System.out.println("Stack's capacity must be positive");
      storage = new int[capacity];
      top = 1;
   }
   public void push(int value) {
      if (top == storage.length)
         System.out.println("Stack's underlying storage is overflow");
      else {
         top++;
         storage[top] = value;
      }
   }
   public int pop() {
     int a;
     if (top == -1) {
        System.out.println("Stack is empty");
        return -1;
     }
     a=storage[top];
     top-;
     return a;
   }
   public static void main(String args[]){
     Stack myStack = new Stack(200);
     int choice=1,i,num;
     clrscr();
     while(choice ==1) {
        printf("MAIN MENU: 1.Add element to stack 2.Delete element from the stack\n");
        scanf("%d",&choice);
        switch(choice) {
          case 1:
             printf("Enter the data... ");
             scanf("%d",&num);
             myStack.push(num);
             break;
          case 2: 
             i=myStack.pop();
             printf("Value returned from pop function is %d ",i);
             break;
          default:
             printf("Invalid Choice . ");
        }
        printf("Do you want to do more operations on Stack ( 1 for yes, any other key to exit) ");
        scanf("%d" , &choice);
     } //end of outer while
   } //end of main
}

Advantages

  • Simplicity: Object oriented programming models real world objects, thus reducing the complexity of the code. It also helps in giving a clear picture of the program structure.<ref name="advobject">Advantages of object oriented languages</ref>
  • Modularity: Object oriented programming uses each object to form a separate entity whose internal workings are decoupled from other parts of the system. Hence it helps to reduce large problems to smaller, more manageable problems.<ref name="advobject1">Advantages of object oriented languages</ref>
  • Modifiability: Object oriented programming helps in making minor changes to the view or the business logic without affecting any other part of the program.
  • Extensibility: Object oriented programming helps in adding new features or modify the existing features without affecting the entire program since the objects and classes are isolated from each other.
  • Maintainability: Object oriented programming uses objects which can be easily located and destroyed when the object is no longer in use.
  • Re-usability: Object oriented programming uses a modular approach where objects and classes can be reused in different programs. Thus less code needs to be written and reduces code redundancy.
  • Framework: Object oriented programming provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.

Limitations

  • Complexity: The writing of classes and functions becomes complex when one has to write a straightforward piece of code.
  • Dynamic: Object oriented approach is well suited in case of a dynamic environment and not for a simple environment.
  • Over generalization: One tends to overgeneralise the amount of development time and often less provision is provided for design processes which may result in incorrect designs.
  • Artificial class relations

Compare and Contrast

The table provides a summary of the various features of block structured and object oriented programming as discussed above.

Point of Comparison Block Structured Object Oriented

1. Definition

Block Structured is a programming language in which sections of source code are executed as a single unit.<ref name="defblock">Definition of Block Structured Programming</ref> Object Oriented programming is a programming language which uses objects to design applications and computer programs.<ref name="defobject">Definition of Object Oriented Programming</ref> These objects are data structures that use data fields and methods along with their interactions.

2. Focus

Task-centric Data-centric

3. Approach

Top-down approach Bottom-up approach

4. Complexity

Simpler to understand for smaller programs, gets complex to understand when the code becomes considerable large Can get complex if not used properly, by creating unnecessary abstraction

5. Modularity

Sequential approach, not very modular Each object forms a separate entity whose internal workings are decoupled from other parts of the system. Hence helps to reduce large problems to smaller, more manageable problems.

6. Data Protection/Hiding

Do not provide for data protection or hiding. Local variables may not be accessible outside a particular block, but, global variables are accessible everywhere and can be modified anywhere. There is no particular way to specify that an needs to be protected Provide for data protection/hiding by abstraction and encapsulation.

Encapsulation hides the internal representation of an object from view outside of the object's definition. Abstraction is the process of hiding away the implementation details.

7. Code Reuse

It is difficult to reuse work done for other projects. By starting with a particular problem and subdividing it into convenient pieces, top-down program design tends to produce a design that is unique to that problem. Rather than starting from scratch with each new application, a programmer can consult libraries of existing components to see if any are appropriate as starting points for the design of a new application.

8. Declaring new data types

Not supported very extensively, can create structures but not as efficient, since it is task-centric. Surrounded around the concept of creating new data types that are more natural and focusing on operations on these new data types.

9. Efficiency

More efficient for solving straightforward, simple problems More efficient for solving complex problems

10. Maintenance

Though block structured breaks up code into simpler blocks, it is difficult to maintain once there are many such blocks. Easier to maintain due to modular design provided by classes.

11. Extensibility

Less extensible since the all blocks affected would need to be reorganized to incorporate the new feature which may lead to data inconsistency More extensible since new features can be easily added due to its isolation of objects and classes

12. Flexibility

Is less flexible, since to make a single change it may require to change the code in many places since it inherently does not support a lot of code reuse More due to modular design and code reuse.

13. Redundancy

More redundancy due to lack of reuse of code Lesser redundancy, similar code is usually put together and resued.

14. Examples

ALGOL, C, Pascal, Fortan C++, Java, Ruby, Smalltalk

Why is Object Oriented better than Block Structured Programming?

Block structured programming is a type of structured programming where the basic code is written in the form blocks. Structured programming gained popularity in about 1970's <ref name="structured">Structured Programming</ref> and most of the procedural programming languages have incorporated features of block structured programming. The principle focus of using block structured programming paradigm was to incorporate the use of sequential lines of codes, known as blocks to follow the top-down design approach for the program.

The system is essentially broken down into sub-systems. Using top-down approach, first an overview of the system is formulated. It then specifies the first level sub-systems, but does not provide any details about the same. Each sub-system is then refined in more greater detail and if additional levels are to be needed, then those are described here. This is carried on till the entire system is reduced to its base elements. These made the blocks of code easily readable and understandable. It also helped in easy debugging of the blocks of code when the program size was reasonable.

Even though block structured programming was popular, but with the increase in the program size and complexity, problems started to arise. As discussed earlier, the major limitation of block structured programming was re-usability of code. The program though was divided into tasks, no provision for re-usability was provided. With the increase in program complexity, to effect a small change, code in multiple locations needed to be changed. For a large system, the organization is more of a network of structures, and insistence on hierarchical structuring for data and procedures can produce cumbersome code with large amounts of tramp data.<ref name="structured"/> It also does not have any support for information hiding or data abstraction. The major limitation is the concept of spaghetti code. Spaghetti code is code that has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other unstructured branching constructs.<ref name="spaghetti">Spaghetti Code</ref> It poses the problem that the code written today will not help to write any future code.

Hence, to overcome these limitations of block structured programming, the programming paradigm of object oriented programming came into existence. This paradigm introduced the concept of objects, which are the data structures containing data fields and methods along with their interactions, to design applications and programs.

Object oriented programming provides concepts like inheritance, polymorphism, data abstraction and data encapsulation. These provide the main advantages for object oriented programming and thus help to overcome the limitations of block structured programming.

With the increase in program size and complexity, object oriented programming provides the feature of maintaining code in modules, which are isolated from each other and thus could be re-used through programs and also allows for easier modification and addition of new functionalities to an existing system with minimal changes. These advantages of object oriented programming make it more efficient and well structured than block structured programming.

We can also illustrate this in the form of an example. From the above implementations of a stack in block structured and object oriented languages we can see the following: In object oriented implementation the variables storage and stack are in abstracted into a class. The variables are defined as private, thus there is no way to manipulate them other than the available methods. Some piece of code cannot erroneously manipulate the value of these variables. There is no such data protection/hiding in block structured programming. Also, it is possible to for a new class to extend the stack class and thus reuse the code, which again is not possible in block structured programming.

Block Structure in Object Oriented Programming

Block structured programming is still used in object oriented programming. The basic fundamentals of block structured programming is the usage of blocks, which is a section of code grouped together. A block consists of declarations and statements, where all the statements are executed as one single statement in a block.

Blocks are used in object creation and initialization, which can be easily encapsulated in a generic function which allows one to create new objects dynamically. The declaration of one object, A in another object, B, if inside a nested recursive declaration sequence (the declarations of the block that forms the body of the method), it creates a new object each time that method is called. Thus, it allows creation of objects dynamically, even though we create the objects by object declarations. We can use this concept of recursive declaration sequence to achieve information hiding which provides the ability to hide generic functions.<ref name="craig">Craig Chambers and Gary T. Leavens (December 1996, Revised April 1997), "BeCecil, A Core Object-Oriented Language with Block Structure and Multimethods: Semantics and Typing".</ref>

Example of a nested class in Java is shown below <ref name="nestedclasses">Nested Classes</ref> :

public class OuterClass {
    private String outerInstanceVar;
    public class InnerClass {
       public void printVars() {
          System.out.println( "Print Outer Class Instance Var.:" + outerInstanceVar);
       }
    } 
}

Blocks are also used in control flow statements like for loop, while loop, do..while loop and do..until loop. The statements inside the loops are nothing but a block of executable statements, and these statements are executed as a single statements for every time the loop gets executed. Block structured programming identifies the blocks of code by embracing them within keywords or braces. Similarly, the loop constructs are embraced with braces, indicating a block of statements.

Example of a nested for loop and if loop construct in Java is shown below:

for(i = 0; i < n; i++) {
   for(j = 1; j < (n-i); j++) {
      if(a[j-1] > a[j]) {
         temp = a[j-1];
         a[j-1]=a[j];
         a[j]=temp;
      }
   }
}

Blocks are used to iterate over arrays or returning closures from a method in Ruby. A block is a closure in Ruby.<ref name="rubyblocks">Ruby Programming Language - Blocks and Iterators</ref>

Example of a block in Ruby is shown below <ref name="rubyguide">Dave Thomas, Chad Fowler and Andy Hunt, Programming Ruby 1.9: The Pragmatic Programmers’ Guide, ISBN: 1-934356-08-5.</ref> :

class BlockExample
   CONST = 0
   @@a = 3
   def return_closure
      a = 1
      @a = 2
      lambda { [ CONST, a, @a, @@a, yield ] }
   end
   def change_values
      @a += 1
      @@a += 1
   end
end
eg = BlockExample.new
block = eg.return_closure { "original" }
block.call # => [0, 1, 2, 3, "original"]
eg.change_values
block.call # => [0, 1, 3, 4, "original"]


There are many object oriented programming languages which use a block structure.

The more common programming languages like C++ and Java use block structures in [classes and control structures like the for loop, do..while, if..then..else and switch. Ruby also uses blocks in iterations over arrays or hash.

The less common object oriented programming languages which supported block structure are: BeCecil is an object oriented language like Cecil, CLOS and Dylan, but along with the mechanisms of inheritance and information hiding, it is also block structured.<ref name="craig"/> The other main object oriented languages that allow full use of block structure are Stimula 67 and Beta <ref name="craig"/> where the block structure is present in the form of nested classes.<ref name="ole">Ole Lehrmann Madsen (November 1987), "Block Structure and Object Oriented Languages", DAIMI PB-230</ref>

Conclusion

Structured programming is essentially a forerunner of object oriented programming. Both the paradigms have their own advantages and limitations. But we can clearly deduce that the limitation of block structured programming are resolved by the advantages of object oriented programming.

Object oriented programming provides a revolutionary new way of looking at computer programming. Historically, programs have been viewed as procedures (or we may think of these as "verbs") that operate on data. OOP takes the view that programs should start by thinking about the data (or "nouns") first.<ref name="glossary">Glossary</ref>

See Also


References

<references/>

External Links