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

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
Line 5: Line 5:


== Overview of Block Structured Languages ==
== Overview of Block Structured Languages ==
Every programming language has a unique syntax and a set of instructions which are usually in a form of statements that should conform to a set of rules in defining and constructing it. The construction of these instruction depends on the language you use. Most of them follow a procedural approach where implementation is done step by step while other require objects to come up with a solution. Among these,  the most common and used technique is what we called block structure programming where declarations and statements are grouped together in a form of a block.
Every programming language has a unique syntax and a set of instructions which are usually in a form of statements that should conform to a set of rules in defining and constructing it. Most of them follow a procedural approach where implementation is done step by step while other require objects to come up with a solution. Among these,  the most common and used technique is what we called block structure programming where declarations and statements are grouped together in a form of a block.


Block structured programming language permits the creation of blocks, with blocks nested within other blocks. The function of blocks in programming is to enable groups of statements to be treated as if they were one statement, and to narrow the lexical scope of variables, procedures and functions declared in a block so that they do not conflict with variables having the same name used elsewhere in a program for different purposes.
Block structured programming language permits the creation of blocks, with blocks nested within other blocks. The function of blocks in programming is to enable groups of statements to be treated as if they were one statement, and to narrow the '''lexical scope''' of variables, procedures and functions declared in a block so that they do not conflict with variables having the same name used elsewhere in a program for different purposes.


In a block-structured programming language, the names of variables and other objects such as procedures which are declared in outer blocks are visible inside other inner blocks, unless they are shadowed by an object of the same name. They do not require prior detailing to be given to the definitions made.The structure is formed first without knowledge of inner groupings. This supports top-down development of code in an organized manner.Blocks allow the programmer to treat a group of statements as a unit, and the default values which had to appear in initialization in this style of programming can, with a block structure, be placed closer to the decision. This technique does not only simplifies the code but also contributes to its readability and maintainability.
In a block-structured programming language, the names of variables and other objects such as procedures which are declared in outer blocks are visible inside other inner blocks, unless they are shadowed by an object of the same name. They do not require prior detailing to be given to the definitions made.The structure is formed first without knowledge of inner groupings. This supports '''top-down development''' of code in an organized manner.


===Block Structure in Programming Languages ===
===Block Structure in Programming Languages ===

Revision as of 06:56, 7 September 2011

Block Structured Language vs OO Languages

Introduction

A programming paradigm is a fundamental style of computer programming. It provides for the programmer the means and structure for the execution of a program and thus serves as a pattern or model. Many programming paradigms have their own concepts and abstraction thus offering different techniques for the programming world. Also they are as well-known for what they do not do as for what they do.As a result, many programming paradigm are regarded as an improvement over earlier styles. This wiki chapter describes about Block Structured Languages and Object Oriented programming paradigm while emphasizing on the transition/improvement of Block Structured Language to Object Oriented Language due to its advantages and usage in today's programming world.

Overview of Block Structured Languages

Every programming language has a unique syntax and a set of instructions which are usually in a form of statements that should conform to a set of rules in defining and constructing it. Most of them follow a procedural approach where implementation is done step by step while other require objects to come up with a solution. Among these, the most common and used technique is what we called block structure programming where declarations and statements are grouped together in a form of a block.

Block structured programming language permits the creation of blocks, with blocks nested within other blocks. The function of blocks in programming is to enable groups of statements to be treated as if they were one statement, and to narrow the lexical scope of variables, procedures and functions declared in a block so that they do not conflict with variables having the same name used elsewhere in a program for different purposes.

In a block-structured programming language, the names of variables and other objects such as procedures which are declared in outer blocks are visible inside other inner blocks, unless they are shadowed by an object of the same name. They do not require prior detailing to be given to the definitions made.The structure is formed first without knowledge of inner groupings. This supports top-down development of code in an organized manner.

Block Structure in Programming Languages

The term 'block structure' refers to different features in different languages, which leads to a confusion about its precise meaning. There are essentially two language features for which the term is commonly used: blocks and nested procedure definitions.

Blocks

Blocks are the combination of compound statements with the declaration of identifiers.In Algol, a block defines the scope of identifiers and restricts their visibility –identifiers introduced in declarations may be used only within the block. More precisely, these scope rules define the changes in the referencing environment at block entry and exit. These changes are defined to permit their effect to be determined at compile time to permit storage for identifiers declared within the block to be allocated upon entry to the block and deallocated upon exit .

