CSC/ECE 517 Fall 2011/ch1 1e dm

From Expertiza_Wiki
Jump to navigation Jump to search

"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