Friday, 22 February 2013

SOLID - OOPS

Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion.

Single responsibility principle
    an object should have only a single responsibility.

Open/closed principle
    “software entities … should be open for extension, but closed for modification”.

Liskov substitution principle
    “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”. See also design by contract.

Interface segregation principle
    “many client-specific interfaces are better than one general-purpose interface.”

Dependency inversion principle
    one should “Depend upon Abstractions. Do not depend upon concretions.”
    Dependency injection is one method of following this principle.

Sunday, 17 February 2013

Spring key points

IOC or inversion of control / DI or dependency injection?
                 This Spring interview question is first step towards Spring framework and many interviewer starts Spring interview from this question. As the name implies Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.
Example:
  <bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">
        <property name="newBid"/>
  </bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.
------------------------------------------------------------------------------------------------------------
AOP?
      The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP is a programming technique that allows developer to modularize crosscutting concerns,  that cuts across the typical divisions of responsibility, such as logging and transaction management. Spring AOP, aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation
Jointpoint?
    A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.
Advice?
    Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.
Pointcut?
    A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.
------------------------------------------------------------------------------------------------------------
Core container module?
       This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.
------------------------------------------------------------------------------------------------------------
Application context module?
       The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

OOPs

The four main concepts are involved in OOP:
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Abstraction is hiding of information from others. In case of Java, its hiding implementation of a method/ object. For example if an interface is available to outer world, so end user won’t know about implementing class details. This is just a kind of abstraction. Abstraction could be anywhere in java, wherever we hide some information, we call it abstraction.
Encapsulation is combining data and method along with implementation hiding within the class. Implementation hiding is done with the help of access modifiers (public, protected, package, private).
Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. Although inheritance may sometimes imply (especially in Java, where the keyword for inheritance is extends) that you are going to add new methods to the interface, that’s not necessarily true. The second and more important way to differentiate your new class is to change the behavior of an existing base-class method. This is referred to as overriding that method.
Polymorphism is something like one name many forms. Polymorphism is also known as dynamic binding or late binding or run-time binding.

---------------------------------------------------------------------------------------------------------------------------
Inheritance?

Definition 1:
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes.
Definition 2:
Inheritance means to acquire property of others. It also means that we can use code of other functions and methods. Means Code reusability. In this object are defines by classes that are super class and which classes uses property of that class is known as sub class. It is very useful in Object Oriented Languages.
-------------------------------------------------------------------------------------------------------------------------
What is Association?
Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

   
public class MyMainClass
{
 public void init()
  {
    new OtherClass.init();
  }
}
-------------------------------------------------------------------------------------------------------------------------
What is Aggregation?

Aggregation has a relationship between two classes. In this relationship the object of one class is a member of the other class. Aggregation always insists for a direction.
   
public class MyMainClass
{
  OtherClass otherClassObj = new OtherClass();
}
-------------------------------------------------------------------------------------------------------------------------
What is Composition?
Composition is a special type of aggregation relationship with a difference that its the compulsion for the OtherClass object to exist for the existence of MyMainClass.

import java.util.ArrayList;

public class Aggregation
{
 public static void main(String[] args)
  {
    MusicPlayer player = new MusicPlayer();
    Car car = new Car();
    car.addPlayer(player);
  }
}

Serialization

1) A class should implement java.io.Serializable interface. (gives compiler an indication)
2) SerialVersionUID JVM generates its based upon structure of class which depends upon interfaces a class implements and several other factors. SerialVersionUID is used for version control of object. serialVersionUID mismatch leads to java.io.InvalidClassException.
3) Externalizable - Flexibility to control the serialization. using right/readExternal()
4) serializing not include some of the members can be achived using static variable or transient variable.
5) Custom serialization are possible, But should take care of Provate methods, Overloading and overriding, Since the private methods reading possible only from JVM, Still what is the need for custom serialization.
6)  To avoid java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.

Monday, 11 February 2013

