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

From Expertiza_Wiki
Jump to navigation Jump to search
(Refined introduction)
 
(63 intermediate revisions by 2 users not shown)
Line 1: Line 1:
"'''Block and Object-Oriented Programming Languages'''" by '''Andrew Davis''' and '''Srikanth Ramachandran'''
"'''Block vs Object-Oriented Programming Languages'''"


In computer science, computer programming languages exhibit variance in syntax and structure in order to effectively solve problems. Two of these variances can be seen between '''block structure''' and '''object-oriented structure'''. A programming language with block structure allows the programmer to group lines of code so that they may be accessed as a single entity. Meanwhile, object-oriented structure allows the programmer to associate data with its actions in a hierarchical manner. Object-oriented structure has many advantages which generally make it more effective and durable than block-structured languages, but object-oriented languages also benefit from ideas present in block structure programming.
In computer science, computer programming languages exhibit variance in syntax and structure in order to effectively solve problems. Two of these variances can be seen between '''block structure''' and '''object-oriented structure'''. A programming language with block structure allows the programmer to group lines of code for convenient use throughout the rest of the program. Object-oriented structure meanwhile goes further to allow the programmer to associate data with its actions in a hierarchical manner. Object-oriented structure has many advantages which generally make it more effective and durable than block-structured languages, even though object-oriented structure benefits from many of the features present in simple block structure.


