EXCEPTION HANDLING AND EVENT HANDLING

EXCEPTION HANDLING AND EVENT HANDLING

Exception handling is a special processing that may required after detection of an exception. Exception handling code unit is called an exception handler. There are many program that allow program to trap input/output errors(including EOF). An exception is any usual event, either erroneous or not, detectable by either hardware or software, that may require special processing.

In a language without exception handling, when an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated.

In a language with exception handling, program are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing.

Advantages of built-in exception handling :

  • Error detection code is tedious to write and it clutters the program
  • Exception handling encourages programmers to consider many different possible errors
  • Exception propagation allows a high level of reuse of exception handling code

Exception handling control flow

C++ exception handlers,

  • Exception Handlers Form:

               try {

— code that is expected to raise an exception

}

catch (formal parameter) {

handler code

}

catch (formal parameter) {

handler code

}

 

Catch function,

  • catch is the name of all handlers–it is an overloaded name, so the formal parameter of each must be unique
  • The formal parameter need not have a variable,

It can be simply a type name to distinguish the handler it is in from others

  • The formal parameter can be used to transfer information to the handler
  • The formal parameter can be an ellipsis, in which case it handles all exceptions not yet handled

 

Throwing exceptions,

  • Exceptions are all raised explicitly by the statement:

               throw [expression];

  • The brackets are metasymbols
  • A throw without an operand can only appear in a handler; when it appears, it simply re-raises the exception, which is then handled elsewhere
  • The type of the expression disambiguates the intended handler

 

Unhandled exception,

  • An unhandled exception is propagated to the caller of the function in which it is raised
  • This propagation continues to the main function
  • If no handler is found, the default handler is called

 

Event handling, an event is a notification that something specific has occurred, such as a mouse click on a graphical button. Event handler is a segment of code that is executed in response to an event.

Posted in Uncategorized | Leave a comment

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING

 

