Difference between revisions of "Multi-Paradigm Programming and Scripting"
Adelo Vieira (talk | contribs) (→Static vs Dynamic Binding in Java) |
Adelo Vieira (talk | contribs) (→Static vs Dynamic Binding in Java) (Tag: Visual edit) |
||
Line 344: | Line 344: | ||
'''Binding time''' is the time at which a binding takes place. Bindings can take place at: | '''Binding time''' is the time at which a binding takes place. Bindings can take place at: | ||
+ | |||
*Language design time | *Language design time | ||
*Language implementation time | *Language implementation time | ||
Line 353: | Line 354: | ||
For example: | For example: | ||
+ | |||
*The asterisk symbol (*) is usually bound to the multiplication operation at language design time. At compile time, a variable in a Java program is bound to a particular data type. | *The asterisk symbol (*) is usually bound to the multiplication operation at language design time. At compile time, a variable in a Java program is bound to a particular data type. | ||
*'''Language design time''': Bind operator symbols to operations | *'''Language design time''': Bind operator symbols to operations | ||
Line 376: | Line 378: | ||
https://www.geeksforgeeks.org/static-vs-dynamic-binding-in-java/ | https://www.geeksforgeeks.org/static-vs-dynamic-binding-in-java/ | ||
− | |||
− | Why binding of static, final and private methods is always a static binding? | + | '''Static Binding:''' The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time . |
− | Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. | + | |
− | Let’s see by an example | + | |
+ | '''Why binding of static, final and private methods is always a static binding?''' | ||
+ | |||
+ | Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods '''cannot be overridden''' and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. Let’s see by an example:<syntaxhighlight lang="java"> | ||
+ | public class NewClass | ||
+ | { | ||
+ | public static class superclass | ||
+ | { | ||
+ | static void print() | ||
+ | { | ||
+ | System.out.println("print in superclass."); | ||
+ | } | ||
+ | } | ||
+ | public static class subclass extends superclass | ||
+ | { | ||
+ | static void print() | ||
+ | { | ||
+ | System.out.println("print in subclass."); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public static void main(String[] args) | ||
+ | { | ||
+ | superclass A = new superclass(); | ||
+ | superclass B = new subclass(); | ||
+ | A.print(); | ||
+ | B.print(); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight>'''Output''': | ||
+ | print in superclass. | ||
+ | print in superclass. | ||
+ | |||
+ | As you can see, in both cases print method of <code>superclass</code> is called. Lets see how this happens: | ||
+ | |||
+ | * We have created one object of <code>subclass</code> and one object of <code>superclass</code> '''with the reference of the <code>superclass</code>'''. | ||
+ | * Since the '''<code>print</code> method of <code>superclass</code> is <code>static</code>, compiler knows that it will not be overridden in <code>subclasses</code>''' and hence compiler knows during compile time which print method to call and hence no ambiguity. | ||
+ | |||
+ | ''As an exercise, reader can change the reference of object B to subclass and then check the output.'' | ||
+ | |||
+ | |||
+ | '''Dynamic Binding:''' In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have same method . Let’s see by an example:<syntaxhighlight lang="java"> | ||
+ | public class NewClass | ||
+ | { | ||
+ | public static class superclass | ||
+ | { | ||
+ | void print() | ||
+ | { | ||
+ | System.out.println("print in superclass."); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public static class subclass extends superclass | ||
+ | { | ||
+ | @Override | ||
+ | void print() | ||
+ | { | ||
+ | System.out.println("print in subclass."); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public static void main(String[] args) | ||
+ | { | ||
+ | superclass A = new superclass(); | ||
+ | superclass B = new subclass(); | ||
+ | A.print(); | ||
+ | B.print(); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | '''Output:''' | ||
+ | print in superclass. | ||
+ | print in subclass. | ||
+ | |||
+ | |||
+ | Here the output differs. But why? Let’s break down the code and understand it thoroughly. | ||
+ | |||
+ | * '''Methods are not static in this code.''' | ||
+ | * During compilation, the compiler has no idea as to which <code>print</code> has to be called since compiler goes only by referencing variable not by type of object and therefore '''the binding would be delayed to <code>runtime</code>''' and therefore the corresponding version of print will be called based on type on object. | ||
+ | |||
+ | |||
+ | '''Important Points''' | ||
+ | |||
+ | * Private, final and static members (methods and variables) use static binding while for virtual methods (In Java methods are virtual by default) binding is done during run time based upon run time object. | ||
+ | * Static binding uses Type information for binding while Dynamic binding uses Objects to resolve binding. | ||
+ | * Overloaded methods are resolved (deciding which method to be called when there are multiple methods with same name) using static binding while overridden methods using dynamic binding, i.e, at run time. | ||
<br /> | <br /> | ||
− | |||
==Object-Oriented Paradigm== | ==Object-Oriented Paradigm== | ||
Revision as of 17:27, 3 November 2019
Why Multi-Paradigm Programming and Scripting? | |||
---|---|---|---|
| |||
Content of this course | |||
Programming Constructs:
|
Programming Paradigms & Languages:
|
Scripting:
|
Applications of Shell Scripting:
|
Contents
- 1 Some important programming concepts
- 2 Object-Oriented Paradigm
- 3 Some tutorials
Some important programming concepts
High level - Low Level Programming
Compilation vs Interpretation
https://medium.com/@DHGorman/a-crash-course-in-interpreted-vs-compiled-languages-5531978930b6
https://guide.freecodecamp.org/computer-science/compiled-versus-interpreted-languages/
Speaking simplistically, compiled languages are those which are written in one language and, before being run, translated or "compiled" into another language, called the target language (typically in machine language that the processor can execute). Once the translation is complete, the executable code is either run or set aside to run later. Some common compiled languages include C
, C++
, Delphi
and Rust
.
The compiler
translates the high-level source program into an equivalent target program (typically in machine language).
The alternative to using a compiler
(for a compiled language) is using an interpreter
(for interpreted languages). Interpreted languages are "interpreted" live in their original source code, although in reality they are merely compiled at runtime. What this allows for is a lot more flexibility, especially when it comes to a program adaptively modifying its structure. This flexibility does have a cost; interpreted languages are considered significantly slower.
Interpreters
will run through a program line by line and execute each command.
Advantages and Disadvantages
Compiled Languages:
- Advantages:
- Programs compiled into native code at compile time usually tend to be faster than those translated at run time, due to the overhead of the translation process.
- Disadvantages:
- Additional time needed to complete the entire compilation step before testing, and Platform dependence of the generated binary code.
Interpreted Languages:
- Advantages:
- Greater flexibility
- Better diagnostics (error messages)
- An Interpreted language gives implementations some additional flexibility over compiled implementations. Because interpreters execute the source program code themselves, the code itself is platform independent (Java's byte code, for example). Other features include dynamic typing, and smaller executable program size.
- Disadvantages:
- The most notable disadvantage is typical execution speed compared to compiled languages.
- Interpreted languages were once known to be significantly slower than compiled languages. But, with the development of just-in-time compilation, that gap is shrinking.
Phases of Compilation
- Scanning:
- Parsing:
- Semantic analysis:
- Intermediate form :
- Optimization:
- Code generation phase :
Procedural - Functional and Object-Oriented Programming
Can we do Object-Oriented Programming with ANSI-C? Yes! this book explains how to do it: https://www.cs.rit.edu/~ats/books/ooc.pdf
https://www.codecademy.com/articles/cpp-object-oriented-programming
https://owlcation.com/stem/Use-Of-Object-Oriented-Programming
https://searchapparchitecture.techtarget.com/definition/object-oriented-programming-OOP
https://www.geeksforgeeks.org/object-oriented-programming-oops-concept-in-java/
http://ee402.eeng.dcu.ie/introduction/chapter-1---introduction-to-object-oriented-programming
Object-oriented programming (OOP) is a programming language paradigm structured around objects (which consists of both data and behaviors[Functions-Methods]). This is in contrast to conventional Functional programming paradigm that is structured based on actions (logic) and only loosely connects data and behaviors.
A traditional functional/procedural(*) program is structured based on actions (logic). In general, a functional program take an input data, process it and produces a result. In other words, the data, stored in variables, is passed to defined functions which perform some action and modify it or create new data. The program is centralized around the actions (logic):
- Take input data
- Process the data
- Produces a result
The object-oriented paradigm allows us to structure the program as a collection of objects that consist of both data and behaviors[Functions-Methods]. So, in object-oriented programming, data and functions are tied together in an entity called object
. We can said that one of the main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. These data in OOPs are known as properties and functions used to modify properties are called methods.
The object-oriented programming approach encourages:
- Modularisation: where the application can be decomposed into modules.
- Software re-use: where an application can be composed from existing and new modules.
Major benefits of using OOPs:
- Encapsulation : Objects created in OOPs are able to hide certain parts of code from programmer. This prevents unintentional modification in the code which may cause unwanted outcomes.
- Code Reuse : Objects created in OOPs can easily be reused in other programs.
- Software Maintenance : Code written in OOPs is easy to debug and maintain.
- Design Benefits : OOPs needs extensive design planning which certainly provide design benefits over traditional style.
For simple programming tasks, use of procedural programming style is well suited but as the program becomes complex and software architecture becomes large, object oriented programming is suitable to create modular designs and patterns. This makes it particularly useful when you create larger programs.
There are four major benefits to object-oriented programming:
- Encapsulation: in OOP, you bundle code into a single unit where you can determine the scope of each piece of data.
- Abstraction: by using classes, you are able to generalize your object types, simplifying your program.
- Inheritance: because a class can inherit attributes and behaviors from another class, you are able to reuse more code.
- Polymorphism: one class can be used to create many objects, all from the same flexible piece of code.
Languages evaluation criteria
https://www.cs.scranton.edu/~mccloske/courses/cmps344/sebesta_chap1.html
Readability | Writability | Reliability | Cost | Other criteria |
---|---|---|---|---|
This refers to the ease with which programs (in the language under consideration) can be understood. This is especially important for software maintenance.
|
This is a measure of how easily a language can be used to develop programs for a chosen problem domain.
|
This is the property of performing to specifications under all conditions.
|
The following contribute to the cost of using a particular language:
|
|
Imperative versus declarative code
Imperative paradigm
Procedural and object-oriented programming belong under imperative paradigm that you know from languages like C
, C++
, C#
, PHP
, Java
and of course Assembly
.
Your code focuses on creating statements that change program states by creating algorithms that tell the computer how to do things. It closely relates to how hardware works. Typically your code will make use of conditinal statements, loops and class inheritence.
Example of imperative code in JavaScript
is:
class Number {
constructor (number = 0) {
this.number = number;
}
add (x) {
this.number = this.number + x;
}
}
const myNumber = new Number (5);
myNumber.add (3);
console.log (myNumber.number); // 8
Declarative paradigm
Logic, functional and domain-specific languages belong under declarative paradigms and they are not always Turing-complete (they are not always universal programming languages). Examples would be HTML
, XML
, CSS
, SQL
, Prolog
, Haskell
, F#
and Lisp
.
Declarative code focuses on building logic of software without actually describing its flow. You are saying what without adding how. For example with HTML you use
to tell browser to display an image and you don’t care how it does that.
Example of declarative code in JavaScript is:
const sum = a => b => a + b;
console.log (sum (5) (3)); // 8
Names - Variables
A name is a string of characters used to identify some entity in a program. Variable names
are the most common names in the programs.
- Are names case sensitive?
- Length?
- etc...
Names with special characters:
PHP
: All variable names must begin with dollar signsPerl
: All variable names begin with special characters, which specify the variable's typeRuby
: Variable names that begin with@
are instance variables; those that begin with@@
are class variables
Case sensitivity names:
- Names in the
C-based
languages are case sensitive. Not in others languages.
Variables
A variable is an abstraction of a memory cell.
Variables can be characterized as a sextuplet (six parts) of attributes:
- Name
- Address
- Value
- Type
- Lifetime
- Scope
Address: The memory address with which it is associated.
- A variable may have different addresses at different times during execution.
- A variable may have different addresses at different places in a program.
- If two variable names can be used to access the same memory location, they are called aliases.
- Aliases are created via pointers, reference variables,
C
andC++
unions - Two pointer variables are aliases when they point to the same memory location. The same is true for reference variables.
- Aliases are harmful to readability (program readers must remember all of them).
Type: Determines the range of values of variables and the set of operations that are defined for values of that type; in the case of floating point, type also determines the precision
For example, the int type in Java specifies a value range of -2147483648 to 2147483647
Value: The value of a variable is the contents of the memory cell or cells associated with the variable:
- The l-value of a variable is its address
- The r-value of a variable is its value
Binding
A binding is an association between an entity and an attribute, such as between a variable and its type or value, or between an operation and a symbol.
Binding time is the time at which a binding takes place. Bindings can take place at:
- Language design time
- Language implementation time
- Compile time
- Load time
- Link time
- Run time
For example:
- The asterisk symbol (*) is usually bound to the multiplication operation at language design time. At compile time, a variable in a Java program is bound to a particular data type.
- Language design time: Bind operator symbols to operations
- Language implementation time: Bind floating point type to a representation
- Compile time: Bind a variable to a type in
C
orJava
- Load time: Bind a
C
orC++
static variable
to a memory cell - Runtime: Bind a
nonstatic local variable
to a memory cell
Static vs Dynamic Binding
https://techdifferences.com/difference-between-static-and-dynamic-binding.html
A binding is static if it first occurs before run time and remains unchanged throughout program execution.
A binding is dynamic if it first occurs during execution or can change during execution of the program.
Static vs Dynamic Binding in Java
https://www.geeksforgeeks.org/static-vs-dynamic-binding-in-java/
Static Binding: The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time .
Why binding of static, final and private methods is always a static binding?
Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. Let’s see by an example:
public class NewClass
{
public static class superclass
{
static void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass
{
static void print()
{
System.out.println("print in subclass.");
}
}
public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}
Output:
print in superclass. print in superclass.
As you can see, in both cases print method of superclass
is called. Lets see how this happens:
- We have created one object of
subclass
and one object ofsuperclass
with the reference of thesuperclass
. - Since the
print
method ofsuperclass
isstatic
, compiler knows that it will not be overridden insubclasses
and hence compiler knows during compile time which print method to call and hence no ambiguity.
As an exercise, reader can change the reference of object B to subclass and then check the output.
Dynamic Binding: In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have same method . Let’s see by an example:
public class NewClass
{
public static class superclass
{
void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass
{
@Override
void print()
{
System.out.println("print in subclass.");
}
}
public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}
Output:
print in superclass. print in subclass.
Here the output differs. But why? Let’s break down the code and understand it thoroughly.
- Methods are not static in this code.
- During compilation, the compiler has no idea as to which
print
has to be called since compiler goes only by referencing variable not by type of object and therefore the binding would be delayed toruntime
and therefore the corresponding version of print will be called based on type on object.
Important Points
- Private, final and static members (methods and variables) use static binding while for virtual methods (In Java methods are virtual by default) binding is done during run time based upon run time object.
- Static binding uses Type information for binding while Dynamic binding uses Objects to resolve binding.
- Overloaded methods are resolved (deciding which method to be called when there are multiple methods with same name) using static binding while overridden methods using dynamic binding, i.e, at run time.
Object-Oriented Paradigm
Overriding
https://www.techopedia.com/definition/24010/overriding
Overriding is an object-oriented programming feature that enables a child class to provide different implementation for a method that is already defined and/or implemented in its parent class or one of its parent classes. The overriden method in the child class should have the same name, signature, and parameters as the one in its parent class.
Overriding enables handling different data types through a uniform interface. Hence, a generic method could be defined in the parent class, while each child class provides its specific implementation for this method.
C++ Inheritance
https://www.w3schools.com/cpp/cpp_inheritance.asp
https://www.tutorialspoint.com/cplusplus/cpp_interfaces.htm
Reflection
A programming language that supports reflection allows its programs to have runtime access to their types and structure and to be able to dynamically modify their behavior
- The types and structure of a program are called
metadata
- The process of a program examining its metadata is called
introspection
- Interceding in the execution of a program is called
intercession
Uses of reflection for software tools:
- Class browsers need to enumerate the classes of a program
- Visual IDEs use type information to assist the developer in building type correct code
- Debuggers need to examine private fields and methods of classes
- Test systems need to know all of the methods of a class
Downsides of Reflection:
- Performance costs
- Exposes private fields and methods
- Voids the advantages of early type checking
- Some reflection code may not run under a security manager, making code nonportable
Reflection in Java
- Limited support from
java.lang.Class
- Java runtime instantiates an instance of
Class
for each object in the program
- The
getClass
method ofClass
returns theClass
object of an object
float[] totals = new float[100];
Class fltlist = totals.getClass();
Class stg = "hello".getClass();
- If there is no object, use class field:
Class stg = String.class;
- Class has four useful methods:
getMethod
searches for a specific public method of a classgetMethods
returns an array of all public methods of a classgetDeclaredMethod
searches for a specific method of a classgetDeclaredMethods
returns an array of all methods of a class- The
Method
class defines the invoke method, which is used to execute the method found bygetMethod
Some tutorials
Examples from Introduction to Programming Using Python 3
http://www.cs.armstrong.edu/liang/py/ExampleByChapters.html
C++ tutorial
http://www.cplusplus.com/doc/tutorial/program_structure/