Java 1.7 features.

    1) JDBC 4.1 more efficient introduced with the following features:
        The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement
        RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver.
    2) String objects can be as Switch literals.
        case "ONE": sop("one"); break;
    3) Automatic Type referece during Generic instance creation.
        Map> sample = HashMap<>(); 
        <> - operator called as diamond operator.
    4) try statement defining resources. No need of finally method to close this resources.
        try(file reader){
            return (readline)
        }
    5) Catch block to handle multiple exceptions.
        catch( arrayourofboune | numberformatexception | ex)
        since we cant use the main exception with in multple exception.
    6) JVM enhancement.

    7) IO - Zip File System Provider, Custom file system provider, java.nio.*, etc

Sunday, 9 December 2012

String Vs StringBuffer Vs StringBuilder

String is immutable while StringBuffer and StringBuilder is mutable object.

StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.


Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.


Criteria to choose among String, StringBuffer and StringBuilder(Simple)

          Use String if you require immutability, 
          Use Stringbuffer in java if you need mutable + threadsafety 
          Use StringBuilder in Java if you require mutable + without thread-safety.

Criteria to choose among String, StringBuffer and StringBuilder(Explained in detail)
          If your text is not going to change use a string Class because a String object is immutable        
          If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
          If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Monday, 9 April 2012

WSDL.

    Web Services Description Language is an XML format for describing Web services. WSDL enables one to separate the description of the abstract functionality offered by a service from concrete details of a service description such as "how" and "where" that functionality is offered.
    - Data type information for all message requests and message responses
    - Binding information about the transport protocol to be used
    - Interface information describing all publicly available functions
    - Address information for locating the specified service

Operation patterns supported by WSDL.      One way
          The service receives a message.
     Request - Response
          The service receives a message and sends a response.
     Solicit - Response
          The service sends a message and receives a response.
     Notification
          The service sends a message.

Java - Annotations - Reflection

A Metadata Facility for the Java Programming Language.

Built-in Annotations in Java:
             @Override
                          Essentially tells to the compiler that method must be an overridden method. If not, then the compilers can report them as errors
             @SuppressWarnings
             @Deprecated

User-defined Annotations:
             Things that we need to consider while creating user defined annotation is as follows. (the same will be used for all annotations)
             Target Annotation
                              @Target(ElementType.METHOD) (Constructor, Field, Type, etc)
              Retention Annotation
                             @Retention(RetentionPolicy.CLASS) (Source Code, Class file, Run-time)

Reflection:
               Information related to Annotation types using Reflection(java Reflection API) for any type of java elements like class, interface, method, variables, etc.

UML - Class diagram.

 - The class diagram is a Static diagram.
 - Visualizing, documenting and describing different aspect of a system.
 - Shows collection of classes, interfaces, associations, collaboration and constrains.

Purpose.

 - Analysis and design of the state view of an application.
 - Describe responsiblities of a system.
 - Base for component and deployment diagrams.
 - Forward and reverse engineering.

Type of Uml diagrams.

 - Structural Diagram.
 - Class Diagram.
 - Object Diagram.
 - Component Diagram.
 - Deployment Diagram.
 - Behavior Diagram.
 - Use case diagram.
 - Sequence Diagram.
 - Collaboration Diagram.
 - Statechart Diagram.
 - Activity Diagram.

http://www.tutorialspoint.com/uml/uml_class_diagram.htm

ArrayList vs LinkedList

Both implements List interface.

       1) ArrayList is implment re sizable array.
       2) LinkedList is implment doubly Linkedlist.

Difference.

       1) Data structure of both is different.
       2) ArrayList - Getting and searching operation is fast(Getting from array index), Where remove opeation is too costly since it require rearrange all the index.
       3) On linkedList we need to iterate through all elements, Does not provide random or indexed base access.
       4) Insertion are very easy in Linkedlist since its not reuqire to rearranging an index.
       5) Linkedlist is more over head then arraylist, Since the node have data and address of the next and previous data.

When to use LinkedList:

                Since application inserts or remove more than retrieval then Linkedlist  is better option.
                If application can live with out random data access then Linkedlist is better option.

