Interfaces in OOP languages and prototype-based languages

Basic OOP principles

- Polymorphism.

In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.

- Abstraction.

Abstraction is one of three central principles (along with encapsulation and inheritance). Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency.

- Inheritance.

Inheritance is the principle of class hierarchy. It is the ability for one object to take on the states, behaviour, and functionality of another object.

- Encapsulation.

The most important principle of object orientation is encapsulation:
The idea that data inside the object should only be accessed through a public interface – that is, the object’s methods.

Encapsulation is a good idea for several reasons:
- the functionality is defined in one place and not in multiple places.
- it is defined in a logical place – the place where the data is kept.
- data inside our object is not modified unexpectedly by external code in a completely different part of our program.
- when we use a method, we only need to know what result the method will produce – we don’t need to know details about the object’s internals in order to use it. We could switch to using another object which is completely different on the inside, and not have to change any code because both objects have the same interface.

(quora.com & webopedia.com & techtarget.com  & gamedevelopment.tutsplus.com & python-textbok.readthedocs.io)

What is an interface OOP?

An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class).
(cs.utah.edu)

Why do we use interface ?

Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces. Interfaces are better in situations in which you do not have to inherit implementation from a base class.Interfaces are useful when you cannot use class inheritance.
(quora.com)

What is meant by abstract class?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods
(stackoverflow.com)

Interfaces in Python

No, python does not have any equivalent of interfaces . Since Python does support multiple inheritance, you can easily emulate the equivalence of interfaces. What that means is that interfaces are implicit in Python : if an object conforms to an interface, you can use it, no need to declare it like you would in statically typed languages such as Java or C# .

The closest thing is probably the abstract base classes module, which allows you to define common methods for a set of classes.

In Python, encapsulation is not enforced by the language, but there is a convention that we can use to indicate that a property is intended to be private and is not part of the object’s public interface: we begin its name with an underscore.

- What is an Inheritance in python?

Inheritance is a way of arranging objects in a hierarchy from the most general to the most specific. An object which inherits from another object is considered to be a subtype of that object. As we saw in the previous chapter, all objects in Python inherit from object. We can say that a string, an integer or a Person instance is an object instance. When we can describe the relationship between two objects using the phrase is-a, that relationship is inheritance.

- What is an abstract class in python?

The abstract class is thus an interface definition – some languages also have a type of structure called an interface, which is very similar. We say that a class implements an interface if it inherits from the class which specifies that interface.

Here is an example:

import math

class Shapes:
    def __init__(self, no_sides):
        self.x = no_sides
        self.sides = [0 for i in range(no_sides)]
        self.height = [0]
        self.radius = [0]

    def input(self):
        if len(self.sides) > 0:
            self.sides = [float(input("Side " + str(i + 1) + " : "))
                          for i in range(self.x)]
        else:
            self.radius = [float(input("Radius : "))]
        self.height = [float(input("Height : "))]


class Square(Shapes):
    def __init__(self):
        print("Square start")
        Shapes.__init__(self, 1)

    def perimeter(self):
        a = self.sides[0]
        perimeter = (2 * a) + (2 * a)
        print('Square perimeter is %0.0f' %perimeter)

    def area(self):
        a = self.sides[0]
        # calculate
        area = a * a
        print('Square area is %0.0f' %area)

    def volume(self):
        a = self.sides[0]
        h = self.height[0]
        area = a * a
        volume = area * h
        print('Square volume is %0.0f' %volume)


class Rectangle(Shapes):
    def __init__(self):
        print("Rectangle start")
        Shapes.__init__(self, 2)

    def perimeter(self):
        a, b = self.sides
        perimeter = (2 * a) + (2 * b)
        print('Rectangle perimeter is %0.1f' %perimeter)

    def area(self):
        a, b = self.sides
        # calculate
        area = a * b
        print('Rectangle area is %0.1f' %area)

    def volume(self):
        a, b = self.sides
        h = self.height[0]
        # calculate
        area = a * b
        volume = area * h
        print('Rectangle volume is %0.1f' %volume)


class Triangle(Shapes):
    def __init__(self):
        print("Triangle start")
        Shapes.__init__(self, 3)

    def perimeter(self):
        a, b, c = self.sides
        perimeter = a + b + c
        print('Triangle perimeter is %0.2f' %perimeter)

    def area(self):
        a, b, c = self.sides
        # calculate the semi-perimeter
        s = (a + b + c) / 2
        area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
        print('Triangle area is %0.2f' %area)

    def volume(self):
        a, b, c = self.sides
        h = self.height[0]
        # calculate the semi-perimeter
        s = (a + b + c) / 2
        area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
        volume_prism = area * h
        print('Rectangle volume prism is %0.1f' %volume_prism)
        volume_pyramid = (1 / 3) * area * h
        print('Rectangle volume Pyramid is %0.1f' %volume_pyramid)


class Circle(Shapes):
    def __init__(self):
        print("Circle start")
        Shapes.__init__(self, 0)

    def perimeter(self):
        r = self.radius[0]
        perimeter = 2 * math.pi * r
        print('Circle perimeter is %0.2f' %perimeter)

    def area(self):
        r = self.radius[0]
        # calculate the semi-perimeter
        area = math.pi * (r * r)
        print('Circle area is %0.2f' %area)

    def volume(self):
        r = self.radius[0]
        h = self.height[0]
        # calculate the semi-perimeter
        area = math.pi * (r * r)
        volume_prism = area * h
        print('Circle volume prism is %0.1f' %volume_prism)
        volume_pyramid = (1 / 3) * area * h
        print('Circle volume Pyramid is %0.1f' %volume_pyramid)


