About Programation

De My Limbic Wiki
Aller à : navigation, rechercher

Central Principles in POO

Abstraction

  • Use the Abstract keyword to be defined
  • Cannot be instanciated
  • Methods can be or not Abstract, if they are they have to be empty
  • Abstract methods HAVE TO be implemented in class wich unherit from this abastract class
  • An interface is a collection of abstract methods

Inheritance

  • Extends: Multiple inheritance
  • Using extends keyword, the child class inherits the methods of parent class.
  • A child inherits the properties and actions (functions) of it’s parent

Encapsulation

  • Declare private variables
  • Declare Setters and Getters to modify them

Polymorphism

  • Process objects differently based on their data type.
  • One method with multiple implementation
  • This can be implemented by designing a generic interface, which provides generic methods for a certain class of action and there can be multiple classes, which provides the implementation of these generic methods.
  • Ways to do it:
    • Override: method of an extended class
    • Compile Time: Multiple methods declaration with multiple parameters
  • In polymorphism, the parent class has a declared method wich is not abstracted and not empty. There is a process inside, it is not only a declaration in a abstract class
  • Le polymorphisme Ad Hoc : permet d'avoir des fonction de même nom, de fonctionnalités similaires mais dans des classes radicalement différentes.
  • Le polymorphisme paramétrique : permet de définir des fonctions de même nom mais de paramètres différents. Le programme choisit ainsi la bonne méthode à adopter en fonction des paramètres d'entrée (logiques, entiers, chaîne de caractère ...)
  • Le polymorphisme d'héritage : permet de redéfinir les méthodes dans les classes héritant (sous classes) d'une classe de base, pour ainsi appeler une fonction sans se soucier de la classe de l'objet (comme pour faire bouger toutes les pièces d'échec avec la fonction bouger sans se soucier de la pièce en question, le mouvement étant défini par la classe de la pièce)

Packages

  • Prevent naming conflicts
  • Control access
  • Make searching/locating and usage of classes, interfaces, enumerations and annotations easier...

Interface

  • Collection of abstract methods.
  • A class implements an interface, thereby inheriting the abstract methods of the interface.

Standard Architecture

standard web architecture

src

  • com.project
    • Main: Entry point
  • com.project.configuration
    • project Security & MVC Configuration

Components

in Java @Component is the top level generic annotation which makes the annotated bean to be scanned and available in the DI container

  • com.project.controllers
    • is specialized annotation which makes the bean MVC aware and allows the use of further annotation like @RequestMapping and all such
  • com.project.model
    • Object Relational Database
  • com.project.repositories
    • DAO Interface is specialized annotation and it brings the feature of converting all the unchecked exceptions from the DAO classes
    • Indicates that an annotated class is a "Repository", originally defined byDomain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage,retrieval, and search behavior which emulates a collection of objects". Teams implementing traditional Java EE patterns such as "Data Access Object"may also apply this stereotype to DAO classes, though care should be taken tounderstand the distinction between Data Access Object and DDD-style repositoriesbefore doing so. This annotation is a general-purpose stereotype and individual teamsmay narrow their semantics and use as appropriate. A class thus annotated is eligible for Spring DataAccessException translationwhen used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified asto its role in the overall application architecture for the purpose of tooling,aspects, etc. As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetectedthrough classpath scanning.
  • com.project.services
    • Indicates that an annotated class is a "Service", originally defined by Domain-DrivenDesign (Evans, 2003) as "an operation offered as an interface that stands alone in themodel, with no encapsulated state." May also indicate that a class is a Business Service Facade (in the Core J2EEpatterns sense),

resources

  • static
    • css
    • images
    • javascript
  • templates
    • admin
    • home
    • registration

properties

  • properties and configuration files

Difference Controller and Presenter

  • Presenter
    • The View is responsible for handling the UI events
  • Controller
    • Handle the UI Events

Design Patterns

  • MVC
  • MVP
  • MVVM

Famous Patterns

Singleton

  • Class Singleton with a private constructor
    • Private static parameter single_instance set to null
    • Private static Method getInstance(): if the parameter is null, instantiate Singleton class as New, if not return the existing instance returning the parameter single_instance

Every instantiation has to be called as: Singleton.getInstance();

Observable

Factory

Strategy

Builder

Adapter

State

Paradigm

  • REST: Representational State Transfer; Used with Web Services
  • Object
  • Procedural

Acronyms

  • CRUD: Create, Read, Update, Delete

Synchronous vs Asynchronous

When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes. In the context of computers this translates into executing a process or task on another "thread."

Architectures

MicroServices

SOA: Service Oriented Architecture