==Block structure==
==Block structure==
===Definition===
===Definition===
Block-structured programming languages are task-centric, high-level languages. Operations on data sets are emphasized rather than the data itself in an attempt to logically organize program operation. The design and implementation involves breaking down the problem into discrete blocks, or units, which can be nested to any depth or not at all. Each block generally consists of a set of delimiters such as braces, indentation, and the like that separate them from other blocks. Each of these blocks contains a set of (optional) declarations and logic to solve a particular problem. Declarations inside of nested blocks introduces the concept of variable scope, which frees the programmer from having to worry about name collisions and other variable maintenance tasks.<ref>[http://en.wikipedia.org/wiki/Block_(programming) Block (programming)] at Wikipedia</ref>
Block-structured programming languages are task-centric, high-level languages. Operations on data sets are emphasized in an attempt to logically organize program operation. The design and implementation involves breaking down the problem into discrete blocks or units which can be nested to any depth or not at all. Each block generally consists of a set of delimiters such as braces or keywords that separate them from other blocks. Each of these blocks contains a set of (optional) declarations and logic to solve a particular problem. Declarations inside of nested blocks introduces the concept of variable scope, which frees the programmer from having to worry about name collisions and other variable maintenance tasks.<ref>[http://en.wikipedia.org/wiki/Block_(programming) Block (programming)] at Wikipedia</ref> A [[CSC/ECE_517_Fall_2011/ch1_1e_sa#Code_example|code example]] of a block structured program is provided later in the article.


Overall, block-structured languages can be summarized as having the following features:
Overall, block-structured languages can be summarized as having the following features:
* Modularization
* Modular - Lines of code/functionality are grouped together
* Scope
* Scoped - Variables are limited to the group of code they are declared in
* Top down approach
* [http://en.wikipedia.org/wiki/Top-down_and_bottom-up_design Top down] - Modules are created as necessary to meet the program's requirements
* Simplicity
* Simple - It is generally simpler to "cobble together" modules of code that accomplish a simple, well-defined task.
* Dynamic lifetime of variables


===History===
===History===
Block-structured languages were first conceived in the 1950s with the advent of ALGOL, one of the first imperative programming languages. An evolution of block structuring was created as the "GOTO" logic of programs became more and more difficult to understand and maintain. In 1968, famed computer scientist Edsger Dijkstra wrote a letter and follow-up article on the ideas and motivation behind "structured programming," where the program exhibits “separation of concerns," single point of entry but multiple points of exit, and ideas of data structures. It was Dijkstra’s and others’ which helped propel this basic idea of block structure programming into the mainstream.<ref>[http://en.wikipedia.org/wiki/Structured_programming Structured programming] at Wikipedia</ref>
Block-structured languages were first conceived in the 1950s with the advent of [http://en.wikipedia.org/wiki/ALGOL ALGOL], one of the first [http://en.wikipedia.org/wiki/Imperative_programming imperative programming languages]. An evolution of block structuring was created as the "GOTO" logic of programs became more and more difficult to understand and maintain. In 1968, famed computer scientist [http://en.wikipedia.org/wiki/Edsger_W._Dijkstra Edsger Dijkstra] wrote [http://dx.doi.org/10.1145%2F362929.362947 a letter] and [http://dx.doi.org/10.1145%2F355604.361591 follow-up article] on the ideas and motivation behind "[http://en.wikipedia.org/wiki/Structured_programming structured programming]," where the program exhibits “[http://en.wikipedia.org/wiki/Separation_of_concerns separation of concerns]," single point of entry but multiple points of exit, and ideas of data structures. It was Dijkstra’s and others’ which helped propel this basic idea of block structure programming into the mainstream.<ref>[http://en.wikipedia.org/wiki/Structured_programming Structured programming] at Wikipedia</ref>


===Programming languages===
===Programming languages===
Block-structured programming languages dominate the general purpose, imperative programming language arena. Indeed most programming languages in modern use enjoy some of the benefits of block structure with grouping of code and scope of variables. Indeed, ignoring their object-oriented aspects, all of C, C++, C#, Java, PHP and Visual Basic – for example – contain elements of block structure.
Block-structured programming languages dominate the general purpose, imperative programming language arena. Indeed most programming languages in modern use enjoy some of the benefits of block structure with grouping of code and scope of variables. Indeed, ignoring their object-oriented aspects, all of [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/PHP PHP] and [http://en.wikipedia.org/wiki/Visual_Basic Visual Basic] – for example – contain elements of block structure.
 
===Code example===
The code snippet given below is an ALGOL example that calculates the [http://en.wikipedia.org/wiki/Arithmetic_mean arithmetic mean] by first asking how many samples to take and then asking for the values of each sample. It exhibits block structure because it is modularizing sections of code with the <b>begin</b> and <b>end</b> keywords, implying changes of variable scope between the beginning of the program and the remainder. For example, the <b>N</b> integer has scope throughout the whole body, but the <b>Data</b> array, <b>sum</b>, <b>i</b>, and <b>avg</b> variables only have scope after reading the number of samples to take, and the <b>val</b> variable has local scope only inside the loop for when values are requested.
====Code listing====
This above-mentioned ALGOL code sample is from the &quot;Compute The Mean Example Program
&quot; from the CIS400 course at the University of Michigan.<ref>http://groups.engin.umd.umich.edu/CIS/course.des/cis400/algol/average.html &quot;Compute The Mean Example Program
&quot; from the CIS400 course at the University of Michigan</ref> Per the notes available at the source web page, this program has not been tested.
<pre>begin
  integer N;
  Read Int(N);
 
  begin
    real array Data[1:N];
    real sum, avg;
    integer i;
    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</pre>
 
====Program operation====
=====User input=====
<pre>5
1
2
3
4
5</pre>
=====Output=====
<pre>3</pre>


==Object-oriented structure==
==Object-oriented structure==
===Definition===
===Definition===
Object-oriented languages have an important overall goal and foster major design principles. A full discussion of these principles is outside the scope of this article and full treatment of them is deferred to their linked articles.
====Description====
====Description====
Object-oriented structured languages are data-centric, high-level languages. Compared to block-structure languages, logical organization of data and the methods associated with them are emphasized. It is a way of grouping data with executable code (called "objects") that works with that data which exhibits attributes in a hierarchical manner (called "classes" in popular languages). Toward this end and depending on the language, objects can be interrelated and defined so that their relationships can produce code that is well-organized, easy to read, and reusable.<ref name="oopref">[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] at Wikipedia</ref>
Object-oriented structured languages are data-centric, high-level languages. This is in contrast to block structure languages, which are task-centric. Compared to block-structure languages, logical organization of <i>data</i> and the methods associated with them are emphasized. It is a way of grouping data with executable code. These groups are called "[http://en.wikipedia.org/wiki/Object_(computer_science) objects]." Objects utilize their data and interact with other objects such that a hierarchy is established (called "[http://en.wikipedia.org/wiki/Class_(computer_science) classes]" in popular languages). Toward this end and depending on the language, objects can be interrelated and defined so that their relationships can produce code that is well-organized, easy to read, and reusable.<ref name="oopref">[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] at Wikipedia</ref>


====Principles====
====Principles====
=====Encapsulation=====
=====Encapsulation=====
Also referred to as "data hiding," encapsulation shields the programmer from the implementation details of an object. These implementation details would include private variables, special libraries, and data structures that the programmer does not need to know in order to utilize the functionality offered by the object.<ref>[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation (object-oriented programming)] at Wikipedia</ref>
Also referred to as "data hiding," [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation] shields the programmer from the implementation details of an object. These implementation details would include [http://en.wikipedia.org/wiki/Local_variable private variables], special [http://en.wikipedia.org/wiki/Library_(computing) libraries], and [http://en.wikipedia.org/wiki/Data_structure data structures] that the programmer does not need to know in order to utilize the functionality offered by the object.<ref>[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation (object-oriented programming)] at Wikipedia</ref>


=====Inheritance=====
=====Inheritance=====
Inheritance introduces the idea of objects sharing functionality in data or methods that are common. Subclasses can inherit data structures, functions, and attributes of their superclasses in order to create an object hierarchy that is effective in organizing data and methods in a logical manner.<ref>[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance (computer science)] at Wikipedia</ref>
[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance] introduces the idea of objects sharing functionality in data or methods that are common. [http://en.wikipedia.org/wiki/Subclass_(computer_science)#Subclasses_and_superclasses Subclasses] can inherit data structures, functions, and attributes of their [http://en.wikipedia.org/wiki/Subclass_(computer_science)#Subclasses_and_superclasses superclasses] in order to create an object or [http://en.wikipedia.org/wiki/Class_hierarchy class hierarchy] that is effective in organizing data and methods in a logical manner.<ref>[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance (computer science)] at Wikipedia</ref>


=====Polymorphism=====
=====Polymorphism=====
Polymorphism describes the idea of interfaces, where one data type can be defined that allows other dissimilar types to implement a common set of methods and fields. This allows a high level of abstraction that allows programmers to write easily maintainable code.<ref>[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism in object-oriented programming] at Wikipedia</ref>
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] describes the idea of interfaces, where one data type can be defined that allows other dissimilar types to implement a common set of [http://en.wikipedia.org/wiki/Method_(computer_programming) methods] and [http://en.wikipedia.org/wiki/Field_(computer_science) fields]. This allows a high level of [http://en.wikipedia.org/wiki/Abstraction_(computer_science) abstraction] that allows programmers to write easily maintainable code.<ref>[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism in object-oriented programming] at Wikipedia</ref>


===History and transition===
===History and transition===
Early forms of OOP were created in the early 1960s with the creation of LISP and an early form of ALGOL, with Simula 67 signaling the actual beginning of the OOP “revolution." The development of OOP languages progressed through other languages like Smalltalk and the archetypal C++ to arrive at the OOP languages we have today.<ref name="oopref"/>
Early forms of object oriented programming languages were created in the early 1960s with the creation of [http://en.wikipedia.org/wiki/Lisp_(programming_language) LISP] and an early form of ALGOL, with [http://en.wikipedia.org/wiki/Simula Simula 67] signaling the actual beginning of the object-oriented "revolution." The development of object-oriented languages progressed through other languages like [http://en.wikipedia.org/wiki/Simula Smalltalk] and the archetypal C++ to arrive at many of the object oriented languages we have today.<ref name="oopref"/> As processing capability has matured, so too have the capabilities of programming languages. More and more though, [http://en.wikipedia.org/wiki/Dynamic_programming_language dynamic programming languages] like [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] are being treated as "true" object-oriented languages because of their rapid prototyping ability and strong [http://en.wikipedia.org/wiki/Object-oriented_analysis_and_design object model].


===Programming languages===
===Programming languages===
A complete list of object oriented languages is outside the scope of this document, but some major examples are Boo, C++, C#, COBOL, F#, Fortran 2003, Java, MATLAB, Objective-C, PHP5, Python, Ruby, and Visual Basic.<ref>[http://en.wikipedia.org/wiki/List_of_object-oriented_programming_languages List of object-oriented programming languages] at Wikipedia</ref>
A complete list of object oriented languages is outside the scope of this document, but some major examples are [http://en.wikipedia.org/wiki/Boo_(programming_language) Boo], C++, C#, [http://en.wikipedia.org/wiki/COBOL COBOL 2002], [http://en.wikipedia.org/wiki/F_Sharp_(programming_language) F#], [http://en.wikipedia.org/wiki/Fortran Fortran 2003], Java, [http://en.wikipedia.org/wiki/Matlab MATLAB], [http://en.wikipedia.org/wiki/Objective_c Objective-C], [http://en.wikipedia.org/wiki/PHP PHP 5], [http://en.wikipedia.org/wiki/Python_(programming_language) Python], Ruby, and Visual Basic.<ref>[http://en.wikipedia.org/wiki/List_of_object-oriented_programming_languages List of object-oriented programming languages] at Wikipedia</ref>
 
====Code example====
The code snippet given below is a simple example from a purely object-oriented language called Ruby. It exhibits object oriented structure in that it defines an object called <b>AdderGen</b>. The object is initialized with a number <b>n</b> to which a provided value <b>a</b> can be added. It also provides a method to square a provided number <b>a</b>.  This is a simple example of object-oriented structure because it associates separate pieces of data (<b>instanceOne</b> and <b>instanceTwo</b>, initialized with 5 and 3, respectively) with methods that act against it (the <b>addVal</b> method).
=====Code listing=====
<pre>class AdderGen
  def initialize(n)
    @classVar1 = lambda {|a| n+a}
    @classVar2 = lambda {|a| a*a}
  end
  def addVal(a)
    return @classVar1.call(a)
  end
  def squareVal(a)
    return @classVar2.call(a)
  end
end
 
instanceOne = AdderGen.new(5)
instanceTwo = AdderGen.new(3)
puts instanceOne.addVal(6)
puts instanceTwo.addVal(8)</pre>
=====Code output=====
<pre>11
=> nil
11
=> nil</pre>


==Structure comparison==
==Structure comparison==
===Advantages and disadvantages===
===Advantages and disadvantages===
==== Block Structured Languages ====
==== Block-structured languages ====
===== Advantages:=====
=====Advantages=====
* Simplicity.
* Simplicity
* Coding and turnover time is quite less.
* Reduced coding and turnover time
* Dynamic lifetime of variables provide efficient usage of memory with allocation and deletion happening at the entrance and exit of each block.
* Dynamic lifetime of variables ([http://en.wikipedia.org/wiki/Scope_(computer_science) Scope]) provide efficient usage of memory since allocation and deletion occur at the entrance and exit of each block
 
=====Disadvantages=====
* Commercial projects are difficult to manage due to very large [http://en.wikipedia.org/wiki/Codebase codebase] sizes
* Reduced code [http://en.wikipedia.org/wiki/Reusability reusability]
* [http://en.wikipedia.org/wiki/Computer_security Security] concerns, especially in the realm of [http://en.wikipedia.org/wiki/Array#In_computer_science arrays] and accessing [http://en.wikipedia.org/wiki/Value_(computer_science) elements] that are [http://en.wikipedia.org/wiki/Privilege_(computing) out of bounds]


===== Disadvantages:=====
====Object-Oriented languages====
* Commercial projects are very difficult to manage due to very large code base sizes.
=====Advantages=====
* There is very less code reuse.
* The software objects model real world objects so program composition is well defined and structured
* When arrays are passed as parameters they are usually unbounded,hence it was easy to access an element out of bounds.
* Each object's definition and internal implementation is decoupled from other objects, making the system design inherently modular ([http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation])
* Adding new features becomes easier because of inheritance, allowing the new class to contain the new feature in addition to all old features from the inherited class
* [http://en.wikipedia.org/wiki/Debugging Debugging] is easier since each object's internal mechanisms are independent of each other, which helps in isolating errors and fixing them
* Enhanced code reusability


==== Object Oriented Languages ====
=====Disadvantages=====
===== Advantages:=====
* The complexity of object-oriented design becomes prohibitive when working on small projects
* The software objects model the real world objects. Hence the program composition is well defined and structured.
* Object-oriented programming paradigm is preferable for dynamic environments rather than simple environments
* Since each object's definition and internal working is decoupled from other objects in the system the design becomes inherently modular.
* Reduced time efficiency compared to block-structured languages
* Adding new features becomes very easy because of the inheritance feature. The new class can contain the new feature in addition to all old  features from the inherited class.
* Debugging is easier since each objects internal working is independent of each other. This helps in isolating errors easily and fixing them.
* Code re usability.


===== Disadvantages: =====
* The complexity of O-O design becomes prohibitive when working on small projects.
* Object-oriented programming paradigm is preferable for dynamic environments rather than simple non complex environments.
* The time efficiency is much less compared to block structured languages.
===Summary of important differences===
===Summary of important differences===
{| class="wikitable" style="font-size: 100%; text-align: center; width: auto;"
{| class="wikitable" style="font-size: 100%; text-align: center; width: auto;"
Line 74: Line 141:
|-
|-
| '''Problem approach'''
| '''Problem approach'''
| Top down approach is followed
| Top-down approach is followed
| Bottom-up approach is followed
| [http://en.wikipedia.org/wiki/Top-down_and_bottom-up_design Bottom-up] approach is followed
|-
|-
| '''Problem focus'''
| '''Problem focus'''
| Focus is on the Algorithm to solve the problem.
| Focus is on the [http://en.wikipedia.org/wiki/Algorithm#Computer_algorithms algorithm] to solve the problem
| Focus is on getting the object design right
| Focus is on getting the object design right
|-
|-
Line 98: Line 165:
|}
|}


===Effectiveness and durability of Object oriented languages over block structured languages ===
===Effectiveness and durability===


Although block structured languages were simpler and faster for smaller projects, when it comes to large commercial undertaking the manpower and tools required to maintain the code base is very prohibitive. It was very difficult to fix issues ,add new features and at the same time to make sure that the integrity of the code base is intact. Many projects were perpetually stagnant at 90% completion with issues coming up at the nth hour. All these problems led to the hastening of the move to object-oriented languages which showed it had the solutions to all the problems that block structured languages could not solve. The following four points are the most important reasons why object-oriented languages were more effective and durable that block structured languages :
Although block structured languages were simpler and faster for smaller projects, when it comes to large commercial undertaking the manpower and tools required to maintain the code base is very prohibitive. It was very difficult to fix issues, add new features, and at the same time to make sure that the integrity of the code base is intact. Many projects were perpetually stagnant at 90%<ref>Fayad, Mohamed, and Mauri Laitinen. <i>Transition to Object-oriented Software Development</i>. New York: Wiley, 1998. Print.</ref> completion with issues coming up at the eleventh hour. All these problems led to the hastening of the move to object-oriented languages which showed it had the solutions to all the problems that block structured languages could not solve. The following four points are the most important reasons why object-oriented languages were more effective and durable that block structured languages:
* Maintenance - In block structured languages especially in large projects system maintenance became a real handful. Object oriented languages could counter this by providing clear demarcation between the objects and making it easier to work on individual aspects of the system without disturbing the other components.
* Maintenance - In block structured languages, especially in large projects, system maintenance became a challenge. Object oriented languages could counter this by providing clear demarcation between the objects and making it easier to work on individual aspects of the system without disturbing the other components.
* Data hiding - In block structured language system the data usually has global scope. Hence it is very difficult to monitor or supervise data access. This was solved by o-o languages by providing data encapsulation. The data and the corresponding attributes are put into a nice little package that was much easier to control and monitor.
* [http://en.wikipedia.org/wiki/Information_hiding Data hiding] - In block structured language system the data usually has global scope. Hence it is very difficult to monitor or supervise data access. This was solved by object-oriented languages by providing data encapsulation. The data and the corresponding attributes are put into a nice little package that was much easier to control and monitor.
* Code re-use - Object oriented languages are proponents of code reuse. Hence the code size could be reduced sufficiently enough when it comes to large projects to warrant a shift from block structured to object oriented languages.
* Code reuse - Object oriented languages are proponents of code reuse. Hence the code size could be reduced sufficiently enough when it comes to large projects to warrant a shift from block structured to object oriented languages.
* Feature Additions - Object oriented languages provide a very cost effective and safe way to add new features to the existing system without causing the whole system to collapse. This feature is very important for large scale software vendors who provide various customizations.
* Feature additions - Object oriented languages provide a very cost effective and safe way to add new features to the existing system without causing the whole system to collapse. This feature is very important for large scale software vendors who provide various customizations.


===Applicability between paradigms===
===Applicability between paradigms===
Object-oriented languages have solved many problems that block structured languages introduced. But all is not lost with block structured languages. They boast some very important features that are needed in any programming language. The simplicity and readability of code in block structured languages are enviable features indeed. Because of this very simplicity we find that block structured languages are very efficient in terms of speed and performance. Such a language would also provide the flexibility in moving legacy block structured systems to the object oriented paradigm seamlessly. A language that can capture both sides of the argument would be a formidable entry into the growing list of programming languages. This explains why we see C++ emerging as one of the most popular object oriented languages. It has both the block structured features of C and the object-oriented concepts built into it, thereby making it a very versatile and efficient programming language.
==C/C++ Case Example==
Below are code examples highlighting key differences between a block structured program and an object oriented program. The execution of each program results in identical output. C and C++ were chosen as the languages for example so a more direct comparison could be made, despite the fact that C++ is not a "true" object oriented language<ref>http://www.jvoegele.com/software/langcomp.html <i>Programming Language Comparison</i> by Jason Voegele</ref>.
===Block structure===
The below example illustrates a typical block structure program. The listing begins with the requisite headers to include functionality, followed by declarative statements that define some blocks ("functions prototypes") later in the program. Program execution begins in the <i>main()</i> method, where the various commands to print to the screen are executed by calling each function's respective message. The functions are focusing on the functionality, and no data association is occurring at all.
<pre>// C standard header files
#include <stdio.h>
#include <stdlib.h>
// Define the messages of each persona
#define KING_MESSAGE  "Read my lips: No new taxes"
#define JESTER_MESSAGE "My wife and I were happy for 20 years. Then we met."
#define PEON_MESSAGE  "The king himself created his own worst enemy, just as tyrants everywhere do!"
// Define the function prototypes for delivering the different messages
char *getKingMessage();
char *getJesterMessage();
char *getPeonMessage();
// Main program entry point
int main()
{
// Go through and make each function call for...
// The King
printf("And now a message from the king: %s\n", getKingMessage());
printf("The King has spoken!\n\n");
// The Court Jester
printf("And now a message from the court jester: %s\n", getJesterMessage());
printf("Wocka wocka wocka!\n\n");
// A Peon
printf("And now a message from a peon: %s\n", getPeonMessage());
printf("... but don't mind me!\n\n");
// Wait for user input before exiting
system("pause");
return 0;
}
// Returns a string containing the text to be spoken by the king
char *getKingMessage()
{
return KING_MESSAGE;
}
// Returns a string containing the text to be spoken by the court jester
char *getJesterMessage()
{
return JESTER_MESSAGE;
}
// Returns a string containing the text to be spoken by all peons
char *getPeonMessage()
{
return PEON_MESSAGE;
}</pre>
===Object oriented structure===
The below object oriented structure source code yields a program that has the exact same output as the block structure program above. The listing begins with the necessary headers to include functionality in the program. This is followed by a class (object) definition for a <i>Person</i>, and how the <i>King</i>, <i>Jester</i>, and <i>Peon</i> all inherit the capabilities and attributes of a <i>Person</i> (like having a <b>label</b> (title of nobility or lack thereof) and being able to <b>DeliverMessage</b>s). Due to inheritance, each of these people is permanently defined by their label -- it will not change due to the nature of a <i>Monarchy</i>. Also, the person's data (label/message) is firmly associated with their functions (DeliverMessage). Carrying on, the program's main function begins by initializing instance of each King, Jester, and Peon, instilling in each one their own unique message and finally having them deliver it (to the screen).
The object oriented structure has a lot of [http://en.wikipedia.org/wiki/Boilerplate_code boilerplate code] necessary to describe this structure, but once it comes to initialization and execution, the program logic and organization simplifies greatly compared to block structure.
<pre>// C++ standard headers
#include <cstdio>
#include <cstdlib>
// Define what each persona should say
#define KING_MESSAGE  "Read my lips: No new taxes"
#define JESTER_MESSAGE "My wife and I were happy for 20 years. Then we met."
#define PEON_MESSAGE  "The king himself created his own worst enemy, just as tyrants everywhere do!"
// Keep all classes clearly separated from other sections of code
namespace Monarchy
{
// Define a basic class where a person has a label and something they want to say
class Person
{
private:
char *szMessage;
char *szLabel;
public:
// Allow a person to deliver their message
void DeliverMessage()
{
printf("A now a message from %s: %s\n", this->szLabel, this->szMessage);
}
// A person needs to be initialized with a label and a message
Person(char*label, char *msg)
{
this->szLabel = label;
this->szMessage = msg;
}
};
// The King is a person (and thus inherits from it)
class King : public Person
{
public:
// The king has the same label, but his message might change according to the political winds
King(char *msg) : Person("the king", msg)
{
}
// Here, the function is being overridden...
void DeliverMessage()
{
// .. but the base class's DeliverMessage is still being called, in addition to the tag line
Person::DeliverMessage();
printf("The King has spoken!\n\n");
}
};
// A peon is a person (and thus inherits from it)
class Peon : public Person
{
public:
// A peon has the same label but his message might change according to his or her attitude toward the king
Peon(char *msg) : Person("a peon", msg)
{
}
// Like above, deliver the message, but always provide a common tag line
void DeliverMessage()
{
Person::DeliverMessage();
printf("... but don't mind me!\n\n");
}
};
// A jester is a person (and thus inherits from it)
class Jester : public Person
{
public:
// A peon has the same label but his message might change if the king is sick of his jokes
Jester(char *msg) : Person("the court jester", msg)
{
}
// Might as well call him Fozzie ;)
void DeliverMessage()
{
Person::DeliverMessage();
printf("Wocka wocka wocka!\n\n");
}
};
}
// Main program entry point
int main()
{
// Initialize some monarchy objects
Monarchy::King TheKing(KING_MESSAGE);
Monarchy::Jester Borat(JESTER_MESSAGE);
Monarchy::Peon Bruno(PEON_MESSAGE);
// Let them deliver their messages
TheKing.DeliverMessage();
Borat.DeliverMessage();
Bruno.DeliverMessage();
// Wait for user input
system("pause");
return 0;
}</pre>
===Output (both structures)===
<pre>And now a message from the king: Read my lips: No new taxes
The King has spoken!
And now a message from the court jester: My wife and I were happy for 20 years. Then we met.
Wocka wocka wocka!
And now a message from a peon: The king himself created his own worst enemy, just as tyrants everywhere do!
... but don't mind me!
Press any key to continue . . .</pre>


==See also==
==See also==
Line 128: Line 375:
* [http://www.developer.com/java/other/article.php/3493761/The-Evolution-of-Object-Oriented-Languages.htm The Evolution of Object-Oriented Languages]
* [http://www.developer.com/java/other/article.php/3493761/The-Evolution-of-Object-Oriented-Languages.htm The Evolution of Object-Oriented Languages]
* [http://www.xp2003.org/the-history-of-oop.htm The History of OOP]
* [http://www.xp2003.org/the-history-of-oop.htm The History of OOP]
* [http://www.brighthub.com/internet/web-development/articles/82024.aspx Structured vs. Object-Oriented Programming: A Comparison]

Latest revision as of 01:25, 21 September 2011

"Block vs Object-Oriented Programming Languages"

In computer science, computer programming languages exhibit variance in syntax and structure in order to effectively solve problems. Two of these variances can be seen between block structure and object-oriented structure. A programming language with block structure allows the programmer to group lines of code for convenient use throughout the rest of the program. Object-oriented structure meanwhile goes further to allow the programmer to associate data with its actions in a hierarchical manner. Object-oriented structure has many advantages which generally make it more effective and durable than block-structured languages, even though object-oriented structure benefits from many of the features present in simple block structure.

Block structure

Definition

Block-structured programming languages are task-centric, high-level languages. Operations on data sets are emphasized in an attempt to logically organize program operation. The design and implementation involves breaking down the problem into discrete blocks or units which can be nested to any depth or not at all. Each block generally consists of a set of delimiters such as braces or keywords that separate them from other blocks. Each of these blocks contains a set of (optional) declarations and logic to solve a particular problem. Declarations inside of nested blocks introduces the concept of variable scope, which frees the programmer from having to worry about name collisions and other variable maintenance tasks.<ref>Block (programming) at Wikipedia</ref> A code example of a block structured program is provided later in the article.

Overall, block-structured languages can be summarized as having the following features:

  • Modular - Lines of code/functionality are grouped together
  • Scoped - Variables are limited to the group of code they are declared in
  • Top down - Modules are created as necessary to meet the program's requirements
  • Simple - It is generally simpler to "cobble together" modules of code that accomplish a simple, well-defined task.

History

Block-structured languages were first conceived in the 1950s with the advent of ALGOL, one of the first imperative programming languages. An evolution of block structuring was created as the "GOTO" logic of programs became more and more difficult to understand and maintain. In 1968, famed computer scientist Edsger Dijkstra wrote a letter and follow-up article on the ideas and motivation behind "structured programming," where the program exhibits “separation of concerns," single point of entry but multiple points of exit, and ideas of data structures. It was Dijkstra’s and others’ which helped propel this basic idea of block structure programming into the mainstream.<ref>Structured programming at Wikipedia</ref>

Programming languages

Block-structured programming languages dominate the general purpose, imperative programming language arena. Indeed most programming languages in modern use enjoy some of the benefits of block structure with grouping of code and scope of variables. Indeed, ignoring their object-oriented aspects, all of C, C++, C#, Java, PHP and Visual Basic – for example – contain elements of block structure.

Code example

The code snippet given below is an ALGOL example that calculates the arithmetic mean by first asking how many samples to take and then asking for the values of each sample. It exhibits block structure because it is modularizing sections of code with the begin and end keywords, implying changes of variable scope between the beginning of the program and the remainder. For example, the N integer has scope throughout the whole body, but the Data array, sum, i, and avg variables only have scope after reading the number of samples to take, and the val variable has local scope only inside the loop for when values are requested.

Code listing

This above-mentioned ALGOL code sample is from the "Compute The Mean Example Program " from the CIS400 course at the University of Michigan.<ref>http://groups.engin.umd.umich.edu/CIS/course.des/cis400/algol/average.html "Compute The Mean Example Program " from the CIS400 course at the University of Michigan</ref> Per the notes available at the source web page, this program has not been tested.

begin
  integer N;
  Read Int(N);

  begin
    real array Data[1:N];
    real sum, avg;
    integer i;
    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

Program operation

User input
5
1
2
3
4
5
Output
3

Object-oriented structure

Definition

Object-oriented languages have an important overall goal and foster major design principles. A full discussion of these principles is outside the scope of this article and full treatment of them is deferred to their linked articles.

Description

Object-oriented structured languages are data-centric, high-level languages. This is in contrast to block structure languages, which are task-centric. Compared to block-structure languages, logical organization of data and the methods associated with them are emphasized. It is a way of grouping data with executable code. These groups are called "objects." Objects utilize their data and interact with other objects such that a hierarchy is established (called "classes" in popular languages). Toward this end and depending on the language, objects can be interrelated and defined so that their relationships can produce code that is well-organized, easy to read, and reusable.<ref name="oopref">Object-oriented programming at Wikipedia</ref>

Principles

Encapsulation

Also referred to as "data hiding," encapsulation shields the programmer from the implementation details of an object. These implementation details would include private variables, special libraries, and data structures that the programmer does not need to know in order to utilize the functionality offered by the object.<ref>Encapsulation (object-oriented programming) at Wikipedia</ref>

Inheritance

Inheritance introduces the idea of objects sharing functionality in data or methods that are common. Subclasses can inherit data structures, functions, and attributes of their superclasses in order to create an object or class hierarchy that is effective in organizing data and methods in a logical manner.<ref>Inheritance (computer science) at Wikipedia</ref>

Polymorphism

Polymorphism describes the idea of interfaces, where one data type can be defined that allows other dissimilar types to implement a common set of methods and fields. This allows a high level of abstraction that allows programmers to write easily maintainable code.<ref>Polymorphism in object-oriented programming at Wikipedia</ref>

History and transition

Early forms of object oriented programming languages were created in the early 1960s with the creation of LISP and an early form of ALGOL, with Simula 67 signaling the actual beginning of the object-oriented "revolution." The development of object-oriented languages progressed through other languages like Smalltalk and the archetypal C++ to arrive at many of the object oriented languages we have today.<ref name="oopref"/> As processing capability has matured, so too have the capabilities of programming languages. More and more though, dynamic programming languages like Ruby are being treated as "true" object-oriented languages because of their rapid prototyping ability and strong object model.

Programming languages

A complete list of object oriented languages is outside the scope of this document, but some major examples are Boo, C++, C#, COBOL 2002, F#, Fortran 2003, Java, MATLAB, Objective-C, PHP 5, Python, Ruby, and Visual Basic.<ref>List of object-oriented programming languages at Wikipedia</ref>

Code example

The code snippet given below is a simple example from a purely object-oriented language called Ruby. It exhibits object oriented structure in that it defines an object called AdderGen. The object is initialized with a number n to which a provided value a can be added. It also provides a method to square a provided number a. This is a simple example of object-oriented structure because it associates separate pieces of data (instanceOne and instanceTwo, initialized with 5 and 3, respectively) with methods that act against it (the addVal method).

Code listing
class AdderGen
  def initialize(n)
    @classVar1 = lambda {|a| n+a}
    @classVar2 = lambda {|a| a*a}
  end
  def addVal(a)
    return @classVar1.call(a)
  end
  def squareVal(a)
    return @classVar2.call(a)
  end
end

instanceOne = AdderGen.new(5)
instanceTwo = AdderGen.new(3)
puts instanceOne.addVal(6)
puts instanceTwo.addVal(8)
Code output
11
=> nil
11
=> nil

Structure comparison

Advantages and disadvantages

Block-structured languages

Advantages
  • Simplicity
  • Reduced coding and turnover time
  • Dynamic lifetime of variables (Scope) provide efficient usage of memory since allocation and deletion occur at the entrance and exit of each block
Disadvantages

Object-Oriented languages

Advantages
  • The software objects model real world objects so program composition is well defined and structured
  • Each object's definition and internal implementation is decoupled from other objects, making the system design inherently modular (Encapsulation)
  • Adding new features becomes easier because of inheritance, allowing the new class to contain the new feature in addition to all old features from the inherited class
  • Debugging is easier since each object's internal mechanisms are independent of each other, which helps in isolating errors and fixing them
  • Enhanced code reusability
Disadvantages
  • The complexity of object-oriented design becomes prohibitive when working on small projects
  • Object-oriented programming paradigm is preferable for dynamic environments rather than simple environments
  • Reduced time efficiency compared to block-structured languages

Summary of important differences

Difference Block Structured Languages Object-Oriented Languages
Problem approach Top-down approach is followed Bottom-up approach is followed
Problem focus Focus is on the algorithm to solve the problem Focus is on getting the object design right
View of data and functions Views data and functions as separate entities Views data and functions as single entity
Cost of maintenance Maintenance is costly Maintenance is relatively cheaper
Software reuse Software reuse is not possible Software reuse is possible
Abstraction Function abstraction is used Data abstraction is used

Effectiveness and durability

Although block structured languages were simpler and faster for smaller projects, when it comes to large commercial undertaking the manpower and tools required to maintain the code base is very prohibitive. It was very difficult to fix issues, add new features, and at the same time to make sure that the integrity of the code base is intact. Many projects were perpetually stagnant at 90%<ref>Fayad, Mohamed, and Mauri Laitinen. Transition to Object-oriented Software Development. New York: Wiley, 1998. Print.</ref> completion with issues coming up at the eleventh hour. All these problems led to the hastening of the move to object-oriented languages which showed it had the solutions to all the problems that block structured languages could not solve. The following four points are the most important reasons why object-oriented languages were more effective and durable that block structured languages:

  • Maintenance - In block structured languages, especially in large projects, system maintenance became a challenge. Object oriented languages could counter this by providing clear demarcation between the objects and making it easier to work on individual aspects of the system without disturbing the other components.
  • Data hiding - In block structured language system the data usually has global scope. Hence it is very difficult to monitor or supervise data access. This was solved by object-oriented languages by providing data encapsulation. The data and the corresponding attributes are put into a nice little package that was much easier to control and monitor.
  • Code reuse - Object oriented languages are proponents of code reuse. Hence the code size could be reduced sufficiently enough when it comes to large projects to warrant a shift from block structured to object oriented languages.
  • Feature additions - Object oriented languages provide a very cost effective and safe way to add new features to the existing system without causing the whole system to collapse. This feature is very important for large scale software vendors who provide various customizations.

Applicability between paradigms

Object-oriented languages have solved many problems that block structured languages introduced. But all is not lost with block structured languages. They boast some very important features that are needed in any programming language. The simplicity and readability of code in block structured languages are enviable features indeed. Because of this very simplicity we find that block structured languages are very efficient in terms of speed and performance. Such a language would also provide the flexibility in moving legacy block structured systems to the object oriented paradigm seamlessly. A language that can capture both sides of the argument would be a formidable entry into the growing list of programming languages. This explains why we see C++ emerging as one of the most popular object oriented languages. It has both the block structured features of C and the object-oriented concepts built into it, thereby making it a very versatile and efficient programming language.

C/C++ Case Example

Below are code examples highlighting key differences between a block structured program and an object oriented program. The execution of each program results in identical output. C and C++ were chosen as the languages for example so a more direct comparison could be made, despite the fact that C++ is not a "true" object oriented language<ref>http://www.jvoegele.com/software/langcomp.html Programming Language Comparison by Jason Voegele</ref>.

Block structure

The below example illustrates a typical block structure program. The listing begins with the requisite headers to include functionality, followed by declarative statements that define some blocks ("functions prototypes") later in the program. Program execution begins in the main() method, where the various commands to print to the screen are executed by calling each function's respective message. The functions are focusing on the functionality, and no data association is occurring at all.

// C standard header files
#include <stdio.h>
#include <stdlib.h>

// Define the messages of each persona
#define KING_MESSAGE   "Read my lips: No new taxes"
#define JESTER_MESSAGE "My wife and I were happy for 20 years. Then we met."
#define PEON_MESSAGE   "The king himself created his own worst enemy, just as tyrants everywhere do!"

// Define the function prototypes for delivering the different messages
char *getKingMessage();
char *getJesterMessage();
char *getPeonMessage();

// Main program entry point
int main()
{
	// Go through and make each function call for...
	// The King
	printf("And now a message from the king: %s\n", getKingMessage());
	printf("The King has spoken!\n\n");

	// The Court Jester
	printf("And now a message from the court jester: %s\n", getJesterMessage());
	printf("Wocka wocka wocka!\n\n");

	// A Peon
	printf("And now a message from a peon: %s\n", getPeonMessage());
	printf("... but don't mind me!\n\n");
	
	// Wait for user input before exiting
	system("pause");

	return 0;
}

// Returns a string containing the text to be spoken by the king
char *getKingMessage()
{
	return KING_MESSAGE;
}

// Returns a string containing the text to be spoken by the court jester
char *getJesterMessage()
{
	return JESTER_MESSAGE;
}

// Returns a string containing the text to be spoken by all peons
char *getPeonMessage()
{
	return PEON_MESSAGE;
}

Object oriented structure

The below object oriented structure source code yields a program that has the exact same output as the block structure program above. The listing begins with the necessary headers to include functionality in the program. This is followed by a class (object) definition for a Person, and how the King, Jester, and Peon all inherit the capabilities and attributes of a Person (like having a label (title of nobility or lack thereof) and being able to DeliverMessages). Due to inheritance, each of these people is permanently defined by their label -- it will not change due to the nature of a Monarchy. Also, the person's data (label/message) is firmly associated with their functions (DeliverMessage). Carrying on, the program's main function begins by initializing instance of each King, Jester, and Peon, instilling in each one their own unique message and finally having them deliver it (to the screen). The object oriented structure has a lot of boilerplate code necessary to describe this structure, but once it comes to initialization and execution, the program logic and organization simplifies greatly compared to block structure.

// C++ standard headers
#include <cstdio>
#include <cstdlib>

// Define what each persona should say
#define KING_MESSAGE   "Read my lips: No new taxes"
#define JESTER_MESSAGE "My wife and I were happy for 20 years. Then we met."
#define PEON_MESSAGE   "The king himself created his own worst enemy, just as tyrants everywhere do!"

// Keep all classes clearly separated from other sections of code
namespace Monarchy
{
	// Define a basic class where a person has a label and something they want to say
	class Person
	{
	private:
		char *szMessage;
		char *szLabel;

	public:
		// Allow a person to deliver their message
		void DeliverMessage()
		{
			printf("A now a message from %s: %s\n", this->szLabel, this->szMessage);
		}

		// A person needs to be initialized with a label and a message
		Person(char*label, char *msg)
		{
			this->szLabel = label;
			this->szMessage = msg;
		}
	};

	// The King is a person (and thus inherits from it)
	class King : public Person
	{
	public:
		// The king has the same label, but his message might change according to the political winds
		King(char *msg) : Person("the king", msg)
		{
		}

		// Here, the function is being overridden...
		void DeliverMessage()
		{
			// .. but the base class's DeliverMessage is still being called, in addition to the tag line
			Person::DeliverMessage();
			printf("The King has spoken!\n\n");
		}
	};

	// A peon is a person (and thus inherits from it)
	class Peon : public Person
	{
	public:
		// A peon has the same label but his message might change according to his or her attitude toward the king
		Peon(char *msg) : Person("a peon", msg)
		{
		}

		// Like above, deliver the message, but always provide a common tag line
		void DeliverMessage()
		{
			Person::DeliverMessage();
			printf("... but don't mind me!\n\n");
		}
	};

	// A jester is a person (and thus inherits from it)
	class Jester : public Person
	{
	public:
		// A peon has the same label but his message might change if the king is sick of his jokes
		Jester(char *msg) : Person("the court jester", msg)
		{
		}

		// Might as well call him Fozzie ;)
		void DeliverMessage()
		{
			Person::DeliverMessage();
			printf("Wocka wocka wocka!\n\n");
		}
	};
}

// Main program entry point
int main()
{
	// Initialize some monarchy objects
	Monarchy::King TheKing(KING_MESSAGE);
	Monarchy::Jester Borat(JESTER_MESSAGE);
	Monarchy::Peon Bruno(PEON_MESSAGE);

	// Let them deliver their messages
	TheKing.DeliverMessage();
	Borat.DeliverMessage();
	Bruno.DeliverMessage();

	// Wait for user input
	system("pause");

	return 0;
}

Output (both structures)

And now a message from the king: Read my lips: No new taxes
The King has spoken!

And now a message from the court jester: My wife and I were happy for 20 years. Then we met.
Wocka wocka wocka!

And now a message from a peon: The king himself created his own worst enemy, just as tyrants everywhere do!
... but don't mind me!

Press any key to continue . . .

See also

References

<references/>

Further reading

  • Freeman, Eric, Elisabeth Freeman, Kathy Sierra, and Bert Bates. Head First Design Patterns. Sebastopol, CA: O'Reilly, 2004. Print.
  • Liberty, Jesse. Sams Teach Yourself C++ in 24 Hours. Indianapolis, IN: Sams, 2002. Print.
  • Microsoft Visual C++ Language Reference. Redmond, WA: Microsoft, 1997. Print.
  • Weiss, Mark Allen. Data Structures & Algorithm Analysis in Java. Reading, MA: Addison-Wesley, 1999. Print.

External links