Wednesday, August 7

Sapient is hiring again !

            

Attention technologists in the financial, capital and commodities industry… Sapient Global Markets is on a recruitment spree! If you're interested in being a part of the future of technology in this domain, apply for our current openings at www.sapientglobalmarkets.com/careers


OR


send me you resume at      manojbharal@gmail.com

   



Lambda Expression in Java 8


LIGHT... CAMERA... ACTION...

ARGUMENT.. ARROW.. EXPRESSION..

You just learnt the syntax of Lambda expressions

Simplest lambda expression could be

()-> system.out.println("expression");

() is argument . Here we are passing no argument . So if there is no argument () is the way to define empty argument

system.out.println("expression") is expression . Expression is nothing but the body of the lambda expression. Here arguments can be used in various body statements

For example

(a,b)->a+b;

(a,b) is argument here . a+b is expression.


lambda expression are also called anonymous methods. Lambda expressions follow scala type of syntax .

Why do we need these?

These expression add functional edge to the language. Let's try to understand that with an example

Before that let me make an statement -

An interface having only one method is called functional interface.

You might have written anonymous class using Runnable ,ActionListener interface . For example :



Public class Engine {

public static void main(String args[]){

new Thread(new Runnable(){
       public void run()
       {
       int count=10
                while (count>0){

                System.out.println(count);
                COUNT--;
       }
}).start();

 }

in above code we are using Runnable interface an anonymous class.

How to replace anonymous class code with lambda expression ?



Public class Engine {

public static void main(String args[]){

new Thread(()->{
     
       {
       int count=10
                while (count>0){

                System.out.println(count);
                COUNT--;
       }
}).start();

}

What is different here. new Runnable , public void run  is not there is this code. But this works fine

This is done because compiler understand that Thread class implement Runnable interface and there is only one method run() in that class.

So to execute only method of interface We can straight away write the code without interface name and method name. So it seems like anonymous method. That's how we can use lambda expression to replace all anonymous class.


Let's take another example


public class Customer{

isCustomerValid(
    roster,
    new ValidateCustomer() {
        public boolean test(Customer cust) {
            return cust.getCountry() == Customer.COUNTRY.US
                && cust.getPoint >= 10
               
        }
    }
);

}

In isCustomerValid method ValidateCustomer is anonymous class.

Now consider ValidateCustomer interface is like :

interface ValidateCustomer{
test(Customer cust);
}

This is functional interface. So we can use lambda expression for this just like below code

public class Customer{

isCustomerValid(
    roster,
    (Customer cust) ->
            cust.getCountry() == Customer.COUNTRY.US
                && cust.getPoint >= 10
               );
 }


So lambda expression is a good way to use functional anonymous method as an argument .

Monday, August 5

Delegation Design Pattern

Delegation design pattern is used by multiple classes to work collaboratively. Java emphasizes on principal of single responsibility i.e. One class should maintain code only for one specific business responsibility For example An Customer class should be responsible only for managing customer data If it starts managing the customer Orders as well It violates the principal of single responsibility. 

So we tend to segregate our overall business logic in multiple classes . Now to work in network of classes All classes need to talk to each other . If customer has to place an order it needs help of Oder class . 

Now one way to attain the capability of using Order class features in Customer class is  inheritance . Customer class may extend Order class. But Orders is not the only class Customer class is dependent on ,there are many other features that customer require , It will ask for billing of the orders. So there would be a BillManager class. Now java supports only single inheritance So you can not extend more than one class. 

What could be the other way of achieving this . You could use multiple inheritance through interface. Implementing multiple interfaces and writing their corresponding implementation classes might help in achieving the same. But would it be possible in every case to write an interface for every class Customer class is dependent on. While writing code from scratch you might provide this implementation But most of the time people have to work on existing code and there you might not have the scope of redesigning the overall class collaboration. 

So what option is left with us which we can use quite flexibly in new and well as existing code. 

Delegation design pattern provides a way of of managing this collaboration. Delegation says One class should not do everything. Customer class should use Order class code by delegating that responsibility to Order class. Customer class will create an instance of Order class to provide required object state and then on that instance will invoke methods written in Order class. Now there is no direct dependence among classes the way it was required in case of inheritance  This is very clean and loosely coupled way of achieving collaborative functionality. So sharing responsibility to other classes is Delegation and this is one of the java programming design principal . 

When to use static members in java

                               When to use statics 

Statics should be used when you don't want to have varying behavior for different objects. 

Statics should be used when data is not instance dependent and for all existing instances of static member you want to apply same state.

Statics should not be used at all If they are not actually required as they create dependencies and references to other classes and class loader in JVM and stay in memory for long time. So they are not considered for garbage collection once they are done with current work Instead they are de-referenced with their loading classes as they maintain a reference to static classes

If you need to access the data only in few instances then it is better to create stateful instance at runtime Instead of choosing static design . So whether to use static or not is very cautious design decision .

Static declaration is kind of situation similar to singleton design pattern where you don't want  lot of different instances for different client calls instead it is same single instance that caters to call. 

Static should be used for the methods where you have mostly utility methods in the class and we hardly need to maintain any object state to achieve the required action. Math class is full of static methods .All methods in class are utility methods and It is very logical to declare them static. 

Should a method of class be invoked before it's any of the available constructor is called? If yes, is the answer because it hardly matters for our functionality If constructor is invoked or not , then it's good to use static method . But again one need to know how much is the volume of client programs who would actually use that . 

So summarizing a bit static methods can be used when : 

1 for utility classes that will remain as it is .
2.Methods being declared static have no dependency on instance data
3.Some data required to be shared among multiple instances SO instead of creating them every-time , create once and share among all .
4. Static methods can not be overridden . So keep in mind So can't apply more specific behavior on static method with overriding technique.

While writing unit test cases you can not mock up the static data differently for a specific instance And you are sharing the same data across multiple instances. 

One argument is We can also use singleton instead of static class . But should we do that or not can be very good design consideration. Static members resides at perm Gen in memory space while singletons  resides on heap . So statics stay in memory till the containing program is not unloaded while singletons gets garbage collected regularly So that could give good preference to singleton wherever possible instead of using statics.

One good rule of java we need to keep in mind is that static method can not invoke non-static method directly . It is must for them to create instance of class enclosing non-static member and then invoke method or access variable using that . So that should be another part of our thought process while designing static classes

Also analyze how static method will behave differently in case of multi-threaded environment and code Synchronization cases. Static method will take lock on class to block the access to all synchronized static methods of the class.

Static modifier is preferred to declare constant variables in a class As they never depend on instances instead are declared once as final values and used forever everywhere.



Sunday, August 4

Permanent generation removed from JDK 1.8

.....................................................
Permanent generation and JDK 1.8 


Breaking News 

Permanent generation will be completely removed from jdk8.0 . Yes there won't be any permanent generation.

So the essential need to tune the performance of permanent generation space will also be eliminated. 

And the data that currently exist in permanent generation will be moved to Java heap or native memory. 

What does currently lie in permanent generation block?

class metadata , intern Strings ,class static variables . And all these will be moved from here to heap or native memory. Thus there will be significcant change in garbage collection mechanism

Saturday, August 3

All about annotations in java

                      All about  annotations in java 

What is annotation ?

Annotation is introduced in java 1.5. It is used to apply meta information on source code in source code file itself

What is the purpose of annotation ?

Annotation help in providing meta information to code source file at as per desired Retention 
policy

What is retention policy?

Retention policy defines at what time do we want to apply the meta information in our source code. Java provides three different levels of applying meta information.
1. SOURCE
2. CLASS
3. RUNTIME 

Source : Meta information is applied at in source code only. At compile time and runtime it won't be available 

Example : @override , @suppress warning

CLASS : Meta information is applied in .class file i.e. bytecode 


RUNTIME : Meta information is applied at runtime .

Example : @deprecated

What is the advantage? 

It helps binding meta information with source code itself with required control . 
It removes dependency on xml file . Annotation replaces XML. Yes , Annotation can be used to apply the same meta information on source what earlier used to be done by XML 

Are there some in built annotation in java?

Yes there are For Example:

 : @Suppress 
   @override
   @deprecated

What is basic syntax of annotation ? 

at minimum it requires combination of @ and interface 

For example 

public @interface myAnnot{
}

Here myAnnot is the annotation defined. This much is sufficient to define a well qualified complete annotation.

How do we apply an annotation?

If you have seen some code written java 1.5 onwards you might have seen something like 


@Override
void mySuperMethod() { ... }


What is @override doing here. This is an annotation saying that this method is overridden. And if any override rule is violated It helps compiler is raising compilation error. If annotation won't have been there compiler would have completely ignored the error and we would have been in big time trouble at runtime. Identifying error at runtime can be very costly and very tedious task to identify.


Similarly 

@SuppressWarnings(value = "unchecked")
void myMethod() { ... }

@suppress annotation is basically instructing compiler to suppress the unchecked warning . After applying this compiler won't highlight any unchecked code warning.

Can we write our own annotation?
Absolutely. myAnnot above is an example of user defined annotation. 

Below is another example of annotation . We generally use this to with our source file.



@interface CodeInfor{
   String author();
   String date();
   String lastModified() default "mycompany";
   String lastModifiedBy() 
  }

What are the rules that are applied on annotations?

 annotation is defined using interface as keyword preceding with @ special character.


Can annotation be applied on another annotation?

Absolutely. @Retention is an example of that . This is discussed above

other useful annotations that are applied on other annotations are : 

@Documented ,
 @Target,@Inherited , 
@Repeatable 

@Target defines at what type this annotation will be applied for example :

constructor 
field
method
parameter

With that we can define at what part of the code a specific annotation should be applied.

Java provides extensive API to identify what annotations are applied at a specific class , method , constructor, variable or parameter.