Blocks in Algol-60 are a typical example and have the form:

ALGOL

  begin 
  integer X;
  Read Int(X);
 
      begin 
      real square;
  
      square= X*X;
      Print Real(square);
      end
  end

Procedures

Procedures are blocks with formal arguments where block bodies are replaced by procedure definitions.

Blocks in Pascal are a typical example and have the form:

PASCAL

  if wages > tax_threshold then
       begin 
       paytax := true ;
       tax := (wages - tax_threshold) * tax_rate;
       if wages > supertax_threshold then 
             begin 
             pay_supertax := true;
             supertax := (wages - supertax_threshold) * supertax_rate;
             end
       else
             begin 
             pay_supertax := false;
             supertax := 0;
             end
       end
  else
       begin
       paytax :=0;
       superpaytax :=0;
       tax :=0; supertax :=0;
       end
  finaltax := wages - tax - supertax;

Notice that is easier to determine the result of the condition by just checking on the inner blocks. Changes can also be integrated with ease in this case without affecting the other blocks. This blocks can also be implemented on looping statements.

Difference between blocks and procedures

The important difference between blocks and procedures is that blocks are executed only when encountered at the site of their definition, whereas procedures are parameterized and maybe invoked from any point within the scope of their names.

Example of a block structured code in JavaScript:-

calculateVal:function(val){
   var increment = $(val).increment;
   var incValue = ;
   for(i=0;i<increment.length;i++){
      if(increments[i].selected==true){
            incValue=increment[i].value;
      }
   }
  return incValue;
}


The for looping statement uses the block structure in this code snippet. The value of incValue changes as it passes to the loop.

Advantages of Block Structured Programming

  • Restricted Visibility: The major advantage of block structure is the restricted visibility it provides for local identifiers. The visibility, or scope rules are used to associate an identifier with its proper declaration. These rules are based on the static structure of the program and, in most cases, permit all associations to be determined during compilation.
  • No Interference: In the case of blocks, identifiers may be declared in close proximity to their use. The visibility restrictions help prevent unintended interference with other uses of the same identifier.
  • Simplicity: The capability of organized structure facilitates writing blocks of codes and often simplifies their usage.

Disadvantages of Block Structured Programming

  • Readability: Block structure can make even moderately large programs difficult to read. The difficulty is due to the physical separation of procedure headings from their bodies which is a result of the 'definition before use' rule in most languages.
  • Separate Compilation: Separate compilation is essential in any large software project where the designers must work 'in-the-large'(with many modules) as opposed to 'in-the-small'(with several procedures in one module) Because procedures depend on the environment in which they are nested ,only outermost procedures are suitable for separate compilation. Recompilation of an outer most procedure involves recompilation of the procedures nested within it.
  • Implementation: Block structure complicates the implementation and execution due to referencing which result in a demand for a lot of register space in the microprocessors as opposed to modules.

Overview of Object Oriented Language

As programming languages evolve, so does the structure of programming. After structured programming, came a new form of programming in the 1970's called Object Oriented which is a methodology for modeling the real world by decomposing the problem into smaller discrete pieces called 'Objects'. OO languages are constituted by class and objects, methods that manipulate the objects and other features such as Encapsulation, Inheritance, Polymorphism,etc. Class definitions must allow objects to cooperate during execution. Thus, OO languages involve programming based on a hierarchy of classes, and well-defined objects.

Object Oriented Methodology

Object oriented programming language took the best ideas of the structured programming and combined them with many new concepts like objects and classes.This makes it imperative to introduce these parts for better understanding of OO Methodology.

  • Classes

The class is the fundamental object-oriented unit. It is a structure that defines the data and the methods to work on that data. Classes define a set of objects that share a common structure and behavior. When you write programs in the Java language, all program data is wrapped in a class.All objects are created from classes, so it important to understand the structure of a class. In fact, it is the design of classes that has fueled the development of various object-oriented languages.Object is an instance of a class.

  • Objects

An "Object" is binding together of data and behavior, and Object Oriented programming, is the use of objects while solving the problem. What makes an "object" unique is the formal and explicit combination of these smaller pieces' behavior with its' data into a single entity.

  • Methods

The object's behaviors are called methods in OO terminology, while its data is called the Object's state.

Principles of OO Languages

