202 - Functional Programming

Methods / Functions are 1st class citizens in Functional Programming!

  1. Methods Literals
  2. Can be assigned to Variables
  3. Can be passed around
  4. Can be returned

Syntax for “Method Literals” To be used as Variable Values. Object :: methodName

  • Lambda expressions allows us to implement “single responsibility” at method level!
  • The Open/Closed Principle rely on an abstraction and can plug in new functionality that fits into this abstraction.
  • Liskov “Substitution” principle helps to avoid the pitfalls of OO Inheritance. (Composition Reuse, Functional Programming)
  • Interface segregation : give user only the need (Proxy and adapter)
  • Dependency-inversion principle : Keep high-level abstractions independent of low-level Implementation / details.

Command Pattern:

Strategy Pattern:

AspectJ

AspectJ is an aspect-oriented programming (AOP) extension created for the Java programming language. And AOP is an attempt to address cross cutting concerns in applications. It requires two features to implement aspects : Quantification & Advice

Extension methods

Allow a programmer to add methods, fields, or interfaces to existing classes from within the aspect. This example adds an acceptVisitor (see visitor pattern) method to the Point class:

aspect VisitAspect { void Point.acceptVisitor(Visitor v) { v.visit(this); } }

Pointcuts

Allow a programmer to specify join points (well-defined moments in the execution of a program, like method call, object instantiation, or variable access). All pointcuts are expressions (quantifications) that determine whether a given join point matches. For example, this point-cut matches the execution of any instance method in an object of type Point whose name begins with set:

pointcut set() : execution(* set*(..) ) && this(Point);

Advices

Allow a programmer to specify code to run at a join point matched by a pointcut. The actions can be performed before, after, or around the specified join point. Here, the advice refreshes the display every time something on Point is set, using the pointcut declared above:

after () : set() {
   Display.update();
}

Object-Oriented vs. Functional Programming

Object-Oriented : Abstraction, Encapsulation, Inheritance, Polymorphism

functional programming: Functions are first class, Use pure function, Functions can be composed, Data is immutable, Data is transformed, not modified, Expressions are preferred over statements

functional programming emphasizes the power of reuse and composition of behavior through higher-order functions

first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

Lambda Expressions

Java 8 Method Reference

reference : https://www.codementor.io/eh3rrera/using-java-8-method-reference-du10866vx

https://medium.freecodecamp.org/learn-these-4-things-and-working-with-lambda-expressions-b0ab36e0fffc

In Java, a functional interface is basically an interface with a single abstract method. This kind of interfaces are also known as SAM (Single Abstract Method) types.

Before Java 8 there were already several interfaces compatible with this idea:

public interface Comparator<T> {
    int compare(T o1, T o2);
}

public interface Callable<V> {
    V call() throws Exception;
}

public interface ActionListener extends EventListener {
    public void actionPerformed(ActionEvent e);
}

public interface Runnable {
    public void run();
}

Many new functional interfaces are being defined in the Java 8, among the most popular, those found in the new java.util.function package. The following are some examples of new functional interfaces in Java:

public interface Predicate<T> {
    boolean test(T t);
}

public interface Function<T,R> {
    R apply(T t);
}

public interface BinaryOperator<T> {
    T apply(T left, T right);
}

public interface Consumer<T> {
    void accept(T t);
}

public interface Supplier<T> {
    T get();
}

In languages that support first class functions, the type of the lambda expression would be a function; but in Java, the lambda expressions are represented as objects, and so they must be bound to a particular object type known as a functional interface. This is called the target type.

Since a functional interface can only have a single abstract method, the types of the lambda expression parameters must correspond to the parameters in that method, and the type of the lambda body must correspond to the return type of this method. Additionally, any exceptions thrown in the lambda body must be allowed by the throws clause of this method in the functional interface.

A method reference is the shorthand syntax for a lambda expression that executes just ONE method. Here's the general syntax of a method reference:

Object :: methodName

Method reference can't be used for any method.They can only be used to replace a single-method lambda expression.

Instead of using

AN ANONYMOUS CLASS

you can use

A LAMBDA EXPRESSION

And if this just calls one method, you can use

A METHOD REFERENCE

SOLID

reference : http://teddy-chen-tw.blogspot.com/2014/04/solid.html

  • S stands for Single-Responsibility Principle : A class should have only one reason to change. 降低單一類別被「改變」所影響的機會
  • O stands for Open-Closed principle: software entities should be open for extension, but closed for modification **當新增需求的時候(功能變化),在不改變現有程式碼的前提之下,藉由增加新的程式碼來實作新的功能。
  • L stands for Liskov Substitution Principle : if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.) Child preserves Parent’s: 1. Preconditions 2. Postconditions 3. Invariants 4. Constraints LSP談的是繼承,也就是透過繼承時子類別所造成的「行為變化」要如何設計,才可以讓程式在runtime透過多型所繫結(bind)到的子類別實作,不至於違反父類別介面的合約。
  • I stands for Interface Segregation Principle : The dependency of one class to another one should depend on the smallest possible interface, (Proxy and adapter) 針對不同的客戶端,只開放其所需要的介面讓它使用,如此一來可避免與降低客戶端因為不相關介面改變也一起被迫需要改變的問題。
  • D stands for Dependency Inversion Principle : A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend on details. Details should depend on abstractions. caller和callee之間的關係,在兩者之間增加一個(抽象)介面,避免caller(上層程式)因為callee(底層程式)改變而被迫改變。

Closure

A closure uses variables that are outside of the function scope. The ability to create functions at runtime, which can then be passed/manipulated by other code.

Higher-order function

a higher-order function is a function that does at least one of the following:

  • takes one or more functions as arguments (i.e. procedural parameters),
  • returns a function as its result.

higher-order functions that take one function as argument are values with types of the form

results matching ""

    No results matching ""