Friday, 23 March 2012

difference builder Vs decorator pattern

Builder 
         Sequence of steps to construct an object
             -During creation.
             -Elements are must.
             -If its fails object incomplete.

Decorator pattern
         On constructed Object adding extra/more functionality.
             -After object created.
             -Elements are optional.
             -It will not affect the basic behavior.
            -Allows new/additional behaviour to be added to an existing object dynamically. 

Wednesday, 22 February 2012

Performance Improvement - Java

DURING DESIGN APPLICATION:
1) Excessive logging
              Use log into buffer and write at the end.
              Use async logging for better performance.
              Use framework like log4j, SLF4J. 
              Don't use System.err, System.out - There is no way to turn it off. 

2) Incorrect application server configuration.
               Use appropiate heap size based on JVM.
               Use proper thread pool, connection pool, connection time, child connection settings, logger levels, etc.

3) Incorrect usage of Java EE
             
4) Improper usage of caching.
               What is the cache hit ratio?
               How much memory the cache take?
               How performance testing with respect to cache? Is it disabled?
               Can cache monitored / managed at run time? (No of objects in cache, hit ratio, amount of memory used, enable/disable cache, flushing the content, etc).
               Use cache if and only if caching is needed.
               Verify the functional and performance behaviour of your cache with performance tests.
               Make sure your cache can be managed and monitored at runtime.

5) Excessive memory usage

6) Badly performing libraries               
  • without checking whether that library is really needed (and does not overlap with functionality already offered by other libraries used),
  • without checking whether that library can offer good performance or whether a better performing alternative is available,
  • without defining how the library is going to be used within the application.
DEPLOYMENT:
Environment tunning, Like tomcat tunning on Memory, thread, Time to live, etc.
    Few other options you should be aware of during Environment tunning:
  1. Add the -server option to the JVM options for Tomcat, which should result in better performance for server applications. Note that this option, in some cases, causes the JVM to crash for no apparent reason. If you face this problem, remove the option.
  2. Minimize logging in Tomcat by setting debug="0" everywhere in <Tomcat>/conf/server.xml.
  3. Remove any unnecessary resources from the Tomcat configuration file. Some examples include the Tomcat examples Web application and extra <Connector>, <Listener> elements.
  4. Set the autodeploy attribute of the <Host> tag to false (unless you need any of the default Tomcat applications like Tomcat Manager).
  5. Make sure you have set reloadable="false" for all your Web application contexts in <Tomcat>/conf/server.xml.
Database tunning. Size, ram, no of connection, etc.

Application tunning, Like code optimization, SQL query optimization, Sql profiler, etc
  1. Avoid using synchronized block in the code.
  2. Classes, Methods, Variables - where every possible use final variable.
  3. provide proper logging to help dubugging. 


Thursday, 16 February 2012

Builder Vs Factory

Builder - Create another object of specific type over several steps.
Builder - Holds the needed state for the target iteam at each step.
Example: When you ask for Car it will give Hond with 4 Cylnder or Honda with 6 cylnder engine or Maruthi.
Example: Make a loan object, There are several loans(education, personal, car, house) and intrest rates are different, So the final object is created with Step by step process.


Factory - Create another object of specify type in one step.
Example: When you ask for Cat it will give Honda or Maruthi.
Example: When there is a super class and 'N' number of subclass, Depends on the parameter the object will create and return.

Wednesday, 15 February 2012

List of Available Design Patterns - GOF.

Creational Design Pattern
1) Abstract Factory pattern
2) Builder pattern
3) Factory pattern
4) Prototype pattern
5) Singletone pattern

Structural Design Pattern
1) Adapter
2) Bridge
3) Composite
4) Facade
5) Flyweight
6) Proxy

Behaviroral Design Pattern
1) Chain of responsiblity
2) Composite
3) Interpretor
4) Iterator
5) Memento 
6) Observer 
7) State 
8) Strategy 
9) Template Method 
10) Visitor 

