Friday, February 1, 2019

Lamda Expressions Concepts


Lambda expression leverages functional programming in Java. Lambda expression contains the implementation of a single function within the instance of an interface. The close similarity of lambda expression is anonymous inner class implementation of an interface.

Lambda expressions implement functional interfaces. A functional interface is an interface that can contain only one abstract method. A functional interface can however contain several default methods and static methods.

Let's define one functional interface like the following:
  @FunctionalInterface
  public interface Greeting {
    public void sayGreeting(String message);
  }

Here use of annotation @FunctionalInterface is recommended since it enforces to use only one abstract method. Lets first implement it with anonymous inner class:
    Greeting greetingImpl = new Greeting() {
          @Override
          public void sayGreeting(String message) {
                System.out.println(message);
          }
    };
    greetingImpl.sayGreeting("Hello from Anonymous inner class.");

Using lambda expression for doing the same task will make the code shorter and cleaner.
    Greeting greetingLambda = message -> System.out.println(message);
    greetingLambda.sayGreeting("Hello from Lambda expression");
Lambda expression syntax:
(argument-list) -> {body}
Java lambda expression is consisted of three parts:
  • Argument-list: It can be empty or non-empty.
  • Arrow-token: It is used to link arguments-list and body of expression.
  • Body: It contains expressions and statements for lambda expression.
Type declaration can be included
MathOperation addition = (int a, int b) -> a + b;
Type declaration can be omitted
MathOperation subtraction = (a, b) -> a - b;
Lambda expression can contain return statement along with curly braces
    MathOperation multiplication = (int a, int b) -> {
          return a * b;
    };
Lambda as method argument:
We can pass both lambda expression as method arguments. For example, let’s consider a method:
  public static void callWithLambda(Greeting greeting, String message) {
    greeting.sayGreeting(message);
  }

We can call the above method like the following:
    callWithLambda(message -> System.out.println(message), 
          "Lambda argument pass test1");

Generic Functional Interfaces
Functional interfaces can be generic.
@FunctionalInterface
interface GenericInterface {
  void test(T param);
}
Lambda expression can associate with generic functional interfaces.
    GenericInterface genericInterface1 = (str) -> System.out.println(str);
    genericInterface1.test("Test generic interface with type string");
    
    GenericInterface genericInterface2 = (i) -> System.out.println(i);
    genericInterface2.test(5);
Method Reference:
There is a shortcut of using lambda expression. That is called method reference. It will make code even shorter. Double colon (::) is used as the syntax of method reference.
Greeting greetingLambda = message -> System.out.println(message);
Equivalent use of method reference
    Greeting greetingMethodReference = System.out::println;
    greetingMethodReference.sayGreeting("Hello from method reference");
Can be used as method argument also:
callWithLambda(System.out::println, "Lambda argument pass test2");
We can reference the following types of methods:
  • Static method:
    public static void defaultGeeting(String message) {
        System.out.println(message);
      }
    callWithLambda(LambdaTest::defaultGeeting, "Static method reference");
    
  • Instance method on parameter objects:
    Finder finder = (s1, s2) -> s1.indexOf(s2);
    
    By using method reference
    Finder finder = String::indexOf;
    
  • Instance method:
    StringConverter stringConverter = new StringConverter();
    
    Deserializer des = stringConverter::convertToInt;
    
  • Constructor:
    It is possible to refer a constructor of a class. We can do that by using ::new as like the following example. Here the functional interface is like
        public interface Factory {
                public String create(char[] val);
        }
    
    Using regular lambda
    Factory factory = chars -> new String(chars);
    
    Using constructor reference
    Factory factory = String::new;
    

References:

Saturday, January 26, 2019

SOLID Principles (part 2)

3. Liskov Substitution Principle: “Derived classes must be substitutable for their base classes. Objects should be replaceable with instances of their subtypes without altering the correctness of that program.” LSP is all about well designed inheritance.
  • An overridden method of a subclass needs to accept the same input parameter values as the method of the superclass. That means we can implement less restrictive validation rules, but we are not allowed to enforce stricter ones in our subclass. Otherwise, any code that calls this method on an object of the superclass might cause an exception, if it gets called with an object of the subclass.
  • Similar rules apply to the return value of the method. The return value of a method of the subclass needs to comply with the same rules as the return value of the method of the superclass. We can only decide to apply even stricter rules by returning a specific subclass of the defined return value, or by returning a subset of the valid return values of the superclass.
  • No new exceptions can be thrown by the subtype unless they are part of the existing exception hierarchy.
  • We should also ensure that Clients should not know which specific subtype they are calling, nor should they need to know that. The client should behave the same regardless of the subtype instance that it is given.
  • New derived classes just extend without replacing the functionality of old classes.
One example of LSP can be found here .

There are situations where we can not apply LSP or subclassing. 3D Board game example of Head First’s ‘Object Oriented Analysis and Design’ book is good example of such case. When subclassing cannot be used, we have several other options to solve the problem:
  • Delegation: When we handover the responsibility of a particular task to another class or method (Using concrete class).
  • Composition: Allows us to use behavior from a family of other classes and to change that behavior at runtime (Using interface or abstraction). In composition, the object composed of the other behaviors owns those behaviors. When the object is destroyed, so are all of its behavior. The behaviors do not exist outside of the composition itself.
  • Aggregation: When one class is used as part of another class, but still exists outside of that other class. We we want the benefits of composition, but we are using behavior from an object that exist outside of our project, we use aggregation.

4. Interface Segregation Principle: “Clients should not be forced to depend upon interfaces that they do not use.”

Instead of one fat interface, many small interfaces are preferred based on groups of methods with each one serving one sub-module.

