Difference between revisions of "Multi-Paradigm Programming and Scripting"

From Sinfronteras
Jump to: navigation, search
(Imperative versus declarative code)
(Scripting)
 
(63 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
'''Timeline of the most popular programming languages since 1965 to 2019:''' https://www.youtube.com/watch?v=Og847HVwRSI
 +
 
[[:File:Some_important_programming_concepts.pdf]]
 
[[:File:Some_important_programming_concepts.pdf]]
  
Line 54: Line 56:
  
 
<br />
 
<br />
==Some important programming concepts==
+
==High level - Low Level Languages==
 
 
 
 
<br />
 
===High level - Low Level Programming===
 
  
  
 
<br />
 
<br />
===Compilation vs Interpretation===
+
==Compiled vs Interpreted languages==
 
https://medium.com/@DHGorman/a-crash-course-in-interpreted-vs-compiled-languages-5531978930b6
 
https://medium.com/@DHGorman/a-crash-course-in-interpreted-vs-compiled-languages-5531978930b6
  
Line 73: Line 71:
  
  
The alternative to using a <code>'''compiler'''</code> (for a compiled language) is using an <code>'''interpreter'''</code> (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.
+
The alternative to using a <code>'''compiler'''</code> (for a compiled language) is using an <code>'''interpreter'''</code> (for interpreted languages). '''Interpreted languages''' are 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.
 +
 
  
 
<code>'''Interpreters'''</code> will run through a program line by line and execute each command.
 
<code>'''Interpreters'''</code> will run through a program line by line and execute each command.
Line 79: Line 78:
  
 
<br />
 
<br />
====Advantages and Disadvantages====
+
===Advantages and Disadvantages===
 
'''Compiled Languages:'''
 
'''Compiled Languages:'''
  
 
*Advantages:
 
*Advantages:
 
+
:*Programs compiled into native code are faster than those translated at run time, due to the overhead of the translation process.
:*Programs compiled into native code usually tend to be faster than those translated at run time, due to the overhead of the translation process.
 
  
 
*Disadvantages:
 
*Disadvantages:
 
+
:*The compilation code usually will only be able to run in the platform where the program was compiled. This is solved in Java by the implementation of the Java Virtual Machine.
:*The compile code usually Platform dependence of the generated binary code.
 
  
  
Line 94: Line 91:
  
 
*Advantages:
 
*Advantages:
 
+
:*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. Other features include dynamic typing, and smaller executable program size.
:*Greater flexibility
+
:*Better diagnostics (error messages).
:*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:
 
*Disadvantages:
 
+
:*The most notable disadvantage is the execution speed, which is less compared to compiled languages.
:*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.
 
:::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.
  
Line 107: Line 101:
 
<br />
 
<br />
  
====Phases of Compilation====
+
===Phases of Compilation===
[[File:Phases of compilation.png|950px|thumb|center|]]
+
Compiler operates in various phases each phase transforms the source program from one representation to another. Every phase takes inputs from its previous stage and feeds its output to the next phase of the compiler. https://www.guru99.com/compiler-design-phases-of-compiler.html
  
  
*'''Scanning:'''
+
[[File:Phases_of_Compilation2.png|950px|thumb|center|Phases of Compilation: https://www.guru99.com/compiler-design-phases-of-compiler.html]]
  
*'''Parsing:'''
 
  
*'''Semantic analysis:'''
+
[[File:Phases of compilation.png|1200px|thumb|center|Phases of Compilations]]
  
*'''Intermediate form :'''
 
  
*'''Optimization:'''
+
* '''Lexical analysis''':
 +
* '''Syntax analysis''':
 +
* '''Semantic analysis''':
 +
* '''Intermediate code generator''':
 +
* '''Code optimizer''':
 +
* '''Code generator''':
  
*'''Code generation phase :'''
 
  
 +
<br />
  
<br />
+
==Subprogram - Subroutine - Procedure - Function - Method - etc==
 +
In computer programming, a <code>'''Subprograms'''</code> is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
 +
 
 +
In different programming languages, a subroutine may be called a procedure, a function, a routine, a method, or a subprogram. https://en.wikipedia.org/wiki/Subroutine
 +
 
 +
 
 +
Luego de revisar varias referencias. No creo que haya diferencias claras entre estos términos. Hay diferencias dependiendo del lenguaje de programación. Sólo he encontrado una diferencia que parece ser mencionada en varias fuentes:
 +
* '''Functions return values and procedures do not'''. Sin embargo, no todas las fuentes concuerdan con esto. See this source: https://softwareengineering.stackexchange.com/questions/20909/method-vs-function-vs-procedure
 +
 
 +
 
 +
You might say a function returns a value. Well, the following C function doesn't return a value:
  
===Procedural - Functional and Object-Oriented Programming===
+
void f() { return; }
https://medium.com/@sho.miyata.1/the-object-oriented-programming-vs-functional-programming-debate-in-a-beginner-friendly-nutshell-24fb6f8625cc
 
  
 +
...but I doubt you'd find anyone who would call it a procedure.
  
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
+
Sure, in Pascal, procedures don't return values and functions return values, but that's merely a reflection of how Pascal was designed. In Fortran, a function returns a value, and a subroutine returns multiple values. Yet none of this really allows us to come up with a "universal" definition for these terms.
  
 +
In fact, the term "procedural programming" refers to a whole class of languages, including C, Fortran and Pascal, only one of which actually uses the term "procedure" to mean anything.
  
https://www.codecademy.com/articles/cpp-object-oriented-programming
+
So none of this is really consistent.  
  
https://owlcation.com/stem/Use-Of-Object-Oriented-Programming
 
  
https://searchapparchitecture.techtarget.com/definition/object-oriented-programming-OOP
+
'''The only exception is probably <code>method</code>, which seems to be used almost entirely with OO Languages, referring to a function that is associated with an object.''' Although, even this is not always consistent. C++, for example, usually uses the term "member function" rather than method, (even though the term "method" has crept into the C++ vernacular among programmers.)
  
https://www.geeksforgeeks.org/object-oriented-programming-oops-concept-in-java/
 
  
http://ee402.eeng.dcu.ie/introduction/chapter-1---introduction-to-object-oriented-programming
+
'''The point is, none of this is really consistent. It simply reflects the terminology employed by whatever languages are en vogue at the time.'''
  
  
<br />
+
<span style="color:#FF0000">A real distinction is when we talk about a function in '''Functional programming'''. If you like to keep a function clean (just look at functional languages) you need to make sure a function does not have a side effect. However, in all the procedural or OOP languages we refer to functions that don't really meet the exact mathematical definition of a function that is used in Functional programming.</span> https://stackoverflow.com/questions/721090/what-is-the-difference-between-a-function-and-a-procedure/721107
====Subprogram - Procedure - Function - Method - etc====
 
  
  
 
<br />
 
<br />
=====Subprograms=====
 
<code>Subprograms</code> are the fundamental building blocks of programs and are therefore among the most important concepts in the programming language design.
 
  
 +
'''Subprogram header''' is the fist part of the definition including the name, the kind of subprogram, and the formal parameters.
  
<br />
+
'''The parameter profile (aka signature)''' of a subprogram is the <code>number</code>, <code>order</code> and <code>types</code> of its parameters.
  
*'''Subprogram header''' is the fist part of the definition including the name, the kind of subprogram, and the formal parameters.
+
'''The protocol''' is a subprogram parameter profile and, if it is a function, its return type.
*'''The parameter profile (aka signature)''' of a subprogram is the <code>number</code>, <code>order</code> and <code>types</code> of its parameters.
 
*'''The protocol''' is a subprogram parameter profile and, if it is a function, its return type.
 
  
  
 
<br />
 
<br />
'''There are tow categories of subprograms:'''
+
'''There are tow categories of subprograms:''' <span style="color:#FF0000">(This is from Muhammad slides. I have already explained what I found in my research about the difference between Procedures and Functions).</span>
  
*'''Procedures:''' are collection of statements that define parameterized computations.
+
*'''Procedures:''' Are collection of statements that define parameterized computations.
*'''Functions:''' structurally resemble procedures but are semantically modeled on mathematical functions.
+
*'''Functions:''' Structurally resemble procedures but are semantically modeled on mathematical functions.
  
  
Line 193: Line 195:
  
 
<br />
 
<br />
======Generic subprograms======
+
 
 +
==Generic subprograms==
 
A generic subprogram is one that takes parameters of different <code>types</code> on different activation.
 
A generic subprogram is one that takes parameters of different <code>types</code> on different activation.
  
Line 230: Line 233:
  
 
<br />
 
<br />
======Overloaded subprograms======
+
==Variables==
An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment. However, every version of an overloaded subprogram has a unique '''protocol'''.
+
A '''name''' is a string of characters used to identify some entity in a program. <code>Variable names</code> are the most common names in the programs.
 
 
<code>C++</code>, <code>Java</code>, <code>C#</code>, and <code>Ada</code> include predefined overloaded subprograms. They allow users to write multiple versions of subprograms with the same name and different '''protocols'''. In <code>Ada</code>, the return type of an overloaded function can be used to disambiguate calls (thus two overloaded functions can have the same parameters)
 
 
 
 
 
<br />
 
======Recursion======
 
https://www.python-course.eu/recursive_functions.php
 
 
 
https://www.geeksforgeeks.org/recursion/
 
 
 
 
 
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
 
 
 
 
 
<span style="background:#E6E6FA; color:red">'''A VERY VERY NICE example of recursion is the factorial function:'''</span>
 
<syntaxhighlight lang="python3">
 
Example:
 
4! = 4 * 3!
 
3! = 3 * 2!
 
2! = 2 * 1
 
Replacing the calculated values gives us the following expression
 
4! = 4 * 3 * 2 * 1
 
</syntaxhighlight>
 
 
 
 
 
<syntaxhighlight lang="python3">
 
def factorial(n):
 
    if n == 1:
 
        return 1
 
    else:
 
        return n * factorial(n-1)
 
</syntaxhighlight>
 
 
 
 
 
<br />
 
 
 
====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 <code>object</code>'''. 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.
 
 
 
 
 
<br />
 
 
 
===Languages evaluation criteria===
 
https://www.cs.scranton.edu/~mccloske/courses/cmps344/sebesta_chap1.html
 
 
 
<br />
 
 
 
{| class="wikitable" style="text-align:left; vertical-align:top;"
 
|- style="text-align:left"
 
! style="text-align:left" |'''Readability'''
 
! style="text-align:left" |'''Writability'''
 
! style="text-align:left" |'''Reliability'''
 
! style="text-align:left" |'''Cost'''
 
! style="text-align:left" |'''Other criteria'''
 
|- style="vertical-align:top;"
 
|
 
This refers to the ease with which programs (in the language under consideration) can be understood. This is especially important for software maintenance.
 
 
 
*Simplicity:
 
*Orthogonality:
 
*Data Types:
 
*Syntax Design:
 
 
 
|
 
This is a measure of how easily a language can be used to develop programs for a chosen problem domain.
 
 
 
*Simplicity and Orthogonality:
 
*Support for Abstraction:
 
*Expressivity:
 
 
 
|
 
This is the property of performing to specifications under all conditions.
 
 
 
*Type Checking:
 
*Aliasing:
 
 
 
|
 
The following contribute to the cost of using a particular language:
 
 
 
*Training programmers: cost is a function of simplicity of language
 
*Writing and maintaining programs: cost is a function of readability and writability.
 
*Compiling programs: for very large systems, this can take a significant amount of time.
 
*Executing programs: Having to do type checking and/or index-boundary checking at run-time is expensive. There is a tradeoff between this item and the previous one (compilation cost), because optimizing compilers take more time to work but yield programs that run more quickly.
 
*Language Implementation System: e.g., Java is free, Ada not
 
*Lack of reliability: software failure could be expensive (e.g., loss of business, liability issues)
 
 
 
|
 
*Portability: the ease with which programs that work on one platform can be modified to work on another. This is strongly influenced by to what degree a language is standardized.
 
*Generality: Applicability to a wide range of applications.
 
*Well-definedness: Completeness and precision of the language's official definition.
 
 
 
|}
 
 
 
 
 
<br />
 
 
 
===Names - Variables===
 
A name is a string of characters used to identify some entity in a program. <code>Variable names</code> are the most common names in the programs.
 
  
 
*Are names case sensitive?
 
*Are names case sensitive?
Line 387: Line 254:
  
 
<br />
 
<br />
====Variables====
+
===Variables===
 
A variable is an abstraction of a memory cell.
 
A variable is an abstraction of a memory cell.
  
Line 422: Line 289:
  
 
<br />
 
<br />
===Binding===
+
==Data type==
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 <code>C</code> or <code>Java</code>
 
*'''Load time:''' Bind a <code>C</code> or <code>C++</code> <code>static variable</code> to a memory cell
 
*'''Runtime:''' Bind a <code>nonstatic local variable</code> to a memory cell
 
 
 
 
 
<br />
 
====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.
 
 
 
 
 
<br />
 
=====Static vs Dynamic Binding in Java=====
 
https://www.geeksforgeeks.org/static-vs-dynamic-binding-in-java/
 
 
 
 
 
<br />
 
'''Static Binding:'''
 
<blockquote>
 
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:
 
 
 
<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''':
 
<syntaxhighlight lang="shell">
 
print in superclass.
 
print in superclass.
 
</syntaxhighlight>
 
 
 
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.''
 
</blockquote>
 
 
 
 
 
<br />
 
'''Dynamic Binding:'''
 
<blockquote>
 
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:'''
 
<syntaxhighlight lang="shell">
 
print in superclass.
 
print in subclass.
 
</syntaxhighlight>
 
 
 
 
 
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.
 
</blockquote>
 
 
 
 
 
<br />
 
'''Important points'''
 
<blockquote>
 
*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.
 
</blockquote>
 
 
 
 
 
<br />
 
===Statically and Dynamically typed languages===
 
 
 
 
 
<br />
 
'''Statically typed languages:'''
 
 
 
A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (e.g.: <code>Java</code>, <code>C</code>, <code>C++</code>); other languages offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: <code>OCaml</code>, <code>Haskell</code>, <code>Scala</code>, <code>Kotlin</code>)
 
 
 
The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.
 
 
 
Examples: <code>C</code>, <code>C++</code>, <code>Java</code>, <code>Rust</code>, <code>Go</code>, <code>Scala</code>
 
 
 
 
 
<br />
 
'''Dynamically typed languages:'''
 
 
 
A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference).
 
 
 
Examples: <code>Perl</code>, <code>Ruby</code>, <code>Python</code>, <code>PHP</code>, <code>JavaScript</code>
 
 
 
<u>Most scripting languages have this feature as there is no compiler to do static type-checking</u> anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.
 
 
 
Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.
 
 
 
 
 
<br />
 
===Data type===
 
 
A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.
 
A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.
  
Line 760: Line 449:
 
|}
 
|}
  
 +
 +
<br />
 
===Pointer===
 
===Pointer===
 
Pointers store address of variables or a memory location.
 
Pointers store address of variables or a memory location.
Line 888: Line 579:
 
<br />
 
<br />
  
==Object-Oriented Paradigm==
+
==Recursion==
 +
https://www.python-course.eu/recursive_functions.php
  
 +
https://www.geeksforgeeks.org/recursion/
  
<br />
 
===Abstraction===
 
https://stackify.com/oop-concept-abstraction/
 
  
Abstraction is a key concept in programming. In particular, it is one of the 4 fundamental concepts of object-oriented programming (OOP) languages. Its main goal is to handle complexity by hiding unnecessary details from the user. That enables the user to implement more complex logic on top of the provided abstraction without understanding or even thinking about all the hidden complexity.
+
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
  
  
<br />
+
<span style="background:#E6E6FA; color:red">'''A VERY VERY NICE example of recursion is the factorial function:'''</span> https://www.geeksforgeeks.org/program-for-factorial-of-a-number/
====Abstraction in the real world====
+
<syntaxhighlight lang="python3">
<blockquote>
+
Example:
I'm a coffee addict. So, when I wake up in the morning, I go into my kitchen, switch on the coffee machine and make coffee. Sounds familiar?
+
4! = 4 * 3!
 +
3! = 3 * 2!
 +
2! = 2 * 1
 +
Replacing the calculated values gives us the following expression
 +
4! = 4 * 3 * 2 * 1
 +
</syntaxhighlight>
 +
 
  
Making coffee with a coffee machine is a good example of abstraction:
+
Iterative solution (Java):
 +
<syntaxhighlight lang="java">
 +
class Main{
 +
    static int factorial(int n){
 +
        int res = 1;
 +
        for (int i=2 ; i<=n ; i++)
 +
          res *= i;
 +
        return res;
 +
    }
 +
    public static void main(String[] args){
 +
        System.out.println(factorial(6));
 +
    }
 +
}
 +
</syntaxhighlight>
  
*You need to know how to use your coffee machine to make coffee.
 
  
::You need to provide water and coffee beans,
+
Recursive solution (Java):
::Switch the machine on,
+
<syntaxhighlight lang="java">
::Select the kind of coffee you want to get ...
+
class Main{
  
 +
    static int factorial(int n){
 +
        if (n == 0)
 +
          return 1;
 +
        return n*factorial(n-1);
 +
    }
  
*The thing you don't need to know is how the coffee machine is working internally to brew a fresh cup of delicious coffee:
+
    public static void main(String[] args){
 +
        System.out.println(factorial(5));
 +
    }
  
::You don't need to know how the coffee machine heat the water,
+
}
::You don't need to know the ideal temperature of the water,
+
</syntaxhighlight>
::Neither the amount of ground coffee you need to use.
 
  
  
Someone else worried about all these details and '''created a coffee machine that now acts as an abstraction of the coffee making process and hides all these details.''' You just interact with a simple interface that doesn't require any knowledge about the internal implementation.
+
One line Solution (Using Ternary operator) (Java):
 +
<syntaxhighlight lang="java">
 +
class Main{
 +
 
 +
int factorial(int n){
 +
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
 +
  }
  
 +
  public static void main(String args[]){
 +
    Main obj = new Main();
 +
    System.out.println(obj.factorial(6));
 +
  }
  
We can use the same concept in programming and specially in object-oriented programming languages...
+
}
 +
</syntaxhighlight>
  
  
Another good example of abstraction, is any Software or Application. Let's consider an Email Service Application (Gmail, for example)...
+
<br />
</blockquote>
+
==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.
  
  
<br>
+
'''Binding time''' is the time at which a binding takes place. Bindings can take place at:
====Abstraction in Programming====
 
<blockquote>
 
  
Abstraction is a concept much more easier than it seams to be. Every time that we create a <code>Function</code> or an <code>Object</code>, we are probably implementing abstraction. If this <code>Function</code> or <code>Object</code> can be re-used in another part of the code or even in another program to perform a particular task, our <code>Function</code> or <code>Object</code> will be acting as an abstraction of the task that is performing; just like the coffee machine of our previous example acts as an abstraction of the coffee making process by hiding all the complex details.
+
*Language design time
 +
*Language implementation time
 +
*Compile time
 +
*Load time
 +
*Link time
 +
*Run time
  
  
Two fundamental abstraction facilities:
+
For example:
  
*'''Process abstraction:'''
+
*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 <code>C</code> or <code>Java</code>
 +
*'''Load time:''' Bind a <code>C</code> or <code>C++</code> <code>static variable</code> to a memory cell
 +
*'''Runtime:''' Bind a <code>nonstatic local variable</code> to a memory cell
  
:Nearly all programming languages support process abstraction with subprograms (functions, for example)
 
  
*'''Data abstraction:'''
+
<br />
 +
===Static vs Dynamic Binding===
 +
https://techdifferences.com/difference-between-static-and-dynamic-binding.html
  
:Nearly all programming languages designed since 1980 support data abstraction (objects).
 
  
 +
A '''binding''' is '''static''' if it first occurs before run time and remains unchanged throughout program execution.
  
</blockquote>
 
  
 +
A '''binding''' is '''dynamic''' if it first occurs during execution or can change during execution of the program.
  
<br>
 
=====Abstraction in OOP=====
 
<blockquote>
 
Objects in an OOP language provide an abstraction that hides the internal implementation details. Similar to the coffee machine in your kitchen, you just need to know which methods of the object are available to call and which input parameters are needed to trigger a specific operation. But you don't need to understand how this method is implemented and which kinds of actions it has to perform to create the expected result.
 
  
Let's implement the coffee machine example in Java. You do the same in any other object-oriented programming language. The syntax might be a little bit different, but the general concept is the same.
+
<br />
 +
====Static vs Dynamic Binding in Java====
 +
https://www.geeksforgeeks.org/static-vs-dynamic-binding-in-java/
  
  
 
<br />
 
<br />
======Abstract methods and classes in Java======
+
'''Static Binding:'''
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
+
<blockquote>
 +
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 .
  
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
 
  
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
+
'''Why binding of static, final and private methods is always a static binding?'''
  
abstract void moveTo(double deltaX, double deltaY);
+
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:
  
If a class includes abstract methods, then the class itself must be declared abstract, as in:
+
<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>
  
<syntaxhighlight lang="java">
+
'''Output''':
public abstract class GraphicObject {
+
<syntaxhighlight lang="shell">
  // declare fields
+
print in superclass.
  // declare nonabstract methods
+
print in superclass.
  abstract void draw();
 
}
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
+
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.
  
<br />
+
''As an exercise, reader can change the reference of object B to subclass and then check the output.''
======Interfaces in Java======
+
</blockquote>
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
 
  
  
 
<br />
 
<br />
======Abstract Classes Compared to Interfaces======
+
'''Dynamic Binding:'''
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
+
<blockquote>
 +
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:'''
 +
<syntaxhighlight lang="shell">
 +
print in superclass.
 +
print in subclass.
 +
</syntaxhighlight>
  
<br />
 
======Abstraction code example - Use abstraction to implement a coffee machine======
 
  
 +
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.
 
</blockquote>
 
</blockquote>
  
  
 
<br />
 
<br />
===Inheritance===
+
'''Important points'''
Inheritance can be defined as the process where one class acquires the properties and behavior (methods and fields) of another class.
+
<blockquote>
 +
*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.
 +
</blockquote>
  
Inheritance enables code reusability as well as adding new features to the existing code.
 
  
*'''superclass''' (base class, parent class): The class whose properties are inherited.
+
<br />
*'''subclass''' (derived class, child class): The class which inherits the properties of other.
+
==Statically and Dynamically typed languages==
  
  
 
<br />
 
<br />
====Types of inheritance====
+
'''Statically typed languages:'''
[[File:types_of_inheritance.png|700px|thumb|center|Types of inheritance]]
 
  
 +
A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (e.g.: <code>Java</code>, <code>C</code>, <code>C++</code>); other languages offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: <code>OCaml</code>, <code>Haskell</code>, <code>Scala</code>, <code>Kotlin</code>)
  
'''Single inheritance''' enables a derived class to inherit properties and behavior from only a single parent class.
+
The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.
  
 +
Examples: <code>C</code>, <code>C++</code>, <code>Java</code>, <code>Rust</code>, <code>Go</code>, <code>Scala</code>
  
'''Multiple inheritance''' enables a class can inherit characteristics and features from more than one parent class.
 
  
 +
<br />
 +
'''Dynamically typed languages:'''
  
A very important fact to remember is that Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:
+
A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference).
  
<syntaxhighlight lang="java">
+
Examples: <code>Perl</code>, <code>Ruby</code>, <code>Python</code>, <code>PHP</code>, <code>JavaScript</code>
public class extends Animal, Mammal{} // Illegal in Java
 
</syntaxhighlight>
 
  
 +
<u>Most scripting languages have this feature as there is no compiler to do static type-checking</u> anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.
  
However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance.
+
Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.
  
  
 
<br />
 
<br />
 +
==Reflection==
 +
http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example
  
====Inheritance in Java====
+
https://docs.oracle.com/javase/tutorial/reflect/index.html
  
  
<br />
+
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.
=====Extends keyword=====
 
'''extends''' is the keyword used to inherit the properties of a class. With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
 
  
Example:
 
<syntaxhighlight lang="java">
 
class Super{
 
    ...
 
    ...
 
}
 
  
 +
*The types and structure of a program are called <code>'''metadata'''</code>
  
class Sub extends Super{
+
*The process of a program examining its metadata is called <code>'''introspection'''</code>
    ...
 
    ...
 
}
 
</syntaxhighlight>
 
  
 +
*Interceding in the execution of a program is called <code>'''intercession'''</code>
  
Calculation.java
 
<syntaxhighlight lang="java">
 
package calculation;
 
  
class Calculation {
+
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example
    int z;
 
   
 
    public void addition(int x, int y){
 
        z=x+y;
 
        System.out.println("The sum of the given numbers:"+z);
 
    }
 
   
 
    public void substraction(int x,int y){
 
        z=x-y;
 
        System.out.println("The difference between the given numbers:"+z);
 
    }
 
}
 
</syntaxhighlight>
 
  
  
MyCalculation.java
+
'''Uses of reflection for software tools:'''
<syntaxhighlight lang="java">
 
package calculation;
 
  
public class MyCalculation extends Calculation{
+
*Class browsers need to enumerate the classes of a program
   
+
*Visual IDEs use type information to assist the developer in building type correct code
    public void multiplication(int x, int y){
+
*Debuggers need to examine private fields and methods of  classes
        z = x*y;
+
*Test systems need to know all of the methods of a class
        System.out.println("The product of the given numbers is: "+z);
 
    }
 
   
 
    public static void main(String args[]){
 
        int a=20, b=10;
 
        MyCalculation demo = new MyCalculation();
 
        demo.addition(a,b);
 
        demo.substraction(a, b);
 
        demo.multiplication(a, b);
 
    }
 
}
 
</syntaxhighlight>
 
  
  
Using '''extends''' keyword, My_Calculation inherits the methods addition() and Subtraction() from Calculation class.
+
'''Downsides of Reflection:'''
  
You can instantiate the class as given below as well. But using the superclass reference variable ( cal in this case ) you cannot call the method multiplication(), which belongs to the subclass My_Calculation:
+
*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 non-portable
  
  
<syntaxhighlight lang="java">
+
<br />
Calculation cal = new My_Calculation();
+
===Reflection in Java===
demo.addition(a, b);
 
demo.Subtraction(a, b);
 
</syntaxhighlight>
 
  
 +
*Limited support from <code>java.lang.Class</code>
  
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
+
*Java runtime instantiates an instance of <code>Class</code> for each object in the program
  
 +
*The <code>getClass</code> method of <code>Class</code> returns the <code>Class</code> object of an object
  
<br />
+
::<code>float[] totals = new float[100];</code>
=====The super keyword=====
+
::<code>Class fltlist = totals.getClass();</code>
The super keyword is similar to this keyword. The following are the scenarios where the super keyword is used.
+
::<code>Class stg = "hello".getClass();</code>
  
*It is used to differentiate the members of superclass from the members of subclass, if they have same names.
+
*If there is no object, use class field:
*It is used to invoke the superclass constructor from subclass.
 
  
 +
::<code>Class stg = String.class;</code>
  
<br />
+
*'''Class has four useful methods:'''
======Differentiating the members======
 
If a class is inheriting the properties of another class, and if the members of the superclass have the same names as the sub class, to differentiate these variables we use super keyword as shown below.
 
<syntaxhighlight lang="java">
 
super.variable
 
super.method();
 
</syntaxhighlight>
 
  
 
+
::<code>getMethod</code> searches for a specific public method of a class
'''Sample Code'''
+
::<code>getMethods</code> returns an array of all public methods of a class
 
+
::<code>getDeclaredMethod</code> searches for a specific method of a class
In the given program you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values.
+
::<code>getDeclaredMethods</code> returns an array of all methods of a class
 +
::The <code>Method</code> class defines the invoke method, which is used to execute the method found by <code>getMethod</code>
  
  
 +
Here is a quick Java Reflection example to show you what using reflection looks like:
 
<syntaxhighlight lang="java">
 
<syntaxhighlight lang="java">
package btest2_the_super_keyword;
+
Method[] methods = MyObject.class.getMethods();
  
class Super_class{
+
for(Method method : methods){
    int num=20;
+
    System.out.println("method = " + method.getName());
 
 
    //display method of superclass
 
    public void display(){
 
        System.out.println("This is the display method of superclass");
 
    }
 
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names. http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example
  
<syntaxhighlight lang="java">
 
package btest2_the_super_keyword;
 
  
public class Sub_class extends Super_class {
+
<br />
    int num=10;
+
==Languages evaluation criteria==
   
+
https://www.cs.scranton.edu/~mccloske/courses/cmps344/sebesta_chap1.html
    //display method of sub class
 
    public void display(){
 
        System.out.println("This is the display method of subclass");
 
    }
 
   
 
    public void my_method(){
 
        //Instantiating subclass
 
        Sub_class sub=new Sub_class();
 
       
 
        //Invoking the display() method of sub class
 
        sub.display();
 
       
 
        //Invoking the display() method of superclass
 
        super.display();
 
       
 
        //printing the value of variable num of subclass
 
        System.out.println("value of the variable named num in sub class:"+ sub.num);
 
       
 
        //printing the value of variable num of superclass
 
        System.out.println("value of the variable named num in super class:"+ super.num);
 
       
 
    }
 
  
    public static void main(String args[]){
+
https://medium.com/@thisisfordeveloper/programming-language-evaluation-criteria-part-2-writability-reliability-cost-6c3029c9d957
        Sub_class obj = new Sub_class();
 
        obj.my_method();
 
    }
 
   
 
}
 
</syntaxhighlight>
 
  
  
 
<br />
 
<br />
======Invoking Superclass constructor======
 
If a class is inheriting the properties of another class, <span style="background:#00FF00">the subclass automatically acquires the default constructor of the super class</span>. But if you want to call a parameterized constructor of the super class, you need to use the super keyword as shown below.
 
  
 +
{| class="wikitable" style="text-align:left; vertical-align:top;"
 +
|- style="text-align:left"
 +
! style="text-align:left" |'''Readability'''
 +
! style="text-align:left" |'''Writability'''
 +
! style="text-align:left" |'''Reliability'''
 +
! style="text-align:left" |'''Cost'''
 +
! style="text-align:left" |'''Other criteria'''
 +
|- style="vertical-align:top;"
 +
|
 +
This refers to the ease with which programs (in the language under consideration) can be understood. This is especially important for software maintenance.
  
<syntaxhighlight lang="java">
+
*Simplicity:
super(values);
+
*Orthogonality:
</syntaxhighlight>
+
*Data Types:
 +
*Syntax Design:
  
<syntaxhighlight lang="java">
+
|
class SuperClass{
+
This is a measure of how easily a language can be used to develop programs for a chosen problem domain.
   
 
    int age;
 
   
 
    SuperClass(int age){
 
        this.age=age;
 
    }
 
   
 
    public void getAge(){
 
        System.out.println("The value of the variable named age in super class is: " +age);
 
    }
 
}
 
</syntaxhighlight>
 
  
 +
*Simplicity and Orthogonality:
 +
*Support for Abstraction:
 +
*Expressivity:
  
<syntaxhighlight lang="java">
+
|
public class SubClass extends SuperClass {
+
This is the property of performing to specifications under all conditions.
   
 
    SubClass(int age){
 
        super(age);
 
    }
 
   
 
    public static void main(String argd[]){
 
        SubClass s = new SubClass(24);
 
        s.getAge();
 
    }
 
   
 
}
 
</syntaxhighlight>
 
  
 +
*Type Checking:
 +
*Aliasing:
  
<br />
+
|
 +
The following contribute to the cost of using a particular language:
  
===Overriding===
+
*Training programmers: cost is a function of simplicity of language
https://www.techopedia.com/definition/24010/overriding
+
*Writing and maintaining programs: cost is a function of readability and writability.
 +
*Compiling programs: for very large systems, this can take a significant amount of time.
 +
*Executing programs: Having to do type checking and/or index-boundary checking at run-time is expensive. There is a tradeoff between this item and the previous one (compilation cost), because optimizing compilers take more time to work but yield programs that run more quickly.
 +
*Language Implementation System: e.g., Java is free, Ada not
 +
*Lack of reliability: software failure could be expensive (e.g., loss of business, liability issues)
  
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.
+
|
 +
*Portability: the ease with which programs that work on one platform can be modified to work on another. This is strongly influenced by to what degree a language is standardized.
 +
*Generality: Applicability to a wide range of applications.
 +
*Well-definedness: Completeness and precision of the language's official definition.
  
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.
+
|}
  
  
 
<br />
 
<br />
===C++ Inheritance===
+
==Some programming paradigms==
https://www.w3schools.com/cpp/cpp_inheritance.asp
 
  
https://www.tutorialspoint.com/cplusplus/cpp_interfaces.htm
 
  
 +
<br />
 +
===Imperative vs Declarative programming paradigm===
 +
https://medium.com/front-end-weekly/imperative-versus-declarative-code-whats-the-difference-adc7dd6c8380
  
<br />
+
https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2
===Reflection===
 
http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example
 
  
https://docs.oracle.com/javase/tutorial/reflect/index.html
 
  
 +
* '''Imperative programming style:'''
 +
:* Focused on describe '''HOW''' the computer should accomplish the task.
  
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.
+
:* A more formal definition: Imperative programming is a programming paradigm that uses statements that change a program's state.
 +
::: 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.
  
 +
:* '''Procedural''' and '''object-oriented programming''' belong under imperative paradigm: <code>C</code>, <code>C++</code>, <code>C#</code>, <code>PHP</code>, <code>Java</code> and of course <code>Assembly</code>.
  
*The types and structure of a program are called <code>'''metadata'''</code>
+
:* Example of imperative code in JavaScript:
 +
::<syntaxhighlight lang="js">
 +
class Number {
  
*The process of a program examining its metadata is called <code>'''introspection'''</code>
+
    constructor (number = 0) {
 +
        this.number = number;
 +
    }
 +
 
 +
    add (x) {
 +
        this.number = this.number + x;
 +
    }
 +
   
 +
}
  
*Interceding in the execution of a program is called <code>'''intercession'''</code>
+
const myNumber = new Number (5);
 +
myNumber.add (3);
 +
console.log (myNumber.number); // 8
 +
</syntaxhighlight>
  
  
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example
+
<br />
  
 +
* '''Declarative programming style:'''
 +
:* Focused on describe '''WHAT''' the computer should accomplish.
  
'''Uses of reflection for software tools:'''
+
:* A more formal definition: Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow:
 +
::: Declarative code focuses on building logic of software without actually describing its flow. You are saying '''WHAT TO DO WITHOUT ADDING HOW'''. For example with HTML you use <code><img src="./image.jpg" /></code> to tell browser to display an image and you don’t care how it does that.
  
*Class browsers need to enumerate the classes of a program
+
:* '''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: <code>HTML</code>, <code>XML</code>, <code>CSS</code>, <code>SQL</code>, <code>Prolog</code>, <code>Haskell</code>, <code>F#</code> and <code>Lisp</code>.
*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
 
  
 +
:* Example of declarative code in JavaScript:
 +
::<syntaxhighlight lang="js">
 +
const sum = a => b => a + b;
 +
console.log (sum (5) (3)); // 8
 +
</syntaxhighlight>
  
'''Downsides of Reflection:'''
 
  
*Performance costs
+
<br />
*Exposes private fields and methods
 
*Voids the advantages of early type checking
 
*Some reflection code may not run under a security manager, making code non-portable
 
  
 +
===Procedural programming paradigm===
  
 
<br />
 
<br />
====Reflection in Java====
+
====Procedural vs Functional vs Object-Oriented Programming====
 +
https://medium.com/@sho.miyata.1/the-object-oriented-programming-vs-functional-programming-debate-in-a-beginner-friendly-nutshell-24fb6f8625cc
  
*Limited support from <code>java.lang.Class</code>
 
  
*Java runtime instantiates an instance of <code>Class</code> for each object in the program
+
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
 +
 
  
*The <code>getClass</code> method of <code>Class</code> returns the <code>Class</code> object of an object
+
https://www.codecademy.com/articles/cpp-object-oriented-programming
  
::<code>float[] totals = new float[100];</code>
+
https://owlcation.com/stem/Use-Of-Object-Oriented-Programming
::<code>Class fltlist = totals.getClass();</code>
 
::<code>Class stg = "hello".getClass();</code>
 
  
*If there is no object, use class field:
+
https://searchapparchitecture.techtarget.com/definition/object-oriented-programming-OOP
  
::<code>Class stg = String.class;</code>
+
https://www.geeksforgeeks.org/object-oriented-programming-oops-concept-in-java/
  
*'''Class has four useful methods:'''
+
http://ee402.eeng.dcu.ie/introduction/chapter-1---introduction-to-object-oriented-programming
  
::<code>getMethod</code> searches for a specific public method of a class
 
::<code>getMethods</code> returns an array of all public methods of a class
 
::<code>getDeclaredMethod</code> searches for a specific method of a class
 
::<code>getDeclaredMethods</code> returns an array of all methods of a class
 
::The <code>Method</code> class defines the invoke method, which is used to execute the method found by <code>getMethod</code>
 
  
 +
<br />
  
Here is a quick Java Reflection example to show you what using reflection looks like:
+
===[[Object-Oriented Concepts and Constructs|Object-Oriented Paradigm]]===
<syntaxhighlight lang="java">
 
Method[] methods = MyObject.class.getMethods();
 
  
for(Method method : methods){
 
    System.out.println("method = " + method.getName());
 
}
 
</syntaxhighlight>
 
  
This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names. http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example
+
<br />
 +
===Functional Programming===
  
  
 
<br />
 
<br />
==Scripting==
+
===Scripting===
 
https://www.geeksforgeeks.org/whats-the-difference-between-scripting-and-programming-languages/
 
https://www.geeksforgeeks.org/whats-the-difference-between-scripting-and-programming-languages/
  
A scripting language is a programming language designed for integrating and communicating with other  programming  languages. Some of the most widely used scripting languages are JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl.
+
Basically, all scripting languages are programming languages. One of the clearest differences between the two is that scripting languages do not require the compilation step and are rather interpreted.
 
 
Basically, all scripting languages are programming languages. The theoretical difference between the two is that scripting languages do not require the compilation step and are rather interpreted.
 
  
  
<br />
+
https://www.pcmag.com/encyclopedia/term/scripting-language
  
==Some tutorials==
+
http://pages.di.unipi.it/corradini/Didattica/AP-19/DOCS/Scott-ch13.pdf
 
 
 
 
<br />
 
===Examples from Introduction to Programming Using Python 3===
 
http://www.cs.armstrong.edu/liang/py/ExampleByChapters.html
 
  
  
 
<br />
 
<br />
===C++ tutorial===
+
====[[Shell Scripting]]====
http://www.cplusplus.com/doc/tutorial/program_structure/
 
  
  
 
<br />
 
<br />

Latest revision as of 19:04, 25 May 2020

Timeline of the most popular programming languages since 1965 to 2019: https://www.youtube.com/watch?v=Og847HVwRSI

File:Some_important_programming_concepts.pdf



Why Multi-Paradigm Programming and Scripting?
  • Universal programming constructs (invariant of language), their functions, uses and how different paradigms/languages employ them.
  • Improved background for choosing appropriate languages:



Content of this course
Programming Constructs:
  • The compilation process
  • Data types (strongly-typed, weakly-typed)
  • Pointers
  • Variables and Invariants
  • Conditionals (Selection)
  • Sequence
  • Repetition
  • Routines
  • Concurrency
Programming Paradigms & Languages:
  • Abstraction (machine to very-high-level)
  • Mark-up
  • Imperative & Declarative
  • Procedural
  • Parallel & Concurrent
  • Functional
  • Event-Driven
  • Multi-Paradigm Languages
  • Interpreted Languages
  • Comparison of all to Object Oriented Paradigm
Scripting:
  • Interpreters and system commands
  • Shell Scripting (Linux/UNIX)
  • PowerShell Scripting (Windows)
  • System Programming & Scripting
Applications of Shell Scripting:
  • Job Control
  • Glue Code / Wrappers
  • Automating Tasks
  • Data Processing / Transformation
  • System uses
  • I/O tasks and functions



High level - Low Level Languages


Compiled vs Interpreted languages

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 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 are faster than those translated at run time, due to the overhead of the translation process.
  • Disadvantages:
  • The compilation code usually will only be able to run in the platform where the program was compiled. This is solved in Java by the implementation of the Java Virtual Machine.


Interpreted Languages:

  • Advantages:
  • 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. Other features include dynamic typing, and smaller executable program size.
  • Better diagnostics (error messages).
  • Disadvantages:
  • The most notable disadvantage is the execution speed, which is less 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

Compiler operates in various phases each phase transforms the source program from one representation to another. Every phase takes inputs from its previous stage and feeds its output to the next phase of the compiler. https://www.guru99.com/compiler-design-phases-of-compiler.html



Phases of Compilations


  • Lexical analysis:
  • Syntax analysis:
  • Semantic analysis:
  • Intermediate code generator:
  • Code optimizer:
  • Code generator:



Subprogram - Subroutine - Procedure - Function - Method - etc

In computer programming, a Subprograms is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.

In different programming languages, a subroutine may be called a procedure, a function, a routine, a method, or a subprogram. https://en.wikipedia.org/wiki/Subroutine


Luego de revisar varias referencias. No creo que haya diferencias claras entre estos términos. Hay diferencias dependiendo del lenguaje de programación. Sólo he encontrado una diferencia que parece ser mencionada en varias fuentes:


You might say a function returns a value. Well, the following C function doesn't return a value:

void f() { return; }

...but I doubt you'd find anyone who would call it a procedure.

Sure, in Pascal, procedures don't return values and functions return values, but that's merely a reflection of how Pascal was designed. In Fortran, a function returns a value, and a subroutine returns multiple values. Yet none of this really allows us to come up with a "universal" definition for these terms.

In fact, the term "procedural programming" refers to a whole class of languages, including C, Fortran and Pascal, only one of which actually uses the term "procedure" to mean anything.

So none of this is really consistent.


The only exception is probably method, which seems to be used almost entirely with OO Languages, referring to a function that is associated with an object. Although, even this is not always consistent. C++, for example, usually uses the term "member function" rather than method, (even though the term "method" has crept into the C++ vernacular among programmers.)


The point is, none of this is really consistent. It simply reflects the terminology employed by whatever languages are en vogue at the time.


A real distinction is when we talk about a function in Functional programming. If you like to keep a function clean (just look at functional languages) you need to make sure a function does not have a side effect. However, in all the procedural or OOP languages we refer to functions that don't really meet the exact mathematical definition of a function that is used in Functional programming. https://stackoverflow.com/questions/721090/what-is-the-difference-between-a-function-and-a-procedure/721107



Subprogram header is the fist part of the definition including the name, the kind of subprogram, and the formal parameters.

The parameter profile (aka signature) of a subprogram is the number, order and types of its parameters.

The protocol is a subprogram parameter profile and, if it is a function, its return type.



There are tow categories of subprograms: (This is from Muhammad slides. I have already explained what I found in my research about the difference between Procedures and Functions).

  • Procedures: Are collection of statements that define parameterized computations.
  • Functions: Structurally resemble procedures but are semantically modeled on mathematical functions.



Design issues for Subprograms:

  • Are local variables static or dynamic?
  • What types of values can be returned from functions?
  • How many values can be returned from functions?
  • Can subprograms be overloaded?
  • Can subprogram be generic?
  • Is the language allowed nested subprograms?



Some important concepts around Subprograms are:

  • Parameter-passing:
  • Pass-by-Value (In Mode)
  • Pass-by-Result (Out Mode)
  • Pass-by-Reference (Inout Mode)
  • Local referencing environments
  • Generic subprograms
  • Overloaded subprograms



Generic subprograms

A generic subprogram is one that takes parameters of different types on different activation.

Following example illustrates how we can print an array of different type using a single Generic method: https://www.tutorialspoint.com/java/java_generics.htm

public class GenericMethodTest {
   // generic method printArray
   public static < E > void printArray( E[] inputArray ) {
      // Display array elements
      for(E element : inputArray) {
         System.out.printf("%s ", element);
      }
      System.out.println();
   }

   public static void main(String args[]) {
      // Create arrays of Integer, Double and Character
      Integer[] intArray = { 1, 2, 3, 4, 5 };
      Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
      Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

      System.out.println("Array integerArray contains:");
      printArray(intArray);   // pass an Integer array

      System.out.println("\nArray doubleArray contains:");
      printArray(doubleArray);   // pass a Double array

      System.out.println("\nArray characterArray contains:");
      printArray(charArray);   // pass a Character array
   }
}



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 signs
  • Perl: All variable names begin with special characters, which specify the variable's type
  • Ruby: 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 and C++ 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



Data type

A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.



Descriptor: It's the collection of the attributes of a variable.

Ex.:

Compile-time descriptor for a single-dimensional array
Compile-time descriptor for a multidimensional array


Example
Primitive Data Types
  • Primitive data types are those not defined in terms of other data types.
  • Almost all programming languages provide a set of primitive data types
Integer byte
short
int
long
Floating Point float
double
Complex Each value consists of two floats, the real part and the imaginary part
Boolean
Character
  • Stored as numeric codings
  • Most commonly used coding: ASCII


Character Strings

Design issues
  • Values are sequences of characters
  • Is it a primitive type or just a special kind of array?
  • Should the length of strings be static or dynamic?
Arrays An array is a homogeneous aggregate of data elements in which an individual element is identified by its position in the aggregate, relative to the first element.


Index Syntax

  • Fortran and Ada use parentheses. Most other languages use brackets.


Rectangular and Jagged Arrays:

  • A rectangular array is a multi-dimensional array in which all of the rows have the same number of elements and all columns have the same number of elements
  • A jagged matrix has rows with varying number of elements

Possible when multi-dimensional arrays actually appear as arrays of arrays

  • C, C++, and Java support jagged arrays
  • F# and C# support rectangular arrays and jagged arrays


Slices:

  • A slice is some substructure of an array; nothing more than a referencing mechanis
  • Slices are only useful in languages that have array operations. Ex. Python, Ruby

Slicing in Python:
Python
vector = [2, 4, 6, 8, 10, 12, 14, 16]
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

vector (3:6) is a three-element array
mat[0][0:2] is the first and second element of the first row of mat


Ruby supports slices with the slice method: list.slice(2, 2)

Associative Arrays An associative array is an unordered collection of data elements that are indexed by an equal number of values called keys:

Ex:

Python: Dictionary

C++: Associative arrays

Perl: Associative Arrays

Associative Arrays in Perl
# Names begin with %; literals are delimited by parentheses
%hi_temps = ("Mon" => 77, "Tue" => 79, "Wed" => 65, ...);

# Subscripting is done using braces and keys
$hi_temps{"Wed"} = 83;

# Elements can be removed with delete
delete $hi_temps{"Tue"};
Record A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names
Enumeration All possible values, which are named constants, are provided in the definition.

No enumeration variable can be assigned a value outside its defined range

C# example:
enum days {mon, tue, wed, thu, fri, sat, sun};



Pointer

Pointers store address of variables or a memory location.

A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable. https://beginnersbook.com/2014/01/c-pointers/


  • A pointer type variable has a range of values that consists of memory addresses and a special value, nil.
  • Provide the power of indirect addressing
  • Provide a way to manage dynamic memory
  • A pointer can be used to access a location in the area where storage is dynamically created (usually called a heap)


C Pointers.jpg



Pointers in C and CPP

How-pointer-works-in-C.png


To use pointers in C, we must understand below two operators: & and *

Ampersand (&):

The unary operator & (ampersand) returns the address of that variable.

For example &x gives us the address of the variable.

// The output of this program can be different in different runs.
// Note that The program prints address of a variable and a variable
// can be assigned different address in different runs. 
#include <stdio.h> 

int main() 
{ 
    int x = 10; 
 
    // Prints address of x 
    printf("%p", &x); 
  
    return 0; 
}
Pointer memory representation.png

Unary (Asterisk) (*) : It is used for two things:

To declare a pointer variable:

  • When a pointer variable is declared in C/C++, there must have a * before its name.
// C program to demonstrate declaration of 
// pointer variables. 
#include <stdio.h> 
int main() 
{ 
    int x = 10; 
  
    // 1) Since there is * in declaration, ptr becomes a pointer
    // varaible (a variable that stores address of another variable)
    // 2) Since there is int before *, ptr is pointer to an integer 
    // type variable 
    int *ptr; 
  
    // & operator before x is used to get address of x.
    // The address of x is assigned to ptr. 
    ptr = &x; 
  
    return 0; 
}

To access the value stored in the address.

  • The unary operator (*) returns the value of the variable located at the address specified by its operand.


// C program to demonstrate use of * for pointers in C 
#include <stdio.h> 
  
int main() 
{ 
    // A normal integer variable 
    int x = 10; 
  
    // A pointer variable that holds address of var. 
    int *ptr = &x; 
  
    // This line prints the value at the address stored in ptr. 
    // The Value stored is the value of variable "x"
    printf("Value of x = %d\n", *ptr); 
  
    // The output of this line may be different in different 
    // runs even on the same machine. 
    printf("Address of x = %p\n", ptr); 
  
    // We can also use ptr as lvalue (Left hand side of assignment) 
    *ptr = 20; // Value at address is now 20 
  
    // This prints 20 
    printf("After doing *ptr = 20, *ptr is %d\n", *ptr); 
  
    return 0; 
}
Pointer assigment.png
j = *ptr



Recursion

https://www.python-course.eu/recursive_functions.php

https://www.geeksforgeeks.org/recursion/


The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.


A VERY VERY NICE example of recursion is the factorial function: https://www.geeksforgeeks.org/program-for-factorial-of-a-number/

Example:
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Replacing the calculated values gives us the following expression
4! = 4 * 3 * 2 * 1


Iterative solution (Java):

class Main{
    static int factorial(int n){
        int res = 1;
        for (int i=2 ; i<=n ; i++)
          res *= i;
        return res;
    }
    public static void main(String[] args){
        System.out.println(factorial(6));
    }
}


Recursive solution (Java):

class Main{

    static int factorial(int n){
        if (n == 0)
          return 1;
        return n*factorial(n-1);
    }

    public static void main(String[] args){
        System.out.println(factorial(5));
    }

}


One line Solution (Using Ternary operator) (Java):

class Main{ 
  
 int factorial(int n){
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); 
  } 

  public static void main(String args[]){ 
    Main obj = new Main(); 
    System.out.println(obj.factorial(6));
  } 

}



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 or Java
  • Load time: Bind a C or C++ 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 of superclass with the reference of the superclass.
  • Since the print method of superclass is static, compiler knows that it will not be overridden in subclasses 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 to runtime 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.



Statically and Dynamically typed languages


Statically typed languages:

A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (e.g.: Java, C, C++); other languages offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin)

The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.

Examples: C, C++, Java, Rust, Go, Scala



Dynamically typed languages:

A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference).

Examples: Perl, Ruby, Python, PHP, JavaScript

Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.

Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.



Reflection

http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example

https://docs.oracle.com/javase/tutorial/reflect/index.html


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


Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example


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 non-portable



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 of Class returns the Class 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 class
getMethods returns an array of all public methods of a class
getDeclaredMethod searches for a specific method of a class
getDeclaredMethods returns an array of all methods of a class
The Method class defines the invoke method, which is used to execute the method found by getMethod


Here is a quick Java Reflection example to show you what using reflection looks like:

Method[] methods = MyObject.class.getMethods();

for(Method method : methods){
    System.out.println("method = " + method.getName());
}

This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names. http://tutorials.jenkov.com/java-reflection/index.html#java-reflection-example



Languages evaluation criteria

https://www.cs.scranton.edu/~mccloske/courses/cmps344/sebesta_chap1.html

https://medium.com/@thisisfordeveloper/programming-language-evaluation-criteria-part-2-writability-reliability-cost-6c3029c9d957



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.

  • Simplicity:
  • Orthogonality:
  • Data Types:
  • Syntax Design:

This is a measure of how easily a language can be used to develop programs for a chosen problem domain.

  • Simplicity and Orthogonality:
  • Support for Abstraction:
  • Expressivity:

This is the property of performing to specifications under all conditions.

  • Type Checking:
  • Aliasing:

The following contribute to the cost of using a particular language:

  • Training programmers: cost is a function of simplicity of language
  • Writing and maintaining programs: cost is a function of readability and writability.
  • Compiling programs: for very large systems, this can take a significant amount of time.
  • Executing programs: Having to do type checking and/or index-boundary checking at run-time is expensive. There is a tradeoff between this item and the previous one (compilation cost), because optimizing compilers take more time to work but yield programs that run more quickly.
  • Language Implementation System: e.g., Java is free, Ada not
  • Lack of reliability: software failure could be expensive (e.g., loss of business, liability issues)
  • Portability: the ease with which programs that work on one platform can be modified to work on another. This is strongly influenced by to what degree a language is standardized.
  • Generality: Applicability to a wide range of applications.
  • Well-definedness: Completeness and precision of the language's official definition.



Some programming paradigms


Imperative vs Declarative programming paradigm

https://medium.com/front-end-weekly/imperative-versus-declarative-code-whats-the-difference-adc7dd6c8380

https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2


  • Imperative programming style:
  • Focused on describe HOW the computer should accomplish the task.
  • A more formal definition: Imperative programming is a programming paradigm that uses statements that change a program's state.
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.
  • Procedural and object-oriented programming belong under imperative paradigm: C, C++, C#, PHP, Java and of course Assembly.
  • Example of imperative code in JavaScript:
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 programming style:
  • Focused on describe WHAT the computer should accomplish.
  • A more formal definition: Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow:
Declarative code focuses on building logic of software without actually describing its flow. You are saying WHAT TO DO 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.
  • 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: HTML, XML, CSS, SQL, Prolog, Haskell, F# and Lisp.
  • Example of declarative code in JavaScript:
const sum = a => b => a + b;
console.log (sum (5) (3)); // 8



Procedural programming paradigm


Object-Oriented Paradigm


Functional Programming


Scripting

https://www.geeksforgeeks.org/whats-the-difference-between-scripting-and-programming-languages/

Basically, all scripting languages are programming languages. One of the clearest differences between the two is that scripting languages do not require the compilation step and are rather interpreted.


https://www.pcmag.com/encyclopedia/term/scripting-language

http://pages.di.unipi.it/corradini/Didattica/AP-19/DOCS/Scott-ch13.pdf