Monday, 13 February 2012

SOA and ESB

SOA is an architectural model for implementing loosely coupled service based applications. ESB is a piece of infrastructure software that helps developers to develop services, and communicate between services through suitable APIs.

SOA Service should be stateless. It may have a context within its stateless execution, but it will not have an intermediary state waiting for an event or a call-back. The retention of state-related data must not extend beyond a request/response on a service. Because state management consumes a lot of resources, and this can affect the scalability and availability that are required for a reusable service.

Pitfalls of SOA; One of the most common pitfalls is to view SOA as an end, rather than a means to an end. Developers who focus on building an SOA solution rather than solving a specific business problem are more likely to create complex, unmanageable, and unnecessary interconnections between IT resources.
Another common pitfall is to try to solve multiple problems at once, rather than solving small pieces of the problem. Taking a top-down approach—starting with major organization-wide infrastructure investments—often fails either to show results in a relevant timeframe or to offer a compelling return on investment.


ESB can be used as a platform on which SOA is realized. ESB is only the medium through which the services flow. ESB provides facilities for the composition and deployment of services, which in turn implement the SOA. Also ESB provide "Any to Any" connectivity between the services with in application.

Wednesday, 8 February 2012

Decorator Design Pattern

Type of Structural Pattern:

Purpose: Add additional responsibilities dynamically to an object.

Adapter Vs Decorator: Adapter changes the object interface it self, But the decorator does not change the object it will add aditional responsiblity to it.

Key:
1) Decoration adds functionality to objects at runtime which would make debugging system functionality harder.
2) Decoration it is also possible to remove the added functionalities dynamically.

Software Design Principles

3 important characteristics of a bad design that should be avoided:
  1. Rigidity - It is hard to change because every change affects too many other parts of the system.
  2. Fragility - When you make a change, unexpected parts of the system break.
  3. Immobility - It is hard to reuse in another application because it cannot be disentangled from the current applications.
Open Close Principle:
Open for extension and close for modification.

Interface Segregation Principle:
Clients should not be forced to depend upon interfaces that they don't use.

Single Responsibility Principle:
A class should have only one reason to change.

Liskov's Substitution Principle:
Derived types must be completely substitutable for their base types.

Tuesday, 7 February 2012

Factory Design Pattern

Type of Creational DP.

Singleton Vs Factory.
            Singleton always returns you a same object, But factory returns to a new and requested/difference objects.

key-point:
              creates objects without exposing the instantiation logic to the client.
              refers to the newly created object through a common interface

How it works:
              1) Client need a object, Instand of creating using new operator it will ask factory object to give a new Object,
              2) The factory instantiates a new concrete product and then returns to the client the newly created product.
              3) Client uses the products as abstract products without being aware about their concrete implementation

Observer Design Pattern.

Observer Design Pattern used whenever a subject changes has to be observed by one or more observers.

Example domain usages: Stocks, Weather reports, News providers and Score providers, etc.

loosely coupling: Change of a state in one object must be reflected in another object without keeping the objects tight coupled.

Key problems
  1. Many Observers to Many Observables.
  2. We can have either push or pull method data transfers.
  3. When many Onververs and Observables comes we may need to introuduce new logic object responsible(ChangeManager) 
    1. Encapsulate the logic of notify the observers
    2. Maintain the many to many relations
    3. Receive the notifications from subjects and delegate them to the observers
Factory, Mediator and Template pattern can be used with in this design patterns.

Monday, 6 February 2012

Singleton Design Pattern.

When to use Singleton: Singleton is used there must be one instance of the class. And it must be accessable to clients from global point.

Example usage of Singleton: Logger object, Configuration object, Cache object, Properties Object, Factory methods are used Single ton, etc..

Problems of singleton:      
          1) Multi-thread safe. ( method level it self)
          2) Lazy installation using double  locking machanism, (Synchronized inside the getInstalnce() method)
          3) Early installtion method.
          4) Serialization. (serializable(), readResolve())