Service-oriented architecture (SOA) is a style of software design where services are provided to the other components by application components, through a communication protocol over a network. The basic principles of service-oriented architecture are independent of vendors, products and technologies.

  • The servcices are independant but not able to deploy independently.
  • Having large entreprise buses: the business and connection pipes between services are mixed, so with time it start to be hard to maintain. Micro Services are insisting on "Thin Pipes" to avoid this kind of problems
  • Has a messaging middleware: needed to make the differents applications communicate where microservices are communicating in REST only (API Layer)

Coupling

Loose Coupling

/**
* #########################################################
* #################### Loose Coupling #####################
* #########################################################
*/
class CustomerRepository{
    private readonly IDatabase database;

    public CustomerRepository(IDatabase database){
        this.database = database;
    }

    public void Add(string CustomerName){
        database.AddRow("Customer", CustomerName);
    }
}

interface IDatabase{
    void AddRow(string Table, string Value);
}

class Database implements IDatabase{
    public void AddRow(string Table, string Value){
		//Do something
	}
}

Tight Coupling

/**
* #########################################################
* #################### Tight Coupling #####################
* #########################################################
*/
class CustomerRepository{
    private readonly Database database;

    public CustomerRepository(Database database){
        this.database = database;
    }

    public void Add(string CustomerName){
        database.AddRow("Customer", CustomerName);
    }
}

class Database{
    public void AddRow(string Table, string Value){
		//DO something
    }
}

Principles

Liskov Substitution Principle

public class Bird{
    public void fly(){}
}
public class Duck extends Bird{}

/**
* Ostrich is a bird, But it can't fly, Ostrich class is a subtype of class Bird, But it can't use the fly method, that means that we are breaking LSP principle.
*/
public class Ostrich extends Bird{}

Dependency Inversion Principle

Rule 1: High-level modules should not depend on low-level modules.

RUle 2: Abstractions should not depend on details.

Both should depend on abstractions.

/**
* #########################################################
* #################### Rule Violation #####################
* #########################################################
*/
public class BackEndDeveloper {
    /** First rule Violation */
    public void writeJava() {}
}
public class FrontEndDeveloper {
    /** First rule Violation */
    public void writeJavascript() {}
}
public class Project {
    /** Second rule Violation */
    private BackEndDeveloper backEndDeveloper = new BackEndDeveloper();
    private FrontEndDeveloper frontEndDeveloper = new FrontEndDeveloper();
    public void implement() {
        backEndDeveloper.writeJava();
        frontEndDeveloper.writeJavascript();
    }
}
/**
* #########################################################
* ######################### Rule ##########################
* #########################################################
*/
public interface Developer {
    void develop();
}
public class BackEndDeveloper implements Developer {
    @Override
    public void develop() {
        writeJava();
    }
    private void writeJava() {}
}

public class FrontEndDeveloper implements Developer {
    @Override
    public void develop() {
        writeJavascript();
    }
    public void writeJavascript() {}
}
public class Project {
    private List<Developer> developers;
    public Project(List<Developer> developers) {
        this.developers = developers;
    }
    public void implement() {
        developers.forEach(d->d.develop());
    }
}
Details should depend on abstractions.

Interface Segregation Principle

Bad Example

// interface segregation principle - bad example
interface IWorker {
	public void work();
	public void eat();
}

class Worker implements IWorker{
	public void work() {
	    // ....working
	}
	public void eat() {
	    // ...... eating in launch break
	}
}

class SuperWorker implements IWorker{
	public void work() {
	    //.... working much more
	}
	public void eat() {
	    //.... eating in launch break
	}
}

class Manager {
	IWorker worker;

	public void setWorker(IWorker w) {
	    worker=w;
	}
	public void manage() {
	    worker.work();
	}
}

Good Exemple

// interface segregation principle - good example
interface IWorker extends Feedable, Workable {
}

interface IWorkable {
	public void work();
}

interface IFeedable{
	public void eat();
}

class Worker implements IWorkable, IFeedable{
	public void work() {
		// ....working
	}

	public void eat() {
		//.... eating in launch break
	}
}

class Robot implements IWorkable{
	public void work() {
		// ....working
	}
}

class SuperWorker implements IWorkable, IFeedable{
	public void work() {
		//.... working much more
	}

	public void eat() {
		//.... eating in launch break
	}
}

class Manager {
	Workable worker;

	public void setWorker(Workable w) {
		worker=w;
	}

	public void manage() {
		worker.work();
	}
}

Composite Reuse Principle

Also known as Favor Composition Over Heritance

Good to Know

  • Priority Queue:In computer science, a priority queue is an abstract data type which is like a regular queue, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. (https://www.hackerrank.com)
  • Covariant Return Types: Java allows for Covariant Return Types, which means you can vary your return type as long you are returning a subclass of your specified return type. (https://www.hackerrank.com)
  • le extends permet d'heriter des fonction protected et public d'une classe ainsi que ses champs
  • le implements permet d'obliger une classe a definir certaines methodes

More