t = Circle()
t.input()
t.perimeter()
t.area()
t.volume()

t = Square()
t.input()
t.perimeter()
t.area()
t.volume()

t = Rectangle()
t.input()
t.perimeter()
t.area()
t.volume()

t = Triangle()
t.input()
t.perimeter()
t.area()
t.volume()

(python-textbok.readthedocs.io & net-informations.com)

Interfaces in JavaScript

Interfaces are not a thing in JavaScript, not really anyway. JavaScript is a dynamic language, one where types are changed so often that the developer may not have even realised, because of this people argue there is no need for an interface to be added to the ECMAScript standard that JavaScript is based on.

A class is a blueprint from which we can create objects that share the same configuration - properties and methods. We use classes as object factories. A class defines a blueprint of what an object should look like and act like and then implements that blueprint by initialising class properties and defining methods. Therefore, when we create an instance of the class, we get an object that has actionable functions and defined properties.

The constructor method is a special method for creating and initializing an object created within a class.

Here is an example:

class Polygon {
  constructor() {
    this.name = "Polygon";
  }
}

var poly1 = new Polygon();

console.log(poly1.name);
// expected output: "Polygon"

Emulating Interfaces with Duck Typing
In the end, it doesn't matter whether a class declares the interfaces it supports, as long as the required methods are in place. That is where duck typing comes in. Duck typing was named after the saying, “If it walks like a duck and quacks like a duck, it's a duck.” It is a technique to determine whether an object is an instance of a class based solely on what methods it implements, but it also works great for checking whether a class implements an interface. The idea behind this approach is simple: if an object contains methods that are named the same as the methods defined in your interface, it implements that interface. Using a helper function, you can ensure that the required methods are there

Here is an example:

// Interfaces.
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
var FormItem = new Interface('FormItem', ['save']);

// CompositeForm class
var CompositeForm = function(id, method, action) { // implements Composite, FormItem
    //...
};

//...

function addForm(formInstance) {
    Interface.ensureImplements(formInstance, Composite, FormItem);
    // This function will throw an error if a required method is not implemented,
    // halting execution of the function.
    // All code beneath this line will be executed only if the checks pass.
    //...
}

Interface.ensureImplements provides a strict check. If a problem is found, an error will be thrown, which can either be caught and handled or allowed to halt execution. Either way, the programmer will know immediately that there is a problem and where to go to fix it.

Here is the  Interface class that we use it the above example:

// Constructor.
var Interface = function(name, methods) {

    if (arguments.length != 2) {
        throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2.");
    }

    this.name = name;
    this.methods = [];

    for (var i = 0, len = methods.length; i < len; i++) {
        if (typeof methods[i] !== 'string') {
            throw new Error("Interface constructor expects method names to be passed in as a string.");
        }

        this.methods.push(methods[i]);
    }
};

// Static class method.
Interface.ensureImplements = function(object) {
    if (arguments.length < 2) {
        throw new Error("Function Interface.ensureImplements called with " + arguments.length + "arguments, but expected at least 2.");
    }

    for (var i = 1, len = arguments.length; i < len; i++) {
        var interface = arguments[i];
        if (interface.constructor !== Interface) {
            throw new Error("Function Interface.ensureImplements expects arguments two and above to be instances of Interface.");
        }

        for (var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
            var method = interface.methods[j];
            if (!object[method] || typeof object[method] !== 'function') {
                throw new Error("Function Interface.ensureImplements: object does not implement the " + interface.name + " interface. Method " + method + " was not found.");
            }
        }
    }
};

(hackernoon.com & toddmotto.com & developer.mozilla.org & jscriptpatterns.blogspot.com)

What strict mode is in JavaScript?

ECMAScript 5's strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode". Strict mode isn't just a subset: it intentionally has different semantics from normal code

Why use it?

Strict mode throws more errors and disables some features in an effort to make your code more robust, readable, and accurate.
Advantages
Strict mode helps out in a couple ways:
- It catches some common coding bloopers, throwing exceptions.
- It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
- It disables features that are confusing or poorly thought out.
Disadvantages
When code mixed strict and “normal” modes. If a developer used a library that was in strict mode, but the developer was used to working in normal mode, they might call some actions on the library that wouldn’t work as expected. Worse, since the developer is in normal mode, they don’t have the advantages of extra errors being thrown, so the error might fail silently.
(developer.mozilla.org & lucybain.com)

What is TypeScript?

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language.

TypeScript is designed for development of large applications and transcompiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. TypeScript may be used to develop JavaScript applications for both client-side and server-side (Node.js) execution.

- Is TypeScript good?

TypeScript also brings everything good that comes with newer versions of ECMAScript, including class syntax and arrow functions. It also adds lots of Object-Oriented Programming features, like interfaces, generics, and method access modifiers, without losing the feeling that you are coding in JavaScript

- What is the advantage of TypeScript?

Optional static typing (the key here is optional) Type Inference, which gives some of the benefits of types, without actually using them. Access to ES6 and ES7 features, before they become supported by major browsers. The ability to compile down to a version of JavaScript that runs on all browsers

- Interfaces with TypeScript

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

Here is an example:

interface LabelledValue {
    label: string;
}

function printLabel(labelledObj: LabelledValue) {
    console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

The interface LabelledValue is a name we can now use to describe the requirement in the previous example. It still represents having a single property called label that is of type string. Notice we didn’t have to explicitly say that the object we pass to printLabel implements this interface like we might have to in other languages. Here, it’s only the shape that matters. If the object we pass to the function meets the requirements listed, then it’s allowed.
(wikipedia.org & ionicframework.com)

Comments

Popular posts from this blog

Concurrency in Web Development

Big-O notation basics for web developers