Similar to the Single Responsibility Principle, the goal of the Interface Segregation Principle is to reduce the side effects and frequency of required changes by splitting the software into multiple, independent parts.

One example of ISP can be found here .

5. Dependency Inversion Principle: “Depend on abstractions, not on concretions.”
  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.
  • An important detail of this definition is, that high-level and low-level modules depend on the abstraction. the high-level module depends on the abstraction, and the low-level depends on the same abstraction.

One example of DIP can be found here .

References:

Friday, January 25, 2019

SOLID Principles (part 1)

SOLID, an acronym for five design principles, was first introduced by Michael Feathers. The principles are a subset of many principles promoted by Robert C. Martin (“Uncle Bob”).

SOLID Acronym
  • Single Responsibility Principle (SRP)
  • Open closed Principle (OSP)
  • Liskov substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

1. Single Responsibility Principle: “A class should have one, and only one, reason to change.”

Every module/class should have the responsibility over a single portion of the functionality provided by the overall system/software, and that responsibility should be entirely encapsulated by the class.

When new requirements will be introduced, the code has to undergo some changes, meaning that the classes have to be modified. The more responsibilities a class will have, the more change requests it will get. And it will be harder to implement those changes.

In Single Responsibility Principle, each class and module should focus on a single task at a time. Everything in the class should be related to that single purpose. There can be many members in the class as long as they related to the single responsibility.

One example of SRP can be found here.

2. Open/Closed Principle: “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”

There are many ways we can apply OCP. The easiest way to apply OCP is to inherit the original class and implement the new functionality on that new derived class.

But, inheritance can introduce tight coupling if the subclasses depend on implementation details of their parent class. That’s why Robert C. Martin and others redefined OCP to the Polymorphic OCP. It uses interfaces instead of superclasses to allow different implementations which you can easily substitute without changing the code that uses them. The interfaces are closed for modifications, and you can provide new implementations to extend the functionality of your software.

One example of OCP can be found here .


References:

Friday, August 17, 2018

Learning the Spring Expression Language (SpEL)


"The Spring Expression Language (abbreviated as SpEL) is a powerful expression language. Within the Spring portfolio, it serves as the foundation for expression evaluation. It supports querying and manipulating an object graph at runtime. It can be used with both XML-based and annotation-based Spring configurations and bean definitions. Since it is capable of assigning value dynamically at runtime, it can save us a lot of code." ... ... ...


The article written by me was published in DZone on 10 August, 2018. To read the full article, please use the following link:
Learning the Spring Expression Language (SpEL)


Thursday, July 19, 2018

ApplicationContext of Spring

Context
Context is the larger surrounding part which can have influence on the current unit of work. It can be the running environment, the environment variables, instance variables, local variables, state of other classes etc. For example, ServletContext represents the servlet’s environment within servlet container. Similarly, ApplicationContext represents Spring’s environment within Spring container. More examples of context are JSF's FacesContext, Android's Context, JNDI's InitialContext etc. The context implementation usually follow the Facade Pattern which hides the complexities of the larger system and provides a simpler interface to the client.

ApplicationContext
The ApplicationContext is the central interface of Spring application. It provides configuration information to the application. It is read-only at run time, but can be reloaded if necessary. A number of classes implement the ApplicationContext interface, allowing for a variety of configuration options and types of applications.

ApplicationContext is the context initialized by ContextLoaderListener that we define in our application’s web.xml file. There will be only one application context per web application. We can explicitly declare the context configuration file name in web.xml using the contextConfigLocation param. Otherwise, Spring will search for the file applicationContext.xml under WEB-INF folder. The configuration would look something like this:
 
<listener>    
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
In the above configuration, we are using the file root-context.xml and Spring will create an ApplicationContext from it.

WebApplicationContext
WebApplicationContext is the servlet specific context. Each DispatcherServlet is associated with a single WebApplicationContext. Dispatcher servlets are also configured in the application’s web.xml file. Each dispatcher servlet can be initialized from <servlet-name>-servlet.xml file, which is the default file name pattern.  Multiple DispatcherServlets allow us to categorize the incoming requests based on the url-pattern of servlet and handle them accordingly. For example, one dispatcher servlet can help serving the web pages via Controller, while another servlet can be used to implement a stateless REST web service.
To change the configuration file of dispatcher-servlet, we can use init-param with contextConfigLocation as param-name, like the following:
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/sample-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
    
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
In the above configuration, Spring will not find dispatcher-servlet context file with the name mvc-dispatcher-servlet.xml, but it will look for the file name sample-dispatcher-servlet.xml because it is specified as the init-param value for contextConfigLocation. 

Difference between ApplicationContext and WebApplicationContext
ApplicationContext is the root-context, which has bean configurations that can be used across the entire application as singletons. There is always a single application context in a web application. But, there can be multiple WebApplicationContexts for each of the dispatcher servlets that we specify in application’s web.xml.
It’s always better to keep a clear separation between middle-tier services and web-related components.  Middle-tier services like business logic components and data access classes are preferred to be defined in the ApplicationContext. Web-related components such as controllers and view-resolvers are preferred to be defined in the respective dispatcher-servlet‘s WebApplicationContext.

References 
http://www.jcombat.com/spring/applicationcontext-webapplicationcontext
https://spring.io/understanding/application-context
http://codesenior.com/en/tutorial/Spring-ContextLoaderListener-And-DispatcherServlet-Concepts
https://schoudari.wordpress.com/2012/07/23/purpose-of-contextloaderlistener-spring-mvc/
https://stackoverflow.com/questions/11815339/role-purpose-of-contextloaderlistener-in-spring