CSC/ECE 517 Fall 2010/ch1 1e vs: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(27 intermediate revisions by 2 users not shown)
Line 2: Line 2:
----
----
==Introduction==
==Introduction==
This article mainly compares and contrasts [http://en.wikipedia.org/wiki/Block_(programming) Block-Structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object-Oriented programming] and also focuses on the advantages of Object-Oriented programming over Block-structured programming. It also emphasizes on the usage of block structures in Object-Oriented programming.
Block structured languages are those languages whose structures are modularized into sections of code enclosed between bracketed keywords. The object oriented languages are those which are organized around data rather than logic. The article presented mainly compares and contrasts [http://en.wikipedia.org/wiki/Block_(programming) Block-Structured programming] and [http://en.wikipedia.org/wiki/Object-oriented_programming Object-Oriented programming] and focuses on the advantages of Object-Oriented programming over Block-structured programming. It also emphasizes on the usage of block structures in Object-Oriented programming.


==What is a Block-Structured Programming?==
==What is a Block-Structured Programming?==
A block is a section of [http://en.wikipedia.org/wiki/Computer_code code] which is grouped together and consists of one or more declarations and statements.  
A block is a section of [http://en.wikipedia.org/wiki/Computer_code code] which is grouped together and consists of one or more declarations and statements enclosed within the bracketed keywords like if....fi.  


A block structured programming languages is a class of high level programming languages that allows the creation of blocks and includes the nested blocks as components where nesting could be extended to any depth. Some examples of block structured languages are: [http://en.wikipedia.org/wiki/ALGOL ALGOL],[http://en.wikipedia.org/wiki/Pascal_(programming_language PASCAL],[http://en.wikipedia.org/wiki/Fortran FORTRAN] etc..
A block structured programming <ref> [http://en.wikipedia.org/wiki/Block_(programming) Block (programming)] </ref> languages is a class of high level programming languages that allows the creation of blocks and includes the nested blocks as components where nesting could be extended to any depth. Some examples of block structured languages are: [http://en.wikipedia.org/wiki/ALGOL ALGOL],[http://en.wikipedia.org/wiki/Pascal_(programming_language PASCAL],[http://en.wikipedia.org/wiki/Fortran FORTRAN] etc..
Block structured languages have a syntax such that the structures are enclosed within the bracketed keywords like if....fi in [http://en.wikipedia.org/wiki/ALGOL ALGOL] language.
 
The code snippet in [http://en.wikipedia.org/wiki/ALGOL ALGOL] below is an example which calculates the arithmetic mean by taking the number of samples and then asking for the values of the samples. It is block structured because of its modularized sections of code with the "begin" and "end" keywords. The scope of variables depends on where they are declared in the program. For example, N is an integer that has scope throughout the code whereas the array, sum, avg variables have the scope after reading the number of samples and the val variable has the local scope inside the for loop where the values are read for each sample.


An example of a block in [http://en.wikipedia.org/wiki/ALGOL ALGOL] looks as shown below:


<code>
<code>
Line 39: Line 39:
*'''Concatenation:''' Concatenation is the element which is responsible for the logical sequence of the statements that make up the basics for the order to be executed.  
*'''Concatenation:''' Concatenation is the element which is responsible for the logical sequence of the statements that make up the basics for the order to be executed.  


*'''Selection:''' Selection is the second element included in the process of structural programming which allows selection of any one of a number of statements to execute, based on the current status of the program. Generally, the selection statements contain keywords like “if,” “then,” “endif,” or “switch.” to identify the order as a logical executable.
*'''Selection:''' Selection is the second element included in the process of structural programming which allows selection of any one of a number of statements to execute, based on the current status of the program. Generally, the selection statements contain keywords like “if,” “then,” “endif,” or “switch” to identify the order as a logical executable.


*'''Repetition:''' In repetition a selected statement remains active until the program reaches a point where there is a need for some other action to take place. Repetition normally includes keywords such as ”repeat,” “for,” or “do…until.” Essentially, repetition instructs the program how long to continue the function before requesting further instructions.  
*'''Repetition:''' In repetition a selected statement remains active until the program reaches a point where there is a need for some other action to take place. Repetition normally includes keywords such as ”repeat,” “for,” or “do…until.” Essentially, repetition instructs the program how long to continue the function before requesting further instructions.  
Line 61: Line 61:


==What is Object-Oriented Programming?==
==What is Object-Oriented Programming?==
Object-Oriented programming is a programming paradigm using [http://en.wikipedia.org/wiki/Object_(computer_science) "objects"]- the data structures which consists of data fields and methods together with their interactions to design the applications and computer programs. The programming techniques include features like [http://en.wikipedia.org/wiki/Data_abstraction data abstraction], [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], [http://en.wikipedia.org/wiki/Message_passing messaging], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Inheritance_(computer_science) inheritance].
Object-Oriented programming is a programming paradigm using [http://en.wikipedia.org/wiki/Object_(computer_science) "objects"]- the data structures which consists of data fields and methods together with their interactions to design the applications and computer programs. It is a type of programming language where the programmers define not only the data type of a structure but also the type of functions that can be applied to the data structure<ref>[http://www.delphibasics.co.uk/Article.asp?Name=OO Object Oriented Overview ]</ref>.
It is a type of programming language where the programmers define not only the data type of a structure but also the type of functions that can be applied to the data structure.


An example of the code from JAVA language is as follows:
Below is an example of the code from JAVA language where there are two classes, Tree and PlantTrees and three objects are created to find the heights for each of the three objects. 


<code>
<code>
  Class HelloWorld
  class Tree
  {
  {  
   public static void main(String args[])
   public int height = 0;
  {
  public void grow()  
    System.out.println("Hello world!"):
  {
    System.out.println("Arguments you have entered is:");
     height = height + 1;  
    if (args.length>0)
  }
    {
      for(int i=0;i<args.length;i++)
      {
        System.out.print(args[i]+" ");
      }
      System.out.println();
    }
     else
      System.out.println("<<No Arguments>>");
    }  
  }
  }
class PlantTrees
{
  public static void main(String[] args)
  { 
    System.out.println("Let's plant some trees!");
    Tree tree1 = new Tree();
    System.out.println("I've created a tree with a height of " + tree1.height + " meter(s)."); 
    tree1.grow();
    System.out.println("After a bit of growth, it is now up to " + tree1.height + " meter(s) tall.");
    Tree tree2 = new Tree(); 
    Tree tree3 = new Tree();
    tree2.grow();
    tree3.grow(); 
    tree2.grow(); 
    tree3.grow();
    tree2.grow();
    System.out.println("Here are the final heights:");   
    System.out.println(" tree1: " + tree1.height + "m"); 
    System.out.println(" tree2: " + tree2.height + "m"); 
    System.out.println(" tree3: " + tree3.height + "m"); 
  }
</code>
Code Output:
<code>
Let's plant some trees!
I've created a tree with a height of 0 meter(s). 
After a bit of growth, it is now up to 1 meter(s) tall.
Here are the final heights:
tree1: 1m   
tree2: 3m 
tree3: 2m 
</code>
</code>


Line 113: Line 136:
==Transition from Block Structured to OO Programming?==
==Transition from Block Structured to OO Programming?==
===History===
===History===
Before the emergence of block structured programming,programmers used to write their code as a continuous stretch of code that extended line after line without any organized structure. This approach was tedious in terms of understanding,debugging and maintaining. This lead to the developement of structural programming.
Before the emergence of block structured programming,programmers used to write their code as a continuous stretch of code that extended line after line without any organized structure. This approach was tedious in terms of understanding,debugging and maintaining. This lead to the developement of structural programming <ref> [http://www.wisegeek.com/what-is-structured-programming.htm Structured Programming] </ref>.


The principle idea behind structured programming was the idea of divide and conquer. A computer program was considered as a set of tasks and any task that is too complex to be described simply would be broken down into a set of smaller component tasks, until the tasks were sufficiently small and self-contained enough that they were easily understood. This was termed as the top-down methodand was found to be adequate for coding moderately extensive programs. Some examples of structured programming languages are: [http://en.wikipedia.org/wiki/Fortran FORTRAN], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL ALGOL],[http://en.wikipedia.org/wiki/C_(programming_language) C] etc.
The principle idea behind structured programming <ref>[http://bulletin.sigchi.org/1997/october/papers/ross/ Structured Programmers learning Object Oriented Programming] </ref> was the idea of divide and conquer. A computer program was considered as a set of tasks and any task that is too complex to be described simply would be broken down into a set of smaller component tasks, until the tasks were sufficiently small and self-contained enough that they were easily understood. This was termed as the top-down method and was found to be adequate for coding moderately extensive programs. Some examples of structured programming languages are: [http://en.wikipedia.org/wiki/Fortran FORTRAN], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL ALGOL],[http://en.wikipedia.org/wiki/C_(programming_language) C] etc.


[http://en.wikipedia.org/wiki/Block_(programming) Block-Structured programming] remained an enormously successful approach for dealing with complex problems until the late 1980s, when the size of programs increased and some of the deficiencies of structured programming had become evident.Some of these problems included:
[http://en.wikipedia.org/wiki/Block_(programming) Block-Structured programming] remained an enormously successful approach for dealing with complex problems until the late 1980s, when the size of programs increased and some of the deficiencies of structured programming had become evident.Some of these problems included:
Line 121: Line 144:
*In this type of methodology as the emphasis is on functions, as the actions became more involved or abstract, the functions grew to be more complex.
*In this type of methodology as the emphasis is on functions, as the actions became more involved or abstract, the functions grew to be more complex.


*Hierarchical structuring for data and procedures produced cumbersome code with large amounts of "tramp data"
*Hierarchical structuring for data and procedures produced cumbersome code with large amounts of [http://en.wiktionary.org/wiki/tramp_data tramp data].


*Usage of global subprogram names and variables was recognized dangerous.  
*Usage of global subprogram names and variables was recognized dangerous.  
Line 129: Line 152:
===Why OOP?===
===Why OOP?===


[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] was developed to respond to these needs, providing techniques for managing enormous complexity, achieving reuse of software components, and coupling data with the tasks that manipulate that data.Object Oriented programming paradigm used "[http://en.wikipedia.org/wiki/Object_(computer_science) objects]" which were considered to be [http://en.wikipedia.org/wiki/Data_structure data structures] consisting of data fields and [http://en.wikipedia.org/wiki/Method_(computer_science) methods] together with their interactions. It also took the concept of [http://en.wikipedia.org/wiki/Subroutine subroutines] into a completely different zone.  
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] was developed to respond to the above needs, providing techniques for managing enormous complexity, achieving reuse of software components, and coupling data with the tasks that manipulate that data.
 
* Object Oriented programming paradigm used "[http://en.wikipedia.org/wiki/Object_(computer_science) objects]" which were considered to be [http://en.wikipedia.org/wiki/Data_structure data structures] consisting of data fields and [http://en.wikipedia.org/wiki/Method_(computer_science) methods] together with their interactions. It also took the concept of [http://en.wikipedia.org/wiki/Subroutine subroutines] into a completely different zone.
 
*The main advantage of object oriented programming over other languages is that they enable programmers to create modules that need not be changed when a type of object is added. Software objects model real world objects and so the complexity is reduced and the program structure becomes very clear.
 
The main features that make the object oriented better are modifiability, extensibility, maintainability, portability, scalability and reusability.
*Modifiability ensures that it is easy to make minor changes in the data representation or the procedures in an OO program. And any changes inside the class will not affect any other part of a program.
*Extensibility is adding new features or responding to changing operating environments by introducing new objects and modifying some existing ones.
*Maintanability is the feature where the objects can be maintained and the problems can be fixed easier.
*Reusability is a very important feature where the objects can be reused in different programs.


The main advantage of object oriented programming over other languages is that they enable programmers to create modules that need not be changed when a type of object is added. Software objects model real world objects and so the complexity is reduced and the program structure becomes very clear. The main features that make the object oriented better are modifiability, extensibility, maintainability, portability, scalability and reusability. Modifiability ensures that it is easy to make minor chnages in the data representation or the procedures in an OO program. And any changes inside the class will not affect any other part of a program. Extensibility is adding new features or responding to changing operating environments can be solved by introducing new objects and modifying some existing ones. Maintanability is the feature where the objects can be maintained and the problems can be fixed easier. Reusability is a very important feature where the objects can be reused in different programs.
This makes OOP efficient for more complicated and flexible interactions. For many systems, an OO approach can speed development time since many objects are standard across systems and can be reused.
This makes OOP efficient for more complicated and flexible interactions. For many systems, an OO approach can speed development time since many objects are standard across systems and can be reused.


Line 139: Line 171:
==Comparision between Block Structured and OO Programming==
==Comparision between Block Structured and OO Programming==


'''Block-Structured languages vs. Object-oriented languages'''
'''Block-Structured languages vs. Object-oriented languages'''<ref>[http://askville.amazon.com/Compare-Contrast-Structured-programming-Object-Oriented/AnswerViewer.do?requestId=2470573 Compare and contrast structured and object oriented]</ref> <ref>[http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/ Structured vs. Object oriented Programming]</ref>


{| class="wikitable" border="1"
{| class="wikitable" border="1"
Line 150: Line 182:
| The focus is around the data structures and subroutines. The subroutines are where actually where stuff happens and data structures are just the containers of the data required by the subroutines.
| The focus is around the data structures and subroutines. The subroutines are where actually where stuff happens and data structures are just the containers of the data required by the subroutines.
| The primary focus of object-oriented programming is on the data itself. Here the types are designed first and then come up with the operations needed to work with them.
| The primary focus of object-oriented programming is on the data itself. Here the types are designed first and then come up with the operations needed to work with them.
|-
| '''Approach'''
| Block Structured languages follow a Top-down approach.
| Object Oriented languagues follow a Bottom-up approach.
|-
| '''Program design'''
| It is complex since the procedure orientation forces the designer to map the real-world problems to features of the programming language.
| It is simpler because the object orientation allows the designer to work with a much higher level conceptual model of the real-world problem.
|-
|-
| '''Data Protection'''
| '''Data Protection'''
Line 158: Line 198:
| It is tedious at the language level if the language does not support OOP.
| It is tedious at the language level if the language does not support OOP.
| It is easily accomplished at this language level by defining a new class for the data type.
| It is easily accomplished at this language level by defining a new class for the data type.
|-
| '''Program design'''
| It is complex since the procedure orientation forces the designer to map the real-world problems to features of the programming language.
| It is simpler because the object orientation allows the designer to work with a much higher level conceptual model of the real-world problem.
|-
| '''Approach'''
| Block Structured languages follow a Top-down approach.
| Object Oriented languagues follow a Bottom-up approach.
|-
|-
| '''Dynamic Binding'''
| '''Dynamic Binding'''
Line 199: Line 231:
In most programming languages, a statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block). In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block. A block is a group of statements separated by a semicolon(;) but grouped together in a block enclosed in braces : {}:  
In most programming languages, a statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block). In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block. A block is a group of statements separated by a semicolon(;) but grouped together in a block enclosed in braces : {}:  


The basic building blocks of object oriented languages are considered as objects and classes. Class is the building block that encapsulates both data and functionality. The blocks in object oriented languages are used to concisely represent some code that would typically be written with loops in some other languages by using looping constructs such as 'if-else', 'while', 'for' etc.. in JAVA. Blocks allow control structure to be implemented using messages and polymorphism. Blocks are used to implement user-defined control structures, enumerators, visitors, pluggable behavior and many other patterns. In any object oriented language, all the programs are designed around functions or block of statements which manipulate data. These languages allow the programmers to think in terms of building blocks that are closer to what program actually will do. The well known programming quality criteria are programming speed, error correction speed, computation speed, readability and portability and the importance of a hierarchical description of systems. The use of encapsulation, inheritance and polymorphism fulfill the previously mentioned criteria without the need to incorporate complex kernels to control data flows. The block structure enables recycling blocks of program code. Once a block of program code is written, it can be reused in any number of programs unlike traditional programming. The methods which represent the operations are declared in the class blocks and the methods are implemented in the method blocks.  
The basic building blocks of object oriented languages are considered as objects and classes. Class is the building block that encapsulates both data and functionality. The blocks in object oriented languages are used to concisely represent some code that would typically be written with loops in some other languages by using looping constructs such as 'if-else', 'while', 'for' etc.. in JAVA. Blocks allow control structure to be implemented using messages and polymorphism. Blocks are used to implement user-defined control structures, enumerators, visitors, pluggable behavior and many other patterns. In any object oriented language, all the programs are designed around functions or block of statements which manipulate data. These languages allow the programmers to think in terms of building blocks that are closer to what program actually will do. The well known programming quality criteria are programming speed, error correction speed, computation speed, readability and portability and the importance of a hierarchical description of systems. The use of encapsulation, inheritance and polymorphism fulfill the previously mentioned criteria without the need to incorporate complex kernels to control data flows. The block structure enables recycling blocks of program code. Once a block of program code is written, it can be reused in any number of programs unlike traditional programming. The methods which represent the operations are declared in the class blocks and the methods are implemented in the method blocks.<ref>[http://drhanson.s3.amazonaws.com/storage/documents/blockstructure.pdf Is Block Structure necessary]</ref> 


Let us now see the usage of blocks in some Object Oriented Languages:
Let us now see the usage of blocks in some Object Oriented Languages:
'''Usage of Blocks in Ruby:'''
In Ruby, closure is called a block.  
In Ruby, closure is called a block.  
In an object instance variable (denoted with '@'), remember a block:
In an object instance variable (denoted with '@'), remember a block:
Line 243: Line 278:
*3.14
*3.14


'''Usage of blocks in CPP:'''
'''Usage of blocks in Java:'''


C++ also uses blocks in many situations like in conditional structures like if and else.
Java also uses blocks in many situations like in conditional structures like if and else, looping constructs like "while", "for" etc.
The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
Let us for instance consider the while statement.The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as follows:


if (condition) statement
<code>
 
while (expression) {
Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure.
    statement(s)
For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:
}
 
<code>
  if (x == 100)
  cout << "x is 100";
</code>
</code>


If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }:
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following PrintCount program:


<code>
<code>
  if (x == 100)
  class PrintCount {
{
    public static void main(String[] args){
  cout << "x is ";
          int count = 1;
  cout << x;
          while (count < 11) {
              System.out.println("Count is: " + count);
              count++;
          }
    }
  }
  }
</code>
</code>


Hence, as seen above blocks form an integral part of programming practice in most of the languagues, but the importance given to the blocks and functions or to the data depends based on the paradigm used.
The statements included in the while block are blocks of code and cannot be avoided in situations such as these.This clearly proves that usage of blocks is not pertinent only to Block Structured Languages but also applies to Object Oriented languages as well.
Hence, blocks form an integral part of programming practice in most of the languagues, but the importance given to the blocks and functions or to the data depends based on the paradigm used.
 
==Conclusion==
Thus in conclusion we can say that, the structure of a block can be used in Object Oriented programming as it provides a better understanding of the code. Although Block Structured languages and Object Oriented languages have their own advantages, Object oriented languages are preferred in the present scenario because of the above mentioned features. The more complicated the project, the easier it is to leverage the strengths of object oriented design.


==See Also==
==See Also==
Line 280: Line 319:


==References==
==References==
* http://en.wikipedia.org/wiki/Block_(programming) Block Programming
<references/>
* http://bulletin.sigchi.org/1997/october/papers/ross/ Structured Programmers Learning Object-Oriented Programming
 
==External Links==
* http://www.cplusplus.com/doc/tutorial/control/ C++
* http://www.cplusplus.com/doc/tutorial/control/ C++
* http://askville.amazon.com/Compare-Contrast-Structured-programming-Object-Oriented/AnswerViewer.do?requestId=2470573 Contrast Structured and OOP
* http://www.cs.rpi.edu/~szymansk/OOF90/F90_Objects.html
* http://www.cs.rpi.edu/~szymansk/OOF90/F90_Objects.html
* http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/ Structured vs Object Oriented Programming
* http://www.ibiblio.org/g2swap/byteofpython/read/oops.html
* http://www.ibiblio.org/g2swap/byteofpython/read/oops.html
* http://www.delphibasics.co.uk/Article.asp?Name=OO Object Oriented Overview
* http://www.delphibasics.co.uk/Article.asp?Name=OO Object Oriented Overview
* http://www.triconsole.com/php/oop.php
* http://www.triconsole.com/php/oop.php
* http://www.wisegeek.com/what-is-structured-programming.htm What is Structured Programming
* http://ascelibrary.org/cpo/resource/1/jccee5/v18/i3/p226_s1 Object-Oriented Paradigm in Programming for Computer-Aided Analysis of Structures
* http://ascelibrary.org/cpo/resource/1/jccee5/v18/i3/p226_s1 Object-Oriented Paradigm in Programming for Computer-Aided Analysis of Structures
* http://expressionflow.com/category/object-oriented-programming/intro-to-oop-in-labview/
* http://expressionflow.com/category/object-oriented-programming/intro-to-oop-in-labview/
* http://dl.acm.org/citation.cfm?id=36164 Block Structure and Object Oriented Languages
* http://dl.acm.org/citation.cfm?id=36164 Block Structure and Object Oriented Languages
* http://en.wikipedia.org/wiki/Smalltalk Smalltalk
* http://en.wikipedia.org/wiki/Smalltalk Smalltalk
* http://drhanson.s3.amazonaws.com/storage/documents/blockstructure.pdf Is Block Structure Necessary?
* http://www.php-developer.org/learn-php-oop-object-oriented-programming-for-beginners-tutorial/ PHP
* http://www.php-developer.org/learn-php-oop-object-oriented-programming-for-beginners-tutorial/ PHP

Latest revision as of 03:10, 26 September 2011

CSC/ECE 517 Fall 2010/ch1 1e vs


Introduction

Block structured languages are those languages whose structures are modularized into sections of code enclosed between bracketed keywords. The object oriented languages are those which are organized around data rather than logic. The article presented mainly compares and contrasts Block-Structured programming and Object-Oriented programming and focuses on the advantages of Object-Oriented programming over Block-structured programming. It also emphasizes on the usage of block structures in Object-Oriented programming.

What is a Block-Structured Programming?

A block is a section of code which is grouped together and consists of one or more declarations and statements enclosed within the bracketed keywords like if....fi.

A block structured programming <ref> Block (programming) </ref> languages is a class of high level programming languages that allows the creation of blocks and includes the nested blocks as components where nesting could be extended to any depth. Some examples of block structured languages are: ALGOL,PASCAL,FORTRAN etc..

The code snippet in ALGOL below is an example which calculates the arithmetic mean by taking the number of samples and then asking for the values of the samples. It is block structured because of its modularized sections of code with the "begin" and "end" keywords. The scope of variables depends on where they are declared in the program. For example, N is an integer that has scope throughout the code whereas the array, sum, avg variables have the scope after reading the number of samples and the val variable has the local scope inside the for loop where the values are read for each sample.


begin
  integer N;
  Read Int(N);
  begin
    real array Data[1:N]
    real sum,avg;
    sum:=0;
    for i:=1 step 1 until N do
       begin real val;
        Read Real (val);
        Data[i]:=if val<0 then -val else val
       end;
    for i:=1 step 1 until N do
     sum:=sum+Data[i];
   avg:=sum/N;
   Print Real(avg);
  end 
end

Features

The essential composition of block structured programming tends to include three basic elements:

  • Concatenation: Concatenation is the element which is responsible for the logical sequence of the statements that make up the basics for the order to be executed.
  • Selection: Selection is the second element included in the process of structural programming which allows selection of any one of a number of statements to execute, based on the current status of the program. Generally, the selection statements contain keywords like “if,” “then,” “endif,” or “switch” to identify the order as a logical executable.
  • Repetition: In repetition a selected statement remains active until the program reaches a point where there is a need for some other action to take place. Repetition normally includes keywords such as ”repeat,” “for,” or “do…until.” Essentially, repetition instructs the program how long to continue the function before requesting further instructions.

The exact nature of block structured programming will varies depending on the purpose and function of the program.

Advantages

  • Restricted visibility to local identifiers.
  • Efficient use of storage.
  • Learning and programming of the language is both quick and relatively easy.
  • Turn around time is likely to be quite rapid, since the number of de-bugging runs is usually small.

Limitations

  • Focus is given on the procedure (logic) and not to the data on which these procedures operate.
  • The data need to be global but global data makes the code complex.
  • As the code size grows, maintaining code becomes difficult and sometimes impossible.
  • Structured programming language is not ‘modular’ i.e., no reuse of code leading to redundant code.

What is Object-Oriented Programming?

Object-Oriented programming is a programming paradigm using "objects"- the data structures which consists of data fields and methods together with their interactions to design the applications and computer programs. It is a type of programming language where the programmers define not only the data type of a structure but also the type of functions that can be applied to the data structure<ref>Object Oriented Overview </ref>.

Below is an example of the code from JAVA language where there are two classes, Tree and PlantTrees and three objects are created to find the heights for each of the three objects.

class Tree 
{ 
  public int height = 0;
  public void grow() 
  { 
   height = height + 1; 
  }
}
class PlantTrees 
{ 
  public static void main(String[] args) 
  {  
   System.out.println("Let's plant some trees!"); 
   Tree tree1 = new Tree(); 
   System.out.println("I've created a tree with a height of " + tree1.height + " meter(s).");  
   tree1.grow(); 
   System.out.println("After a bit of growth, it is now up to " + tree1.height + " meter(s) tall."); 
   Tree tree2 = new Tree();  
   Tree tree3 = new Tree();
   tree2.grow();
   tree3.grow();  
   tree2.grow();  
   tree3.grow(); 
   tree2.grow();
   System.out.println("Here are the final heights:");     
   System.out.println(" tree1: " + tree1.height + "m");   
   System.out.println(" tree2: " + tree2.height + "m");   
   System.out.println(" tree3: " + tree3.height + "m");   
  }
}  

Code Output:

Let's plant some trees! 
I've created a tree with a height of 0 meter(s).  
After a bit of growth, it is now up to 1 meter(s) tall. 
Here are the final heights: 
tree1: 1m     
tree2: 3m   
tree3: 2m  

Features

  • Inheritance: Inheritance establishes relationships among classes where it helps the objects to work together and makes it easy to extend existing structures to produce new structures with slightly different behavior.
  • Encapsulation: Encapsulation is defined as the process of binding or wrapping the data and the code that operates on the data into a single entity. This keeps the data safe from outside interface and misuse.
  • Data Abstraction: Data abstration is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. Abstraction can denote a model, a view, or some other focused representation for an actual item and is used to manage complexity.
  • Polymorphism: The concept of polymorphism can be explained as "one interface, multiple methods". Polymorphism enables one entity to be used as as general category for different types of actions and there are two basic types of polymorphism. Overridding, also called run-time polymorphism and Overloading, which is referred to as compile-time polymorphism.

Advantages

  • Simulates real-world event much more effectively
  • Code is reusable thus less code may have to be written
  • Data becomes active
  • Better ability to create GUI (graphical user interface) applications
  • Ability to reach their goals faster
  • Programmers are able to produce faster, more accurate and better-written applications

Limitations

  • Best suited for dynamic, interactive environments but becomes complicated for systems that don't require so much complexity.
  • OOP provides only one representation (object-oriented).
  • Although OOP technology allows the creation of reusable components, programmers may not know what reusable components already exist, how to access them, how to understand them, and how to combine, adapt, and modify them to meet current needs.

Transition from Block Structured to OO Programming?

History

Before the emergence of block structured programming,programmers used to write their code as a continuous stretch of code that extended line after line without any organized structure. This approach was tedious in terms of understanding,debugging and maintaining. This lead to the developement of structural programming <ref> Structured Programming </ref>.

The principle idea behind structured programming <ref>Structured Programmers learning Object Oriented Programming </ref> was the idea of divide and conquer. A computer program was considered as a set of tasks and any task that is too complex to be described simply would be broken down into a set of smaller component tasks, until the tasks were sufficiently small and self-contained enough that they were easily understood. This was termed as the top-down method and was found to be adequate for coding moderately extensive programs. Some examples of structured programming languages are: FORTRAN, Pascal, ALGOL,C etc.

Block-Structured programming remained an enormously successful approach for dealing with complex problems until the late 1980s, when the size of programs increased and some of the deficiencies of structured programming had become evident.Some of these problems included:

  • In this type of methodology as the emphasis is on functions, as the actions became more involved or abstract, the functions grew to be more complex.
  • Hierarchical structuring for data and procedures produced cumbersome code with large amounts of tramp data.
  • Usage of global subprogram names and variables was recognized dangerous.
  • Also, a small change, such as requesting a user-chosen new option (text font-color) could cause a massive ripple-effect with changing multiple subprograms to propagate the new data into the program's hierarchy.

Why OOP?

Object-oriented programming was developed to respond to the above needs, providing techniques for managing enormous complexity, achieving reuse of software components, and coupling data with the tasks that manipulate that data.

  • Object Oriented programming paradigm used "objects" which were considered to be data structures consisting of data fields and methods together with their interactions. It also took the concept of subroutines into a completely different zone.
  • The main advantage of object oriented programming over other languages is that they enable programmers to create modules that need not be changed when a type of object is added. Software objects model real world objects and so the complexity is reduced and the program structure becomes very clear.

The main features that make the object oriented better are modifiability, extensibility, maintainability, portability, scalability and reusability.

  • Modifiability ensures that it is easy to make minor changes in the data representation or the procedures in an OO program. And any changes inside the class will not affect any other part of a program.
  • Extensibility is adding new features or responding to changing operating environments by introducing new objects and modifying some existing ones.
  • Maintanability is the feature where the objects can be maintained and the problems can be fixed easier.
  • Reusability is a very important feature where the objects can be reused in different programs.

This makes OOP efficient for more complicated and flexible interactions. For many systems, an OO approach can speed development time since many objects are standard across systems and can be reused.

Its programming techniques included features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance which changed the face of programming for many people. Some of the most commonly used object-oriented programming languages are: C++, Java etc..

Comparision between Block Structured and OO Programming

Block-Structured languages vs. Object-oriented languages<ref>Compare and contrast structured and object oriented</ref> <ref>Structured vs. Object oriented Programming</ref>

Properties Block-Structured languages Object-oriented languages
Primary focus The focus is around the data structures and subroutines. The subroutines are where actually where stuff happens and data structures are just the containers of the data required by the subroutines. The primary focus of object-oriented programming is on the data itself. Here the types are designed first and then come up with the operations needed to work with them.
Approach Block Structured languages follow a Top-down approach. Object Oriented languagues follow a Bottom-up approach.
Program design It is complex since the procedure orientation forces the designer to map the real-world problems to features of the programming language. It is simpler because the object orientation allows the designer to work with a much higher level conceptual model of the real-world problem.
Data Protection These languages do not prohibit a code that directly accesses global data, and local variables are not very useful for representing data that must be accessed by many functions. Object-Oriented languages enforce "hiding" of data declared private in a class which can be accessed externally only through the public member functions of that class.
Creation of new data types It is tedious at the language level if the language does not support OOP. It is easily accomplished at this language level by defining a new class for the data type.
Dynamic Binding Instance variables, static variables, static overridden methods and overloaded methods are all bound at compile time. OOP enables polymorphism in which objects belonging to different types respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. So the exact behavior is determined at run-time (called late binding or dynamic binding).
Comprehension of the program Rigorous due to poor equivalence between the program variables and physical entities More apparent due to the close match between program classes and real-world classes.
Modularity Not as good since data structures and functions are not linked. Better since related data and functions are placed in the same module.
Complexity Simple to understand small programs but gets complicated when the code gets large. Easy to understand but can get complex in some cases by unnecessary abstraction.
Maintainance and extension of the program Requires high degree of knowledge of the entire program. Convenient due to enhanced modularity of the program.
Reusability of code Difficult to reuse since submodules are generally coded to satisfy specific needs of a higher level module Easy to use the existing classes without modification by deriving sub classes with additional items and functions required for specific application
Examples C, ALGOL 60, PASCAL are examples of block-structured languages. C++ and JAVA are examples of object-oriented languages.

Usage of Block Structures in Object Oriented Programming

In most programming languages, a statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block). In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block. A block is a group of statements separated by a semicolon(;) but grouped together in a block enclosed in braces : {}:

The basic building blocks of object oriented languages are considered as objects and classes. Class is the building block that encapsulates both data and functionality. The blocks in object oriented languages are used to concisely represent some code that would typically be written with loops in some other languages by using looping constructs such as 'if-else', 'while', 'for' etc.. in JAVA. Blocks allow control structure to be implemented using messages and polymorphism. Blocks are used to implement user-defined control structures, enumerators, visitors, pluggable behavior and many other patterns. In any object oriented language, all the programs are designed around functions or block of statements which manipulate data. These languages allow the programmers to think in terms of building blocks that are closer to what program actually will do. The well known programming quality criteria are programming speed, error correction speed, computation speed, readability and portability and the importance of a hierarchical description of systems. The use of encapsulation, inheritance and polymorphism fulfill the previously mentioned criteria without the need to incorporate complex kernels to control data flows. The block structure enables recycling blocks of program code. Once a block of program code is written, it can be reused in any number of programs unlike traditional programming. The methods which represent the operations are declared in the class blocks and the methods are implemented in the method blocks.<ref>Is Block Structure necessary</ref>

Let us now see the usage of blocks in some Object Oriented Languages:

Usage of Blocks in Ruby:

In Ruby, closure is called a block. In an object instance variable (denoted with '@'), remember a block:

def remember(&a_block)
 @block = a_block
end

Invoke the above method, giving it a block which takes a name:

remember {|name| puts "Hello, #{name}!"}

When the time is right (for the object) -- call the closure:

@block.call("Jon")

=> "Hello, Jon!"

Iterating over enumerations and arrays using blocks:

array = [1, 'hi', 3.14]
array.each {|item| puts item }

  • 1
  • 'hi'
  • 3.14

array.each_index {|index| puts "#{index}: #{array[index]}" }

  • 1
  • 'hi'
  • 3.14

Usage of blocks in Java:

Java also uses blocks in many situations like in conditional structures like if and else, looping constructs like "while", "for" etc. Let us for instance consider the while statement.The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as follows:

while (expression) {
    statement(s)
}

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following PrintCount program:

class PrintCount {
    public static void main(String[] args){
         int count = 1;
         while (count < 11) {
              System.out.println("Count is: " + count);
              count++;
         }
    }
}

The statements included in the while block are blocks of code and cannot be avoided in situations such as these.This clearly proves that usage of blocks is not pertinent only to Block Structured Languages but also applies to Object Oriented languages as well. Hence, blocks form an integral part of programming practice in most of the languagues, but the importance given to the blocks and functions or to the data depends based on the paradigm used.

Conclusion

Thus in conclusion we can say that, the structure of a block can be used in Object Oriented programming as it provides a better understanding of the code. Although Block Structured languages and Object Oriented languages have their own advantages, Object oriented languages are preferred in the present scenario because of the above mentioned features. The more complicated the project, the easier it is to leverage the strengths of object oriented design.

See Also

References

<references/>

External Links