Formally, there are technical attributes that must be present for a program (or a programming Language) to be considered Object Oriented, such as inheritance, polymorphism, encapsulation, and protection.

Encapsulation:

One of the most important characteristics of OOP is data encapsulation where the internal representation of an object is generally hidden from view outside of the object's definition. The public interface, formed by the collections of messages understood by an object, completely defines how to use this object. Programs that want to manipulate an object, only have to be concerned about which messages this object understands, and do not have to worry about how these tasks are achieved nor the internal structure of the object. The hiding of internal details makes an object abstract, and the technique is normally known as data abstraction.

Inheritance:

Another powerful feature of OOP, is the concept of inheritance,that allows a (sub)class to inherit all the attributes and methods of a parent class – in effect, extending the parent. It can best be described as an “is a” relationship. The derived class can inherit the properties of its base class and also adds its own data and routines. The concept above is known as single inheritance, but it is also possible to derive a class from several base classes, which is known as multiple inheritance.

Composition:

Composition is a slightly different sort of relationship – this is where it could be said that a class was “composed” of other classes. For instance,a wall is “composed” of bricks and a molecule is “composed” of atoms. Neither of these examples could be described as inheritance – the statement, “a wall is a brick” simply isn’t true. Composition can be described as “has a” and “uses a” relationships; a wall “has a” brick or a wall “uses a” brick.

Polymorphism:

An object-oriented programming language must support polymorphism; meaning different classes can have different behaviors for the same attribute or method.And one more important characteristics is polymorphism where message is sent to an object without concern about how the software is going to accomplish the task, and furthermore it means that the task can be executed in completely different ways depending on the object that receives the message. This can best be illustrated with an example:

   class formElement
   {
      Attributes:
       id
       name
       class
      Methods:
       getHtml()
       {
         // returns generic form element HTML
       }
   }
   class textArea extends formElement
   {
      Attributes:
       cols
       rows
      Methods:
       getHtml()
       {
        // returns textarea form element HTML
       }
   }

As you can see in the example, both classes have the method “getHtml” but the “textarea” class is a subclass of the “formElement” class. This results in the “getHtml” method being overloaded. Overloading is a good example of polymorphism in action – an object-oriented language must support polymorphism in order to know which “getHtml” method applies to which object.

Why use Object Oriented Programming?

Object-orientation can help programmers create relationships between one object and another. For example, objects can inherit characteristics from other objects. One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that it eliminates the redundant code and extends the use of existing classes providing Reusability. It provides security to program by using the Data hiding principles. The multiple objects can be co-exists without any reference leading to Maintainability and Modularity of code. Work can be divided into easily manageable units i.e. objects. Complexity can be managed easily through abstraction. Simpler syntax. Have wide areas of applications such as real time systems,object oriented databases,neutral network, expert system and artificial intelligent.

Examples of OO Languages

Simula was the first object-oriented programming language. Java, Python, C++, Visual Basic .NET and Ruby are the most popular OOP languages today. The Java programming language is designed especially for use in distributed applications on corporate networks and the Internet. Ruby is used in many Web applications. Curl, Smalltalk, Delphi and Eiffel are also examples of object-oriented programming languages.

An example to check if a given number is Even or Odd in Java:

public class FindEvenOrOddNumber 
{
 public static void main(String[] args) 
 {
  int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10}; //create an array of 10 numbers
  for(int i=0; i < numbers.length; i++)
  {
   if(numbers[i]%2 == 0)
   System.out.println(numbers[i] + " is even number.");
   else
   System.out.println(numbers[i] + " is odd number.");
  }
 }
}

History of Block Structure: Before OO Language

Ideas of block structure were developed in the 1950s during the development of the first autocodes, and were formalized in the Algol 58 and Algol 60 reports. Algol 58 introduced the notion of the "compound statement", which was related solely to control flow.

The subsequent Revised Report which described the syntax and semantics of Algol 60 introduced the notion of a block, consisting of " A sequence of declarations followed by a sequence of statements and enclosed between begin and end..." in which every declaration appears in a block in this way and is valid only for that block.

The notion of blocks is introduced by different syntax in different languages, but there are two broad families: the ALGOL family in which blocks are delimited by the keywords begin and end, and the C family in which blocks are delimited by curly braces "{" and "}".