Object-oriented programming (OOP) , there are three major language features; ADT, Inheritance (inheritance is the central theme in OOP an language that support it, Polymorphism. Inheritance can increase productivity by reuse. ADTs are difficult to reuse-always need change, all ATDs are independent and at the same level.

Object-Oriented Concept

  • ADTs are usually called classes
  • Class instances are called objects
  • A class that inherits is a derived class or a subclass
  • The class from which another class inherits is a parent class or superclass
  • Subprograms that define operations on objects are called methods
  • Calls to methods are called messages
  • The entire collection of methods of an object is called its message protocol or message interface
  • Messages have two parts–a method name and the destination object
  • In the simplest case, a class inherits all of the entities of its parent
  • Inheritance can be complicated by access controls to encapsulated entities
    1. A class can hide entities from its subclasses
    2. A class can hide entities from its clients
    3. A class can also hide entities for its clients while allowing its subclasses to see them
  • Besides inheriting methods as is, a class can modify an inherited method
    1. The new one overrides the inherited one
    2. The method in the parent is overriden
  • Three ways a class can differ from its parent:
  1. The parent class can define some of its variables or methods to have private access, which means they will not be visible in the subclass
  2. The subclass can add variables and/or methods to those inherited from the parent
  3. The subclass can modify the behavior of one or more of its inherited methods.
  • There are two kinds of variables in a class:
    • Class variables – one/class
    • Instance variables – one/object
  • There are two kinds of methods in a class:
    • Class methods – accept messages to the class
    • Instance methods – accept messages to objects
  • Single vs. Multiple Inheritance
  • One disadvantage of inheritance for reuse:
    • Creates interdependencies among classes that complicate maintenance

 

 

Design issues for OOP

  • The exclusivity of objects, everything is an object, add objects to a complete typing system, include an imperative-style typing system for primitives but make everything else objects.
  • Are subclases subtypes, If a derived class is-a parent class, then objects of the derived class must behave the same as the parent class object. Subclass can only add variables and methods and override inherited methods in “compatible” ways.
  • Single and multiple ineritance, multiple inheritance allows a new class to inherit from to or more classes. The disadvantages is language and implementation complexity. The Advantage it is quite convenient and valuable.
  • Object allocation and deallocation, If they behave line the ADTs, they can be allocated from anywhere. If they are all heap-dynamic, references can be uniform thru a pointer or reference variable. If objects are stack dynamic, there is a problem with regard to subtypes – object slicing.
  • Dynamic and static binding,

Should all binding of messages to methods be dynamic?

  • If none are, you lose the advantages of dynamic binding
  • If all are, it is inefficient

Maybe the design should allow the user to specify

  • Nested classes, If a new class is needed by only one class, there is no reason to define so it can be seen by other classes.

Support for OOP in C++,

  • General Characteristics:
    • Evolved from C and SIMULA 67
    • Among the most widely used OOP languages
    • Mixed typing system
    • Constructors and destructors
    • Elaborate access controls to class entities

 

  • Implementation of Object-Oriented Constructs Two interesting and challenging parts; Storage structures for instance variables, dynamic binding of messages to methods.

 

Posted in Uncategorized | Leave a comment

ABSTRACT DATA TYPES

ABSTRACT DATA TYPES

The concept of abstraction , abstraction is a viow or representation of an entity that includes only the most significant attributes. The concept is fundamental in programing. Almost all programming language support process abstraction with subprogram and support data abstraction.

Introduction to data abstraction , abstract data type is a user-defined data type that statisfies  this condition:

  • The representation of objects of the type is hidden from the program units that use these objects, so the only operations possible are those provided in the type’s definition
  • The declarations of the type and the protocols of the operations on objects of the type are contained in a single syntactic unit. Other program units are allowed to create variables of the defined type.

Language examples C++ ,

  • Based on C struct type and Simula 67 classes
  • The class is the encapsulation device
  • A class is a type
  • All of the class instances of a class share a single copy of the member functions
  • Each instance of a class has its own copy of the class data members
  • Instances can be static, stack dynamic, or heap dynamic
  • Information Hiding
    • Private clause for hidden entities
    • Public clause for interface entities
    • Protected clause for inheritance
  • Constructors:
    • Functions to initialize the data members of instances (they do not create the objects)
    • May also allocate storage if part of the object is heap-dynamic
    • Can include parameters to provide parameterization of the objects
    • Implicitly called when an instance is created
    • Can be explicitly called
    • Name is the same as the class name
  • Destructors
    • Functions to cleanup after an instance is destroyed; usually just to reclaim heap storage
    • Implicitly called when the object’s lifetime ends
    • Can be explicitly called
    • Name is the class name, preceded by a tilde (~)

 

 

Example in C++:

class Stack {

private:

int *stackPtr, maxLen, topPtr;

public:

Stack() { // a constructor

stackPtr = new int [100];

maxLen = 99;

topPtr = -1;

};

~Stack () {delete [] stackPtr;};

void push (int number) {

if (topSub == maxLen)

cerr << ″Error in push – stack is full\n″;

else stackPtr[++topSub] = number;

};

void pop () {…};

int top () {…};

int empty () {…};

 

 

Parameterized abstract data types, classes can be somewhat generic by writing parameterized constructor functions

               Stack (int size) {

stk_ptr = new int [size];

max_len = size – 1;

top = -1;

};

 

A declaration of a stack object:

               Stack stk(150);

 

  • The stack element type can be parameterized by making the class a templated class
    template <class Type>
    class Stack {
    private:
    Type *stackPtr;
    const int maxLen;
    int topPtr;
    public:
    Stack() {  // Constructor for 100 elements
    stackPtr = new Type[100];
    maxLen = 99;
    topPtr = -1;
    }

Stack(int size) {  // Constructor for a given number

stackPtr = new Type[size];

maxLen = size – 1;

                topSub = -1;

       }

}

    – Instantiation: Stack<int> myIntStack;

 

 

Encapsulation constructs,

  • Large programs have two special needs:
    • Some means of organization, other than simply division into subprograms
    • Some means of partial compilation (compilation units that are smaller than the whole program)
  • Obvious solution: a grouping of subprograms that are logically related into a unit that can be separately compiled (compilation units)
  • Such collections are called encapsulation

 

Naming encapsulation, Organizing programs by nesting subprogram definitions inside the logically larger subprograms that use them. Nested subprograms are supported in Ada, Fortran 95+, Python, JavaScript, and Ruby

 

 

Posted in Uncategorized | Leave a comment

SUBPROGRAM

SUBPROGRAM

Subprogram is part of program that can be tested and designed independently. There are two kind of subprogram; function and procedure. Function return value, procedure just executes command.

Fundamentals of subprograms:

  • each subprogram has single entry point
  • the calling program is suspended during execution of the called subprogram
  • control always return to the caller when the called subprogram’s executions terminates

 

Local referencing environments

  • Local variables can be stack-dynamic
    • Advantages
      • Support for recursion
      • Storage for locals is shared among some subprograms
    • Disadvantages
      • Allocation/de-allocation, initialization time
      • Indirect addressing
      • Subprograms cannot be history sensitive
    • Local variables can be static
      • Advantages and disadvantages are the opposite of those for stack-dynamic local variables

Parameter-passing methods, models of parameter passing ;

Pass-by-value ( in mode ), the value of the actual parameter is used to initialize the corresponding formal parameter.

Pass-by-result ( out mode), before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called call by result. In general, pass by result technique is implemented by copy.

Pass-by-value-result / pass-by-copy (inout mode), combination of pass-by-value and pass-by-result. The formal parameters have local storage.

Pass-by-reference(aliasing) / pass-by-sharing (inout mode) , used by pass an access path. In c used by using pointer. Efficient because no copying and no duplicated storage.

Pass-by-name ( inout mode), passed by textual substitution. Formals are bound ot an access method at the time of the call, but the actual binding to a value or address takes place at the time of a reference or assignment. Allows flexibility in late binding .

 

Parameters that are subprograms,  referencing environment:

  • Shallow binding: The environment of the call statement that enacts the passed subprogram
    – Most natural for dynamic-scoped

Languages

  • Deep binding: The environment of the definition of the passed subprogram
    – Most natural for static-scoped languages
  • Ad hoc binding: The environment of the call statement that passed the subprogram

 

Calling subprograms indirectly, Usually when there are several possible subprograms to be called and the correct one on a particular run of the program is not know until execution (e.g., event handling and GUIs). In C and C++, such calls are made through function pointers.

 

Overloaded subprograms is a subprogram that has the same name with other subprogram in same refencing environment.

Generic subprograms or polymorphic subprogram takes parameter of different types on different activasions. It provide ad hoc polymorphism.

User-defined overloaded operators,

  • Operators can be overloaded in Ada, C++, Python, and Ruby
  • A Python example

def __add__ (self, second) :

                               return Complex(self.real + second.real,

self.imag + second.imag)

Use: To compute x + y, x.__add__(y)

 

Closures , is a subprogram and the referencing environment where it was defined.

  • The referencing environment is needed if the subprogram can be called from any arbitrary place in the program
  • A static-scoped language that does not permit nested subprograms doesn’t need closures
  • Closures are only needed if a subprogram can access variables in nesting scopes and it can be called from anywhere
  • To support closures, an implementation may need to provide unlimited extent to some variables (because a subprogram may access a nonlocal variable that is normally no longer alive)

 

Coroutines

  • A coroutine is a subprogram that has multiple entries and controls them itself
  • Also called symmetric control: caller and called coroutines are on a more equal basis
  • A coroutine call is named a resume
  • The first resume of a coroutine is to its beginning, but subsequent calls enter at the point just after the last executed statement in the coroutine
  • Coroutines repeatedly resume each other, possibly forever
  • Coroutines provide quasi-concurrent execution of program units (the coroutines); their execution is interleaved, but not overlapped

 

Posted in Uncategorized | Leave a comment

STATEMENT-LEVEL CONTROL STUCTURES

STATEMENT-LEVEL CONTROL STUCTURES

Control structure is a control statement and the statement whose execution it controls.

Selection statements, provide the means of choosing between two or more path of execution.

There are two general categories :

  • Two-way selector

Example: if-else

General form : if control_expresion

Then clause

Else clause

We can also make nesting selectors , to be clear look at the example.

Example of nesting selector :

If(sum == 0 ){

If(count == 0 )

Result = 0;

}

Else result = 1;

  • Multiple way selector

Allow the selection of one of any number of statement in statement groups.

For example: if-else if , C’s switch case(in C’s switch case the control expression can be only an integer type).

Example of using C,C++, Java, and JavaScript switch case ;

Switch(expression) {

Case cons_exprt1: stmt1;

Case cons_exprt2: stmt2;

Default: stmt(n+1)

}

Example of multiple-way selection using if :

If coutn < 10 :

Bag1 = True

Elif count < 100 :

Bag2 = True

Elif count < 1000 :

Bag3 = True

The Python example can be written as a Ruby case

case

when count < 10 then bag1 = true

when count < 100 then bag2 = true

when count < 1000 then bag3 = true

end

 

Iterative statements, repeated execution of a statement or compound statement is accomplished either by iteration or recurtion.

Counter-controlled loops, counting iterative statement has a loop variable and a means of specifying the initial and terminal, and stepsize values.

Example: for ,, for ([expr_1] ; [expr_2] ; [expr_3]) statement

Logically controlled loops, the repetition control based on a Boolean expretion.

It can be pretest or posttest. Pretest is testing the statement first before returning the value. Posttest is return the value first then test. Example of pretest is while . example of posttest is do-while.

User-controlled loop control mechanism, example in C there are break to stop a loop and continue to skip the remainder of the current iteration but does not exit the loop.

Iteration based on data structures

  • The number of elements in a data structure controls loop iteration
  • Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate
  • C’s for can be used to build a user-defined iterator:

               for (p=root; p==NULL; traverse(p)){

}

 

Posted in Uncategorized | Leave a comment

EXPRESSION AND ASIGNMENT STATEMENTS

EXPRESSION AND ASIGNMENT STATEMENTS

Expressions are fundamental means of specifying computation in programming language. We need to be familiar with orders of operator and operand evaluation to understand expression evaluation. This is very important for programmer to understand syntax, semantics, and expression from the used programming language.

Arithmetic expressions , consist of operators, operands, parentheses, and function call.

  • Operators

Unary operator: has one operand

Binary operator: has two operands

Ternary operator: has three operands

Operator precedence rules: parentheses → unary operators → **(if the language support) → *, / → +,- .

Operator associativity rule: rules for expression evaluation define the order when the operators precedence level are same. Typical associativity rules is left to right, except **. And sometimes unary operators associate right to left.

Overloaded operators is when an operator used for more than one purpose. For example: + for int and float. C++, C#, and F# allow user-defined overloaded operators.  But there are potential problems: user can define nonsense operations, and readability may suffer even when the operators make sense.

Type conversions :

Narrowing conversion, convert an object to a type that cannot include all of the values  of the original type. Example: float to int.

Widening conversion, object converted to a typep that can include at elase approximations to all of the values of the original type. Example: int to float.

An error can occur in expression because division by zero, limitation of computer arithmetic.

Relational and Boolean expressions

  • Relational expression: use relational operators and operands of various tupes, evaluate to some Boolean representation
  • JS and PHP have two additional operator, === and !==, it’s similar to == and != except they do not coerce their operands. Coercion is an implicit type conversion, in most  language all numeric types are coerced in expression using widening conversions.

Short-circuit evaluation is an expression which the result is determined without evaluating all of the operands and/or operators. Example: (13 * a) * (b / 13 -1 ). If a is zero, there is no need to evaluate (b / 13 -1 ).

Assignment statements is a process to save a value in some location that named as variable.

Mixed mode assignment, in Fortran, C, Perl, and C++ any numeric type value can be assigned to any numeric type variable. In java and C# only widening assignment coercions are done. In Ada there is n assignment coercion.

 

Posted in Uncategorized | Leave a comment

GSLC DATA TYPES

GSLC DATA TYPES

 

  1. What are the advantages and disadvantages of decimal data types?
    2. How does a decimal value waste memory space?
    3. In what way is static type checking better than dynamic type checking?
    4. What is coercion in programming languages?
    5. Explain how coercion rules can weaken the beneficial effect of strong typing?

 

  1. Advantages :

able to precisely store decimal values at least those within a restricted range, which can’t be done with floating-point

Disadvantages :

range of the value is restricted because no exponents are allowed, and their representation in memory is mildly wasteful.

 

  1. Decimal types are stored using binary codes for the decimal digits. These representations are called binary coded decimal (BCD). They take more storage than binary representations. It takes at least four bits to code a decimal digit.
    Therefore, to store a six-digit coded decimal number requires 24 bits of memory.
    However, it takes only 20 bits to store the same number in binary.
    Decimal values store numeric information as digits encoded using the four bit binary equivalents: 0 (0000) to 9 (1001). That means a single byte can hold values between 0 and 99. But simply using the same byte to hold a binary value will yield values between 0 and 255 (or –128 and +127).

 

  1. The benefit of static type checking is it allows type errors to be caught early in development cycle. Usually static type checking results in compiled code that run more quickly because when the compiler knows the exact data types that are in use, it can produce optimized machine code (i.e. faster and/or using less memory). Static type checkers evaluate only the type information that can be determined at compile time, but are able to verify that the checked conditions hold for all possible executions of the program, which eliminates the need to repeat type checks every time the program is executed.

 

  1. Coercion is automatic conversion of value to to another of different data type and vice versa where it is appropriate. Also called implicit conversion.

For example:

double x, y;

x = 3;            // implicitly coercion (coercion)

y = (double) 5;   // explicitly coercion (casting)

 

  1. A language that allows many type coercions can weaken the beneficial effect of strong typing by allowing many potential type errors to be masked by simply coercing the type of an operand from its incorrect type given in the statement to an acceptable type, rather than reporting it as an error.

 

Posted in Uncategorized | Leave a comment

NAMES, BINDING, AND SCOPES

NAMES, BINDING, AND SCOPES

Variables is an abstraction of a memory cell. Variable provide a way of labeling data with a descriptive name, so the program can be understood more clearly by the reader. To design it, we must consider scope, lifetime , type checking, initialization, and type compatibility.

Name in programming language is a string of character that used to identify a program. If too short, they cannot be connotative. Every language can have different maximum character of name. for example  FORTRAN 95 has maximum 31 character but C++ has no limit.

There are special characters to variable names, for example PHP variable names must begin with dollar signs and in Ruby variables names begin with @. Special character specify the variable’s type.

Variable names are case sensitive in some language. The disadvantage is readability, because name that look alike ex(name and Name) is different.

The Concept  of Binding

Binding is association between an entity and an attribute, for ex, between operation and symbol.

Binding time is the time which a binding takes place.

Possibility binding times; language design time, language implementation time, compile time, load time, runtime.

Dynamic Type Binding, it can change after runtime when the program run.

Scope refers to the visibility of variables and methods in one part of a program to another part of that program. There are two general scope concepts in most language : local and global scope.

Block is method to creat static scope in program unit.

Ex:

{

Int temp;

Temp=list[upper];

list[upper]= list[lower];

list[lower]=temp;

}

Local scope, variables or methods that have local scope are accessible only in the current block of code.

Global scope, all of the variables defined at the beginning of a program are available to the entire program. In a function, the variables that declared at the beginning are available to all code in that function.

 

 

 

Posted in Uncategorized | Leave a comment

DESCRIBING SYNTAX AND SEMANTICS

DESCRIBING SYNTAX AND SEMANTICS

Syntax, form/structure of expression, statements, and program units that computer can interpret (grammar of the language). So syntax error will happen if the user executes command without using proper syntax.

Example: <assign> -> <var> = <expr>

Semantic, is meaning of the expression, statements, and program units. Syntax and semantics  provide language’s definition.

Grammar in programming languages is rules that determine the order of character(lexical token).

  • Unambigous grammar

<assign> → <id> = <expr>

<id>         → A | B | C | D

<expr>    → <expr> + <term> | <term>

<factor> → (<expr>) | <id>

 

  • Grammar for small language

<program> → begin<stmt_list>end

<stmt_list> → <stmt>

|  <stmt>; <stmt_list>

<stmt>    → <var>  = <expr>

<var>      → A|B|C|D

<expr>  → <var> + < var>

| <var> – <var>

| <var>

  • Grammar for simple assignment statement

<assign> → <id> = <expr>

<id>         →    A|B|C|D

<expr>    →  <id> + <expr>

|  <id> * <expr>

|  (<expr>)

|  <id>

Example of using gammar:   A = B + C

<assign> → <id> = <expr>

<assign> → A = <expr>

<assign> → A = <id> + <expr>

<assign> → A = <B> + <expr>

<assign> → A = <B> + <id>

<assign> → A = <B> + <C>

 

Parse tree,  graph that connected and  not circuler and have one root, from there it has route to every leaf.

Example:

Posted in Uncategorized | Leave a comment

INTRODUCTION TO PROGRAMMING LANGUAGE CONCEPT

INTRODUCTION TO PROGRAMMING LANGUAGE CONCEPT

Reason to learn. First topic is reason to learn programming language concept. The first step to learn programming actually is to learn programming language concept(PLC) first.  There are many reason to study the concept of programming languages. Learning PLC increase our ability to express ideas in programming, it means better use of programming languages. Studying PLC also increase our ability to learn new language, we can learn new language easier and faster. We can understand how to choose appropriate languages to use and give us better understanding of implementation of programming.

Programming domain define how to use or what is the use of programming language . Programming domain can be divided as scientific applications, business applications, artificial intelligence, system programming, web software.

Language Evaluation Criteria of a good programming language:

  • Readability: programming language easy to read and understand
  • Writability: the ease which a language can be used to create programs
  • Reliability: conformance to specifications of what we can do with the programming language
  • Cost: total of the cost is crucial to choose which programming language to use

Influences on Language Design. Programming languages must be designed so it’s not hard to understand the languages. Computer architecture(concept of planning and basic structure operation of computer system ), languages are developed around the prevalent computer architecture, known as the von Neumann architecture. Programming Design Methodologies, method to design a program.

Language Categories

  • Imperative
  • Functional
  • Logic
  • Markup / programming hybrid

Implementation Methods

  • Compilation, Programs translated into machine language. Used for large commercial applications.
  • Pure interpretation, program is not translated , run the instruction without first compiling the program. Used for small programs where efficiency is not an issue.
  • Hybrid implementation system, hybrid of compilation and pure interpretation. Used for small and medium systems when efficiency is not prior.
Posted in Uncategorized | Leave a comment