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

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(199 intermediate revisions by 2 users not shown)
Line 1: Line 1:
L M
==Introduction==
This wiki article discusses two things viz the effectiveness & durability of object oriented languages (like Java, Python, etc) as compared to block structured languages(like C, Pascal, Algol etc) and how block structure can be leveraged in an object oriented language.


==Block structured languages==


5. Block-structured vs. o-o languages. Before o-o languages"took over the world" in the 1980s, the spotlight was on block-structured languages.  Why were o-o languages more effective and more durable than block-structured languages?  Can block structure be useful in an object-oriented language?  Explain.
===Definition===
A [http://en.wikipedia.org/wiki/Block_(programming) block] is a piece of code consisting of one or more [http://en.wikipedia.org/wiki/Declaration_(computer_science) declarations] and [http://en.wikipedia.org/wiki/Statement_(programming) statements]. A block structured programming language is the one that would allow usage of such blocks & including [http://en.wikipedia.org/wiki/Nesting_(computing) nesting] of such blocks.
The purpose of blocks is to allow a group of statements to be treated as one.For instance, you might want to have a block of statements which does matrix multiplication.Blocks also narrow the lexical scope of the variables, procedures & functions declared in a block so that they don’t conflict with others(which might be used for a totally different purpose)having the same name elsewhere in the program.For instance, you might want to have a local variable “count” to count the sum of some variables whereas you might have another local variable with the same name “count” to count the number of elements in an array.


===Basic features===
*Tasks are accomplished using functions. The primary focus is on functions. It involves creating a list of instructions and grouping them into blocks.
*The functions share global data. The data is stored in data structures which act as information containers. These are global in scope and are passed around between functions using parameters.
*It uses a top down approach<ref>[http://www.robdavispe.com/free2/software-qa-testing-test-tester-2229.html Davis, Rob. "What Is the Difference Between Top Down and Bottom up Design?" N.p., 2001. Web.]</ref> of program design. Here the system is broken down into sub-systems which are recursively refined into additional sub- system levels until we reach base level of granularity which can be implemented by a single function.
*Functions are implemented as black-boxes<ref>[http://www.webopedia.com/TERM/B/Black_Box_Testing.html Black Box Testing]</ref> with an input and output specification.


Block structured languages<br>
===Examples===
Definition<br>
Some of the examples of these languages include Algol, C & Pascal.
Origin<br>
*E.g. Pascal program multiply two numbers.
Examples<br>
Here we can see that the block is delimited by "Begin" & "End" keywords.


o-o languages motivation<br>
<nowiki>
o-o advantages over block-structured<br>
Program Multiplication_Of_Two_Numbers;
Block structured vs o-o languages<br>
 
usefulness of bloc-structured in o-o with examples<br>
Var Product, Multiplier, Multiplicand : Real;
 
Begin
    Writeln('Program to multiply 2 numbers:');
    Writeln;
    Writeln;
    Write('Enter the Multilicand: ');
    Readln(Multiplicand);
    Writeln;
    Write('Enter the Multiplier: ');
    Readln(Multiplier);
 
    Product := Multiplicand * Multiplier;
    Writeln;
    Writeln('Product of ',Multiplicand,'and ',Multiplier,'equals '+
          +'to ',Product);
 
End.
 
</nowiki>
 
*E.g. C program to read a file line by line.
Here we can see that the blocks are delimited by the flower braces. We can also see the usage of global variable by the function print_file().
Also, the print_file returns an integer which represents success. By using return a called block can return a value to the scope of the calling block.
 
<nowiki>
#include<stdio.h>
 
FILE *ifp;                                                                /*File pointer which points to the file*/
 
int print_file(char *filename)
{
      char line[80];                                                      /*Assuming each line is 80 character in length*/
      ifp = fopen(*filename, "r");                                        /*opens the file for "reading" mode only*/
      if(!ifp)
          return -1;
      while(fgets(line,1,sizeof(line),fp)                                  /*Loop till no more lines to read*/
      {
            printf("%s", line);                                            /*Prints this line on to the standard output*/
      }
      fclose(fp);                                                          /*Closes the file*/
      return 0;
}
 
void main()
{
    char *name;
    int success;
 
    printf("Enter the name of the file to be opened: ");
    scanf("%s", name);         
   
    success = print_file(name);                                                    /*Function call made to print_file() to print the file*/
    if(success == -1)
          printf("\n Error opening file");
}
</nowiki>
 
==Object Oriented Languages:==
 
===Definition===
Object oriented languages are built on the object oriented concept. This is the programming paradigm that bundles the data and the methods that access and manage this data into single entity called an '''''Object'''''. This bundling of data and methods allows the object to act as a single entity and have a fluid interface through which it can interact with the outside world. The objects are generally modeled on real world objects.
 
===Fundamental features of Object Oriented languages===
*[http://en.wikipedia.org/wiki/Object_%28computer_science%29 Object]/[http://en.wikipedia.org/wiki/Class_%28computer_programming%29 Class]: Class consists of tightly coupled data fields and set of operations that act on the data. The entire set of data and operations represent a user-defined data type. An object is an instance of a class. Thus a class acts as a collection of objects of similar type. Multiple objects may be created out of a class. The objects may share the operations of the class but have their own set of data fields. An object can be defined by its current state (current value of its data members) and its behavior (the methods that can be called on the object). 
 
*[http://en.wikipedia.org/wiki/Abstraction_(computer_science) Data Abstraction]/[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation]: The wrapping of data and functions into a single unit (class) is called encapsulation. Encapsulation protects an object from accidental modifications by an external entity since data fields can be accessed only through predetermined interfaces. Encapsulation is implemented using language constructs like private, public, protected, etc. Abstraction involves representing only the essential features of the object and hiding the background details. Classes provide abstraction by hiding the data attributes and providing functions that provide a controlled view of the object to an external entity.
 
*[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance]:  Inheritance is the ability of a class to inherit partly or completely the features of another class. It allows the hierarchical classification of objects.For example, the bird ''Peacock'' is a part of the class ''Flying bird'' which again is part of the class ''Bird''. Inheritance allows the reusability of code. Pre-existing classes can be reused by extending them and adding new functionality to create sub classes without modifying the original classes. The sub class will then have the combined features of both classes. This allows a programmer to tailor a new class from an existing class without introducing any undesirable side effects in the base classes.
 
*[http://en.wikipedia.org/wiki/Interface_%28Java%29 Interface]: Interface is an abstract type containing no data but only a list of method definitions. A class that has all the methods defined in the interface is said to have implemented the method interface. Interfaces allow classes to define how they will communicate with an external entity.  By implementing an interface, a class promises an external entity using the interface that it will provide the functionality specified by the interface.
 
*[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]/[http://en.wikipedia.org/wiki/Dynamic_dispatch Dynamic Binding]: This is the ability of a variable, method or an object to take more than one forms. This enables an objects of different types to respond to same method or property call but in its own type specific way. For example consider overloading the + operator, so that when called on strings, it concatenates the strings while for numbers it adds them up. Polymorphism also allows objects with different internal structures to share the same external interface. This helps in dynamic binding. Dynamic binding means that the code executed for a given function call is not known until actual runtime. For example, in a dynamically typed language a variable can hold an object irrespective of its data type. Hence a function call associated with a reference (variable) depends on the dynamic type of that reference (variable) i.e. the current object referenced by the variable.
 
===Examples===
The below languages implement different degrees of OO  features<ref>[http://www.jvoegele.com/software/langcomp.html Voegele, Jason. "Programming Language Comparison." Web.]</ref>
*Ruby, Scala, Smalltalk, Eiffel are said to be purely OO languages. Here even primitives are implemented as OO objects.
*Java, C++, C#, VB.NET, Python are OO languages but have some degree of procedural elements.
*Visual Basic, PHP, Perl are basically procedural languages with some OO features.
 
 
E.g. C++ program demonstrating the use of a class.
The class CRectangle represents a rectangle and has data members x,y which represent the length and breadth (ie: properties) of the rectangle. The functions set_values() and area() allow us to access these data members in a controlled manner. The class object has been instantiated in function main.
<nowiki>
 
#include <iostream>
using namespace std;
 
class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () ;
};
 
void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}
 
void CRectangle::area() {
  return x*y;
}
 
int main () {
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}
</nowiki>
 
==Need for Object Oriented Languages==
Block structured languages follow a task-centric approach rather than a data-centric approach. This resulted in certain flaws:
#Structured programming follows a hierarchy of structures. However in large programs data is generally in the form of a network of structures. This resulted in a lot of [http://en.wiktionary.org/wiki/tramp_data tramp data] being passed around.<ref> [http://en.wikipedia.org/wiki/Structured_programming#Object-oriented_comparison Object Oriented Comparison. Web. 8 June 2011.] </ref>
#As the program size increased the amount of data being passed around increased proportionately. Ensuring parameters are correctly passed to the correct subprogram becomes a major issue.
#In case of large programs even a small change resulted in massive ripple-effect with changing multiple sub modules to propagate the new data through the program's hierarchy.
#Structured program shared a lot of global data.<ref>[http://c2.com/cgi/wiki?GlobalVariablesAreBad Global Variables Are Bad]</ref> The access to the data was uncontrolled and unpredictable. There was no control over who had access to what.
#Structured program suffered from memory leaks.<ref>[http://www.cprogramming.com/debugging/valgrind.html Using Valgrind to Find Memory Leaks and Invalid Memory Use]</ref> This was because anyone could create global structures and there was no responsibility on the creator to deallocate the memory.
The main motivating factor for object-oriented approach is to remove these flaws of block structured languages. OO languages treat data as a critical element and do not allow it to flow freely around the system. The data is tied to the functions with operate on and prevent it from accidental modification from external functions.
 
==Advantages of Object-oriented languages over Block structured languages==
#Object oriented approach follows a data centered approach. It is possible to map objects in the problem domain to those in the program. This helps the programmer visualize the program in terms of real world objects and which leads to a much better design. Also it allows more details of a model to be captured in implementable form.<ref>Balaguruswamy, E. Object Oriented Programming with C++. New Delhi: Tata Mcgraw-Hill, 2008. Print.</ref>
#The principle of data hiding helps in building secure programs. The data fields of an object can be accessed only through the interface defined by its publicly accessible methods. Such controlled access prevents any inadvertent change to object data by external modules.<ref>[http://www.developer.com/design/article.php/3387591/Hiding-Data-within-Object-Oriented-Programming.htm Weisfeld, Matt. "Hiding Data within Object-Oriented Programming." N.p., 29 July 2004. Web.]</ref>
#Mapping real world entities into objects help reduce and easily manage software complexity . Also it helps when systems need to be upgraded to larger systems.<ref>[http://www.artima.com/interfacedesign/SigObjects.html "Interface Design by Bill Venners." Web.]</ref>
#Objects act as black boxes with internal structure and well defined interfaces. Hence adding new functionality becomes easier, since we can easily isolate the objects/classes that need to be modified or extended. The low coupling between objects allows an object to be modified without any effect on the other objects accessing it so long as the interface through which they interact remain untouched.
#Most modern object oriented languages provides a load of class libraries and frameworks. These are much easier to use as compared to library functions present in block structured languages. The frameworks help in rapid software development and easier testing and debugging thus leading to increased productivity.<ref>[http://www.cs.bgsu.edu/maner/domains/RAD.htm Maner, Walter. RAPID APPLICATION DEVELOPMENT. N.p., 15 Mar. 1997. Web.]</ref> <ref>[http://www.chillarege.com/authwork/TestingBestPractice.pdf Chillarege, Ram. "Software Testing Best Practices." N.p., 26 Apr. 1999. Web.]</ref>
#Message passing techniques (ex: interfaces in JAVA) help separate implementation of an object from its externally visible interface. Multiple classes of objects may implement the same interface. In such cases an object can be replaced by another object without affecting external entities dependent on that object so long as the interface is untouched. This results in low coupling.
#Object oriented design provides much better memory management. Recent OO languages sport automated garbage handling. Even for languages without garbage collection<ref>[http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html Paul, Javin. "Garbage Collection in Java." How Garbage Collection Works In Java. N.p., 11 Apr. 2011. Web. ]</ref>, memory deallocation of data members can be handled in the destructors of the objects. But in case of block structured languages (like C), it is the programmers responsibility to take care of releasing the dynamically allocated memory. Also the data structures tend to be global in scope and persist beyond the scope of the functions calling them. Hence it becomes difficult to fix responsibility on functions to deallocate them. This leads to memory leaks.
 
==Drawbacks of Object-Oriented Languages==
Although object oriented languages sport some very advantageous features as compared to block structured languages, they do have some drawbacks.
#Economy of language features: The addition of OO features to a language and the additional syntax needed to implement these features makes it bulky. The complexity of these languages make them daunting to learn and master.<ref name="badEnggProperties">[http://lucacardelli.name/Papers/BadPropertiesOfOO.html Bad Engineering Properties of Object-Oriented Languages by Luca Cardelli]</ref>
#Economy of execution: OO style is intrinsically less efficient as compared to block structured style. In procedural languages, type checking occurs at compile time. Hence no tests are needed at runtime for pointer dereferencing for method calls.In OO style each routine is supposed to be a virtual method. This introduces indirections in the form of method tables during for dereferencing.
#Also many OO languages include automatic garbage collection (e.g. Java) & hence it might slow down the performance.<ref>[http://www.jelovic.com/articles/why_java_is_slow.htm Why Java is slow Jelovic, Dejan. "Why Java Is Slow." Why Java Will Always Be Slower Than C++. N.p., 18 Dec. 2009. Web.]</ref>. This along with the overhead of creation and destruction of objects degrades performance in resource intensive systems such as embedded systems and real time systems.<ref>[http://csjournals.com/IJCSC/PDF1-2/9..pdf Object Oriented Vs Procedural Programming in Embedded System ]</ref>
 
==Usage of block-structures in Object Oriented languages==
OO languages have evolved from block structured languages. Though OO languages use the concepts of class and objects,inheritance,etc they inherently still rely on a blocks to define the structure of  the code. The key areas where OO languages assimilate the idea of block structure are as follows:
*In classes the member functions or methods are implemented using blocks. Each method can be viewed as a block that accepts parameters from an external entity that calls it, performs some processing (that may or may not require the use of data fields of the object) and returns control back with or without a return value. 
*Blocks are also useful in defining control structures like loops, conditional blocks(e.g. if...else), etc.
E.g. Java program demonstrating the usage of a while loop .The while loop encloses a group of statements within curly braces signifying a block that may be iterated upon till while condition holds true.
<nowiki>
package hashmap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
 
public class ExampleHashMap
{
public static void main(String args[])
{
LinkedHashMap h = new LinkedHashMap();                          //Creates a LinkedHashMap. Linked HashMaps defines the
h.put("A",100);                                                //iteration ordering, which is normally the
h.put("B",200);                                                //order in which keys were inserted into the map.
h.put("C",300);
h.put("D",400);
h.put("E",500);
Set s = h.entrySet();                                          //Returns a set containing key value pairs
Iterator i = s.iterator();                                     
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();                    //Each element in the set has to be casted to Map.Entry
System.out.println(me.getKey()+" : "+me.getValue());    //to access the key/value
}
      }
}
</nowiki>
*OO languages generally provide inbuilt language support for exception handling. Most OO languages implement exception handling in terms of blocks
E.g.: Try...catch  blocks in Java
Here the catch and finally blocks are used to delimit a group of statements that can be called to handle exceptions at runtime. Also, we can see usage of conditional statements if...else in this case.
<nowiki>
try{
    System.out.println("Inside try block of testMethod!");
    int p=1000, q=0, i=0;
    if(p>q){                                              //We can clearly see here that a Divide by Zero exception will occur.
        i=p/q;
    }
    else if(q>p){
        i=q/p;
    }
    else{                                                //In this case p equals q
        i=p/q;
    }
}
catch(Exception e){
    System.out.println("Inside catch block of testMethod!");
    System.out.println(“Caution: your trying to Divide a number by Zero...”);
}
finally{                                                 
    System.out.println("Inside finally block of testMethod!");
    System.out.println(“This block executes everytime an exception is caught...”);
}
</nowiki>
*Certain OO languages like JAVA allow creation of anonymous classes which are basically blocks which don’t have a name but can be instantiated without actually making a separate class.
E.g.
Here ActionListener is an interface which has been implemented as anonymous block in the below JAVA example.
<nowiki>
import java.awt.Button;
 
class Submit()
{
      public Submit()
      {
              Button button1 = new Button("Submit");
               
              button1.addActionListener(new ActionListener(){
                    public void actionPerformed (ActionEvent event){
                            System.out.println("actionPerfomed is implemented as anonymous class here & is added as a listener to button1");
                    } 
              });
      }
}
 
</nowiki>
*In a pure OO language like Ruby, blocks can also be used to defines closures(blocks, procs & lambdas)<ref>[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Sosinski, Robert. "Understanding Ruby Blocks, Procs and Lambdas." N.p., 21 Dec. 2008. Web. 8 Sept. 2011.]</ref>
E.g.
Given below is a method which yields control to a block in Ruby & also passes parameter to it at the same time.
<nowiki>
def block_demo
    yield("Smith")
end
 
block_demo { |name| puts " Hello #{name} " }
 
The Output will be
Hello Smith
</nowiki>
 
==Conclusion==
Block structured languages had their uses in earlier days when code size was small and the main focus was on efficiency(in terms of space & memory) of programs. However, these programs could not scale in size as maintenance and code complexity became an overhead.
 
Object Oriented concepts like encapsulation, inheritance(which helps in code re-usability), interfaces & polymorphism allowed better visualization of the software problem and its design to handle this complexity. Moreover, class libraries and frameworks developed in these languages helped abstract the code complexity and allowed rapid program development. This led to a gradual transition from block oriented to object oriented languages for application development.
 
 
 
==References==
<references/>
 
==External Links==
#[http://golang.org/ The Go Programming Language by Google for multicore and networked machines]
#[http://download.oracle.com/javase/tutorial/java/concepts/ Object Oriented Concepts (Java Tutorials)]
#[http://www.daimi.au.dk/publications/PB/230/PB-230.pdf  Block Structure and Object Oriented Languages by Ole Lehrmann Madsen]
#[http://portal.acm.org/citation.cfm?id=356671 A Tutorial on Algol 68, by Andrew S. Tanenbaum, in Computing Surveys, Vol. 8, No. 2, June 1976, with Corrigenda (Vol. 9, No. 3, September 1977) ]
#[http://ruby-lang.org Official Ruby Webpage]
#[http://www.pascal-programming.info/index.php Pascal programming tutorials]
#[http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html Dynamic Languages Strike Back]
#[http://amath.colorado.edu/computing/mmm/funcproc.html Functional vs Procedural languages]
#[http://www.scala-lang.org/ Scala Software]
#[http://www.smalltalk.org/main/ Smalltalk]
#[http://www.eiffel.com/ Eiffel Software]
#[http://www.cplusplus.com/doc/tutorial/ C++ Programming Language]
#[http://java.com/en/ Java Software]
#[http://msdn.microsoft.com/en-us/vcsharp/aa336809 The C Sharp Language]
#[http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express Visual Basic]
#[http://www.python.org/ Python Programming Language]
#[http://www.php.net/ PHP: Hypertext Preprocessor]
#[http://www.perl.org/ Perl Programming Language]

Latest revision as of 05:24, 29 September 2011

Introduction

This wiki article discusses two things viz the effectiveness & durability of object oriented languages (like Java, Python, etc) as compared to block structured languages(like C, Pascal, Algol etc) and how block structure can be leveraged in an object oriented language.

Block structured languages

Definition

A block is a piece of code consisting of one or more declarations and statements. A block structured programming language is the one that would allow usage of such blocks & including nesting of such blocks. The purpose of blocks is to allow a group of statements to be treated as one.For instance, you might want to have a block of statements which does matrix multiplication.Blocks also narrow the lexical scope of the variables, procedures & functions declared in a block so that they don’t conflict with others(which might be used for a totally different purpose)having the same name elsewhere in the program.For instance, you might want to have a local variable “count” to count the sum of some variables whereas you might have another local variable with the same name “count” to count the number of elements in an array.

Basic features

  • Tasks are accomplished using functions. The primary focus is on functions. It involves creating a list of instructions and grouping them into blocks.
  • The functions share global data. The data is stored in data structures which act as information containers. These are global in scope and are passed around between functions using parameters.
  • It uses a top down approach<ref>Davis, Rob. "What Is the Difference Between Top Down and Bottom up Design?" N.p., 2001. Web.</ref> of program design. Here the system is broken down into sub-systems which are recursively refined into additional sub- system levels until we reach base level of granularity which can be implemented by a single function.
  • Functions are implemented as black-boxes<ref>Black Box Testing</ref> with an input and output specification.

Examples

Some of the examples of these languages include Algol, C & Pascal.

  • E.g. Pascal program multiply two numbers.

Here we can see that the block is delimited by "Begin" & "End" keywords.

Program Multiplication_Of_Two_Numbers;

Var Product, Multiplier, Multiplicand : Real; 

Begin
    Writeln('Program to multiply 2 numbers:');
    Writeln;
    Writeln;
    Write('Enter the Multilicand: ');
    Readln(Multiplicand);
    Writeln;
    Write('Enter the Multiplier: ');
    Readln(Multiplier);
   
    Product := Multiplicand * Multiplier;
    Writeln;
    Writeln('Product of ',Multiplicand,'and ',Multiplier,'equals '+
           +'to ',Product);

End.


  • E.g. C program to read a file line by line.

Here we can see that the blocks are delimited by the flower braces. We can also see the usage of global variable by the function print_file(). Also, the print_file returns an integer which represents success. By using return a called block can return a value to the scope of the calling block.

#include<stdio.h>

FILE *ifp;                                                                 /*File pointer which points to the file*/

int print_file(char *filename)
{
      char line[80];                                                       /*Assuming each line is 80 character in length*/
      ifp = fopen(*filename, "r");                                         /*opens the file for "reading" mode only*/
      if(!ifp)
           return -1;
      while(fgets(line,1,sizeof(line),fp)                                  /*Loop till no more lines to read*/
      {
            printf("%s", line);                                            /*Prints this line on to the standard output*/
      }
      fclose(fp);                                                          /*Closes the file*/
      return 0;
}

void main()
{
     char *name;
     int success;

     printf("Enter the name of the file to be opened: ");
     scanf("%s", name);          
     
     success = print_file(name);                                                     /*Function call made to print_file() to print the file*/
     if(success == -1)
           printf("\n Error opening file");
}

Object Oriented Languages:

Definition

Object oriented languages are built on the object oriented concept. This is the programming paradigm that bundles the data and the methods that access and manage this data into single entity called an Object. This bundling of data and methods allows the object to act as a single entity and have a fluid interface through which it can interact with the outside world. The objects are generally modeled on real world objects.

Fundamental features of Object Oriented languages

  • Object/Class: Class consists of tightly coupled data fields and set of operations that act on the data. The entire set of data and operations represent a user-defined data type. An object is an instance of a class. Thus a class acts as a collection of objects of similar type. Multiple objects may be created out of a class. The objects may share the operations of the class but have their own set of data fields. An object can be defined by its current state (current value of its data members) and its behavior (the methods that can be called on the object).
  • Data Abstraction/Encapsulation: The wrapping of data and functions into a single unit (class) is called encapsulation. Encapsulation protects an object from accidental modifications by an external entity since data fields can be accessed only through predetermined interfaces. Encapsulation is implemented using language constructs like private, public, protected, etc. Abstraction involves representing only the essential features of the object and hiding the background details. Classes provide abstraction by hiding the data attributes and providing functions that provide a controlled view of the object to an external entity.
  • Inheritance: Inheritance is the ability of a class to inherit partly or completely the features of another class. It allows the hierarchical classification of objects.For example, the bird Peacock is a part of the class Flying bird which again is part of the class Bird. Inheritance allows the reusability of code. Pre-existing classes can be reused by extending them and adding new functionality to create sub classes without modifying the original classes. The sub class will then have the combined features of both classes. This allows a programmer to tailor a new class from an existing class without introducing any undesirable side effects in the base classes.
  • Interface: Interface is an abstract type containing no data but only a list of method definitions. A class that has all the methods defined in the interface is said to have implemented the method interface. Interfaces allow classes to define how they will communicate with an external entity. By implementing an interface, a class promises an external entity using the interface that it will provide the functionality specified by the interface.
  • Polymorphism/Dynamic Binding: This is the ability of a variable, method or an object to take more than one forms. This enables an objects of different types to respond to same method or property call but in its own type specific way. For example consider overloading the + operator, so that when called on strings, it concatenates the strings while for numbers it adds them up. Polymorphism also allows objects with different internal structures to share the same external interface. This helps in dynamic binding. Dynamic binding means that the code executed for a given function call is not known until actual runtime. For example, in a dynamically typed language a variable can hold an object irrespective of its data type. Hence a function call associated with a reference (variable) depends on the dynamic type of that reference (variable) i.e. the current object referenced by the variable.

Examples

The below languages implement different degrees of OO features<ref>Voegele, Jason. "Programming Language Comparison." Web.</ref>

  • Ruby, Scala, Smalltalk, Eiffel are said to be purely OO languages. Here even primitives are implemented as OO objects.
  • Java, C++, C#, VB.NET, Python are OO languages but have some degree of procedural elements.
  • Visual Basic, PHP, Perl are basically procedural languages with some OO features.


E.g. C++ program demonstrating the use of a class. The class CRectangle represents a rectangle and has data members x,y which represent the length and breadth (ie: properties) of the rectangle. The functions set_values() and area() allow us to access these data members in a controlled manner. The class object has been instantiated in function main.


#include <iostream>
using namespace std;

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () ;
};

void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

void CRectangle::area() {
  return x*y;
}

int main () {
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}
 

Need for Object Oriented Languages

Block structured languages follow a task-centric approach rather than a data-centric approach. This resulted in certain flaws:

  1. Structured programming follows a hierarchy of structures. However in large programs data is generally in the form of a network of structures. This resulted in a lot of tramp data being passed around.<ref> Object Oriented Comparison. Web. 8 June 2011. </ref>
  2. As the program size increased the amount of data being passed around increased proportionately. Ensuring parameters are correctly passed to the correct subprogram becomes a major issue.
  3. In case of large programs even a small change resulted in massive ripple-effect with changing multiple sub modules to propagate the new data through the program's hierarchy.
  4. Structured program shared a lot of global data.<ref>Global Variables Are Bad</ref> The access to the data was uncontrolled and unpredictable. There was no control over who had access to what.
  5. Structured program suffered from memory leaks.<ref>Using Valgrind to Find Memory Leaks and Invalid Memory Use</ref> This was because anyone could create global structures and there was no responsibility on the creator to deallocate the memory.

The main motivating factor for object-oriented approach is to remove these flaws of block structured languages. OO languages treat data as a critical element and do not allow it to flow freely around the system. The data is tied to the functions with operate on and prevent it from accidental modification from external functions.

Advantages of Object-oriented languages over Block structured languages

  1. Object oriented approach follows a data centered approach. It is possible to map objects in the problem domain to those in the program. This helps the programmer visualize the program in terms of real world objects and which leads to a much better design. Also it allows more details of a model to be captured in implementable form.<ref>Balaguruswamy, E. Object Oriented Programming with C++. New Delhi: Tata Mcgraw-Hill, 2008. Print.</ref>
  2. The principle of data hiding helps in building secure programs. The data fields of an object can be accessed only through the interface defined by its publicly accessible methods. Such controlled access prevents any inadvertent change to object data by external modules.<ref>Weisfeld, Matt. "Hiding Data within Object-Oriented Programming." N.p., 29 July 2004. Web.</ref>
  3. Mapping real world entities into objects help reduce and easily manage software complexity . Also it helps when systems need to be upgraded to larger systems.<ref>"Interface Design by Bill Venners." Web.</ref>
  4. Objects act as black boxes with internal structure and well defined interfaces. Hence adding new functionality becomes easier, since we can easily isolate the objects/classes that need to be modified or extended. The low coupling between objects allows an object to be modified without any effect on the other objects accessing it so long as the interface through which they interact remain untouched.
  5. Most modern object oriented languages provides a load of class libraries and frameworks. These are much easier to use as compared to library functions present in block structured languages. The frameworks help in rapid software development and easier testing and debugging thus leading to increased productivity.<ref>Maner, Walter. RAPID APPLICATION DEVELOPMENT. N.p., 15 Mar. 1997. Web.</ref> <ref>Chillarege, Ram. "Software Testing Best Practices." N.p., 26 Apr. 1999. Web.</ref>
  6. Message passing techniques (ex: interfaces in JAVA) help separate implementation of an object from its externally visible interface. Multiple classes of objects may implement the same interface. In such cases an object can be replaced by another object without affecting external entities dependent on that object so long as the interface is untouched. This results in low coupling.
  7. Object oriented design provides much better memory management. Recent OO languages sport automated garbage handling. Even for languages without garbage collection<ref>Paul, Javin. "Garbage Collection in Java." How Garbage Collection Works In Java. N.p., 11 Apr. 2011. Web. </ref>, memory deallocation of data members can be handled in the destructors of the objects. But in case of block structured languages (like C), it is the programmers responsibility to take care of releasing the dynamically allocated memory. Also the data structures tend to be global in scope and persist beyond the scope of the functions calling them. Hence it becomes difficult to fix responsibility on functions to deallocate them. This leads to memory leaks.

Drawbacks of Object-Oriented Languages

Although object oriented languages sport some very advantageous features as compared to block structured languages, they do have some drawbacks.

  1. Economy of language features: The addition of OO features to a language and the additional syntax needed to implement these features makes it bulky. The complexity of these languages make them daunting to learn and master.<ref name="badEnggProperties">Bad Engineering Properties of Object-Oriented Languages by Luca Cardelli</ref>
  2. Economy of execution: OO style is intrinsically less efficient as compared to block structured style. In procedural languages, type checking occurs at compile time. Hence no tests are needed at runtime for pointer dereferencing for method calls.In OO style each routine is supposed to be a virtual method. This introduces indirections in the form of method tables during for dereferencing.
  3. Also many OO languages include automatic garbage collection (e.g. Java) & hence it might slow down the performance.<ref>Why Java is slow Jelovic, Dejan. "Why Java Is Slow." Why Java Will Always Be Slower Than C++. N.p., 18 Dec. 2009. Web.</ref>. This along with the overhead of creation and destruction of objects degrades performance in resource intensive systems such as embedded systems and real time systems.<ref>Object Oriented Vs Procedural Programming in Embedded System </ref>

Usage of block-structures in Object Oriented languages

OO languages have evolved from block structured languages. Though OO languages use the concepts of class and objects,inheritance,etc they inherently still rely on a blocks to define the structure of the code. The key areas where OO languages assimilate the idea of block structure are as follows:

  • In classes the member functions or methods are implemented using blocks. Each method can be viewed as a block that accepts parameters from an external entity that calls it, performs some processing (that may or may not require the use of data fields of the object) and returns control back with or without a return value.
  • Blocks are also useful in defining control structures like loops, conditional blocks(e.g. if...else), etc.

E.g. Java program demonstrating the usage of a while loop .The while loop encloses a group of statements within curly braces signifying a block that may be iterated upon till while condition holds true.

package hashmap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class ExampleHashMap
{
	public static void main(String args[])
	{
		LinkedHashMap h = new LinkedHashMap();                          //Creates a LinkedHashMap. Linked HashMaps defines the 
		h.put("A",100);                                                 //iteration ordering, which is normally the 
		h.put("B",200);                                                 //order in which keys were inserted into the map.
		h.put("C",300);
		h.put("D",400);
		h.put("E",500);
		
		Set s = h.entrySet();                                           //Returns a set containing key value pairs
		Iterator i = s.iterator();                                      
		
		while(i.hasNext())
		{
			Map.Entry me = (Map.Entry)i.next();                     //Each element in the set has to be casted to Map.Entry 
			System.out.println(me.getKey()+" : "+me.getValue());    //to access the key/value 
		}
       }
}
		

  • OO languages generally provide inbuilt language support for exception handling. Most OO languages implement exception handling in terms of blocks

E.g.: Try...catch blocks in Java Here the catch and finally blocks are used to delimit a group of statements that can be called to handle exceptions at runtime. Also, we can see usage of conditional statements if...else in this case.

try{
    System.out.println("Inside try block of testMethod!");
    int p=1000, q=0, i=0;
    if(p>q){                                               //We can clearly see here that a Divide by Zero exception will occur.
         i=p/q;
    }
    else if(q>p){
         i=q/p;
    }
    else{                                                 //In this case p equals q
         i=p/q;
    }
}
catch(Exception e){
    System.out.println("Inside catch block of testMethod!");
    System.out.println(“Caution: your trying to Divide a number by Zero...”);
}
finally{                                                  
    System.out.println("Inside finally block of testMethod!");
    System.out.println(“This block executes everytime an exception is caught...”);
}

  • Certain OO languages like JAVA allow creation of anonymous classes which are basically blocks which don’t have a name but can be instantiated without actually making a separate class.

E.g. Here ActionListener is an interface which has been implemented as anonymous block in the below JAVA example.

import java.awt.Button;

class Submit()
{
       public Submit()
       {
              Button button1 = new Button("Submit");
                
              button1.addActionListener(new ActionListener(){
                     public void actionPerformed (ActionEvent event){
                            System.out.println("actionPerfomed is implemented as anonymous class here & is added as a listener to button1");
                     }  
              });
       }
}


E.g. Given below is a method which yields control to a block in Ruby & also passes parameter to it at the same time.

def block_demo
    yield("Smith")
end

block_demo { |name| puts " Hello #{name} " }

The Output will be
 Hello Smith 

Conclusion

Block structured languages had their uses in earlier days when code size was small and the main focus was on efficiency(in terms of space & memory) of programs. However, these programs could not scale in size as maintenance and code complexity became an overhead.

Object Oriented concepts like encapsulation, inheritance(which helps in code re-usability), interfaces & polymorphism allowed better visualization of the software problem and its design to handle this complexity. Moreover, class libraries and frameworks developed in these languages helped abstract the code complexity and allowed rapid program development. This led to a gradual transition from block oriented to object oriented languages for application development.


References

<references/>

External Links

  1. The Go Programming Language by Google for multicore and networked machines
  2. Object Oriented Concepts (Java Tutorials)
  3. Block Structure and Object Oriented Languages by Ole Lehrmann Madsen
  4. A Tutorial on Algol 68, by Andrew S. Tanenbaum, in Computing Surveys, Vol. 8, No. 2, June 1976, with Corrigenda (Vol. 9, No. 3, September 1977)
  5. Official Ruby Webpage
  6. Pascal programming tutorials
  7. Dynamic Languages Strike Back
  8. Functional vs Procedural languages
  9. Scala Software
  10. Smalltalk
  11. Eiffel Software
  12. C++ Programming Language
  13. Java Software
  14. The C Sharp Language
  15. Visual Basic
  16. Python Programming Language
  17. PHP: Hypertext Preprocessor
  18. Perl Programming Language