Block Structure permited efficient use of storage. As a consequence of the scope rules, storage was shared among local variables of procedures declared at that level. This is the reason that an Algol program required storage than a Fortran program. In Algol, storage was required for data associated for active procedures while in Fortran the storage was required for data associated for all procedures.

Transition to Object Oriented language

One of the major purposes of block structure is to hide information, but it is an inadequate mechanism for doing so. The visibility rules are implicit and based only on nesting. The need for an explicit and more general means of controlling visibility had been recognized. Thus, came the transition from block structured to Object Oriented Programming(OOP).

Another prime reason for OO languages taking over the block structured was the debugging comfort that it provided as the programs were getting larger and larger and it became difficult to debug.

Other important points that make OOP better than Block Structure are :-

  • simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear.
  • modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.
  • modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside the class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.
  • extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.
  • maintainability: objects can be maintained separately, making locating and fixing problems easier.
  • re-usability: objects can be reused in different programs.

Block Structure in Object Oriented Language

Block Structure in any language is defined to be a block of a code that is grouped together. It can be any block of code like conditional statements as in 'if' and 'else' or looping constructs like 'for' loop or 'while' loop. Most OOP language basically involves such conditional statement and constructs like Java, C++ or Ruby. Block Structure is basically still a part of OOP languages nowadays.

In OOP terminology, block structure means classes, nested classes, methods and blocks. Object is used as a common name for instance of a class. A block activation is an instance of a block while in OOP it is an instance of a class which is an object.

Simple Class Definition in Java :-

    Class Employee
    {
        int age;
        String name;
        int id;
        Employee(int Eage,String Ename, int Eid)
        {
             age=Eage;
             name=Ename;
             id=Eid;
        }    
        void display()
        {
            System.out.println("Employee "+ name + " has age " + age " and id " +id ");
        }
    }

This code describes a class which also defines a block structure describing class and methods in JAVA.

Following aspects of block structure are viewed in OOP languages:-

  • Locality:- The major advantage of block structure is locality. This makes it possible to restrict the existence of an object and its description to the environment where it has meaning.
  • Scope Rule :- These are following aspects of scope rules for names declared within an object:
    • They only exist when the object exist. This is a consequence of locality.
    • Access to global names and re-declaration of names.
    • Access to names within a block from “outside” the block may be restricted. Like in Simula language.

Comparison of Block Structure and Object Oriented Language

Block-Structured Languages Object Oriented Languages
Block Structure involves section of code grouped together with one or more declaration and statements Object Oriented Programming involves programming around objects which is an instance of a class representing data fields and methods for interaction.
Block Structure provides no means of access to variables and limits the scope within the block. Object Oriented Programming allows to define different access specifiers(public,private,protected) when defining any field or method.
Maintainibility is difficult as the programs size increases Easy to maintain as objects can be maintained separately thus making easy to locate and manage.
Program flow has a single point of entry and exit Program flow depends on the state and interaction within objects.
Has limited modifiability where a procedure is defined for performing certain function which cannot be modified to a greater extent Easy to make changes in the data representation and methods as changes within a class do not affect others.
No re-usability Objects can be re-used in another programs.
Not preferable when working with large programs Can handle large programs due to its design, organization and flow of the program.
Limited Modularity The objects form a separate entity whose internal workings are decoupled from other parts of the system.
Limited extensibility as very difficult to extend the modules and its function which requires re-structuring Introduction of few new objects can help in adding or changing new features.
Example :- Algol 60,Pascal, C Example:- Simula,C++,JAVA,Ruby

Conclusion

Block Structure Languages is not a programming paradigm but falls under structured programming paradigm and Object Oriented Programming is a forerunner of structured programming. Object Oriented Programming have many features which are an improvement towards many block structure programming languages like Algol and Pascal. Block Structure is useful in number of technical problems in programming. Object Oriented Programming makes modelling any phenomena useful as it characterizes an object by means of a class. Object Oriented Programming is used nowadays in software world making it easy for developer to map the problems into objects and into classification hierarchies.

Reference

  1. Structured Programming
  2. Block Programming
  3. Object Oriented Programming
  4. Block Structure Programming Languages
  5. Object Oriented vs Structured Programming Tayfun Bilsel
  6. Dictionary of Programming Languages
  7. Evolution of OOL
  8. Java
  9. Programming Paradigm
  10. Pascal
  11. Simula
  12. Ruby
  13. [IsBlockStructureNecessary? by DAVIDR.HANSON, University of Arizona]