Sunday, December 4, 2016

Management lesson from The Bridge Riddle

Most of us come across the Bridge Riddle sometime before, it is all about optimizing time to cross the bridge. Here is the riddle

You, an assistance, a jenitor and a scientist have to cross a wooden bridge in 17 minutes. The bridge is weak and only able to carry the weight of
two of them at a time. Because they are in a rush and the light is
fading they must cross in the minimum time possible and must carry a
torch (flashlight,) on each crossing.

They only have one torch and it can’t be thrown. Because of their
different fitness levels and some minor injuries they can all cross at
different speeds. You can cross in 1 minute, assistance in 2 minutes, the janitor
in 5 minutes and the scientist in 10 minutes.

Below TED Ed video explains and solve this riddle

As explained in the video the key decision is to reply on the assistant who is comparatively less efficient than “You”, the assistant takes double time to cross the bridge than “You”. The assistant is taken first to other end and kept on other end so that he/she can come back with torch to pick up “You” to pass the bridge with time.

So what is management learning here ?
What I have learned from the solution is that even if you are key performer of the team it is worth passing responsibility to other team member for optimal team performance. It is not necessary to take responsibility of each thing on you considering no one can do it better than you.

Tuesday, April 12, 2016

All about Java stream collect offering

Lets start with a problem statement “Provided collection of employees, we need to find average, max and min age of employee by county”

public static void avgMaxMinEmployeeAgeByCounter() {
    String AVG = "AVG";
    String MAX = "MAX";
    String MIN = "MIN";
    String SUM = "SUM";
    String COUNT = "COUNT";

    List<Employee> employees = Employee.EMPLOYEES;//LIst of all employees, pojos
    // Mapping country name to average, max, min age of employee
    Map<String, Map<String, Double>> summary = new HashMap<>();

    for(Employee e: employees) {
            Map<String, Double> map = summary.get(e.getCountry());
            map.put(SUM, (map.get(SUM) + e.getAge()));
            map.put(COUNT, map.get(COUNT) +1);
            map.put(MAX, map.get(MAX) < e.getAge() ? e.getAge():map.get(MAX));
            map.put(MIN, map.get(MIN) > e.getAge() ? e.getAge():map.get(MIN));
        } else {
            Map<String, Double> map = new HashMap<>();
            map.put(AVG, Double.valueOf(e.getAge()));
            map.put(MIN, Double.valueOf(e.getAge()));
            map.put(SUM, Double.valueOf(e.getAge()));
            map.put(COUNT, Double.valueOf(1));
            summary.put(e.getCountry(), map);
    //Printing result
    Set<String> keySet = summary.keySet();
    for(String country: keySet) {
        System.out.println("\t Average "+summary.get(country).get(SUM)/summary.get(country).get(COUNT));
        System.out.println("\t Max "+summary.get(country).get(MAX));
        System.out.println("\t MIN "+summary.get(country).get(MIN));

Output ::
    Average 31.8
    Max 45.0
    MIN 25.0
    Average 30.0
    Max 30.0
    MIN 30.0

We have been writing so many lines of code till Java 8 stream API. Whole perceptive of providing solution for a problem has changed now. Instead of imperative way, Java 8 stream API gives of flexibility of declarative programming. Just let the machine know what you want, instead of giving instructions to how to get it calculated. Considering above problem, we need NOT to instruct how to perform group by, calculate min , max or average.

Lets see how can we solve same problem using Java8 stream’s collect operation

Map<String, DoubleSummaryStatistics> collect = Employee.EMPLOYEES
    .collect(Collectors.groupingBy(Employee::getCountry, Collectors.summarizingDouble(Employee::getAge)));

collect.keySet().stream().forEach(country-> {
    System.out.println( "\t Average - " + collect.get(country).getAverage());
    System.out.println( "\t Max - " + collect.get(country).getMax());
    System.out.println( "\t Min - " + collect.get(country).getMin());

Average - 30.0
Max - 30.0
Min - 30.0
Average - 31.8
Max - 45.0
Min - 25.0

We can see no of code lines reduces to less than half. Here API of interest is ‘collect’, it is called terminal operation. The argument passed to collect is an object of type java What does a Collector object do? It essentially describes a recipe for accumulating the elements of a stream into a final result. The Collector provides many recipe to consolidate streams like

  • transform stream to list, set etc
  • grouping stream by any attribute
  • Partitioning
  • multiple grouping
  • summarizing

In above example, we are using Collectors.groupingBy to group the stream of employees by first country and then summarizing each of group of records to find average, min, max. Its so simple !!

I have gone through most of the “collect” offering and applied to typical grouping/summarizing problem. For example

  • Employee count by country or city
  • Get employee name with highest salary in given country
  • Partition employee by employment mode by county

You can find complete code sample in my github repository

Sunday, March 13, 2016

Utilizing ES6 Generator

I am going through Mozilla documentation about the Iterator and Generator concept introduced in ECMAScript6. Here is the overview as per Mozilla JS guide

Processing each of the items in a collection is a very common
operation. JavaScript provides a number of ways of iterating over a
collection, from simple for loops to map() and filter(). Iterators and
Generators bring the concept of iteration directly into the core
language and provide a mechanism for customizing the behavior of
for…of loops.

This post is not about how it works, it is better explained at Mozilla JS guide.

I have tried to apply the JS generator for one of the our day to day code. I think it is better suitable for lazy traversing and evaluating each item and proceed further if required. A common example comes in my mind is the tree traversing. I have implemented Depth First Search ( pre-order) using generator.

Consider the scenario where you need to traverse the tree node, evaluate/process the node and go further for next node. The code is as simple as below

var tree = getTree();
for (let node in tree.dfs()){
    // process node.

Isn’t above code super simple to understand, all traversing code it hidden, no need to manipulate the index/pointer etc.

Here I wrote simple traversing code that uses generator that return each node one by one.

function constructTree(values) {    
    return {
        dfs: function* (index) {
            if (!index) index = 0;
            yield values[index];
            if((2 * index + 1) < values.length)
                yield* this.dfs(2 * index + 1);
            if((2 * index + 2) < values.length)
                yield* this.dfs(2 * index + 2);


var tree = constructTree(values); 
for (let val of tree.dfs()) { 
   //process val

Here I am expecting the tree structure in an array. You can notice new syntax has been introduced function* to represent iterator/generator for the given JS object.

A generator is a special type of function that works as a factory for
iterators. A function becomes a generator if it contains one or more
yield expressions and if it uses the function* syntax.

The complete example is available at fiddle

Sunday, September 13, 2015

Looping & Closure

Here is simple code to dynamically create set of buttons that greet in different languages.

document.body.onload =  createButtons;
function createButtons() {
    var greetings = [
        {lang:'English', msg:'Good Morning !!'},
        {lang:'German', msg:'Guten Morgen !!'},
        {lang:'French', msg:'Bonjour !!'},
        {lang:'Finnish', msg:'Huomenta !!'}
    for(var i=0;i<greetings.length; i++){
        var greet = greetings[i]
        var input = document.createElement("button");
        input.setAttribute('class','btn btn-default btn-lg');
        input.onclick = function(event){

Pretty simple, looping through array of objects and adding buttons with language label and greet message in respective language as alert dialog on click action.
Here is the final html looks like

Multi-language greeting buttons

Many of you guys might already have understood the issue with above code. One can easily notice that all button greet you in ‘Finnish’.

Miss-matched greet message

Why ?
It is all because of onclick function has become ‘closure‘.

input.onclick = function(event){

It carries all the local variable that are in scope, here ‘greet’ object . As the value of ‘greet’ object change in every loop, all references in onclick callback closures also get same reference. So final reference in all the callback will be the last value of the greet in the loop.
I need not explains more about this typical problem, here is complete explanation available .

How to solve ?
One way to fix this issue by using functional scope. Lets wrap the callback function into another immediately invoked function with message as parameter. In this self invoked wrapper function with message as parameter, the callback function gets bind to wrapper function parameter , not the outside looping variable.

input.onclick = (function(msg){return function(event){

ES6 Way
ES6 has brought cleaner solution for this issue, let statement.

The let statement declares a block scope local variable, optionally
initializing it to a value.

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
In our script, we just need to use let statement instate of var while storing array object.

for(var i=0;i<greetings.length; i++){
        /*Using let instate of var*/
        let greet = greetings[i];
        var input = document.createElement("button");
        input.setAttribute('class','btn btn-default btn-lg');
        input.onclick = function(event){

So all our greet button are started displaying messages in there respective languages

enter image description here

Here is the complete code snippet,output

Friday, April 10, 2015

NPE as well as Null check free code ... Really ?

NPE as well as Null check free code … Really ?


Is this how your Java code review start ? NPE is always nightmare for a Java developer. Lets not discussion to much and jump on an usual Java code snippet

public interface Service {  
    public boolean switchOn(int timmer);
    public boolean switchOff(int timmer);
    //Other controls 
public class RefrigeratorService implements Service {
// ...
public class HomeServices {
    private static final int NOW = 0;
    private static HomeServices service;

    public static HomeServices get() {
        //Null Check #1
        if(service == null) {
            service = new HomeServices();
        return service;

    public Service getRefrigertorControl() {
        return new RefrigeratorService();

    public static void main(String[] args) {
        /* Get Home Services handle */
        HomeServices homeServices = HomeServices.get();
        //Null Check #2
        if(homeServices != null) {
            Service refrigertorControl = homeServices.getRefrigertorControl();
            //Null Check #3
            if (refrigertorControl != null) {

Above few lines of code snippet has multiple null checks, of-course to make it robust against all possible cases. Well that is necessary but is there any better way … ? It was so often that I uses Eclipse template to surround piece of code with if condition for null check

Eclipse template for NPE check

Is there any better way ?

Well Yes !!!.
Java 8 has introduced java.util.Optional<T> . It is a container that may or may not hold non-null value. Java 8 have given safer way to handle object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have home service factory that returns handle to multiple appliances available in the home. But these services may or may not available/functional, it means it may result NullPointerException. Instead of adding null if condition before using any service, let wrap it in to Optional<Service>.

Wrapping to Option<T>

Lets consider method to get reference of service from factory, instead of returning the service reference wrap it with Optional. It let the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    return Optional.ofNullable(s);

As you see Optional.ofNullable() provides easy way to get the reference wrapped. There are another ways to get reference of Optional , either Optional.empty() & Optional.of(). One for returning empty object instead of retuning null and other to wrap non-nullable object, respectively.

So how exactly it helps to avoid null check ?

Once you have wrapped reference object, Optional provide may useful methods to invoke methods on wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();

Optional.ifPresent invoke the given Consumer with reference if it is non-null value otherwise does nothing.

public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We user ternary operator very often for checking null condition and return alternative value or default value. Optional provides another way to handle same condition without checking null. Optional.orElse(defaultObj)returns defaultObj if the Optional has null value. Lets use this in our sample code

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;

Now HomeServices.get() does same thing but in better way. It checks whether the service is already initialize of not. If it is then return same or create new New service. Optional<T>.orElse(T) helps to return default value.

Finally here is our NPE as well as null check free code

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

    public static Optional<HomeServices> get() {
        service = Optional.of(service.orElse(new HomeServices()));
        return service;

    public Optional<Service> getRefrigertorControl() {
        Service s = new  RefrigeratorService();
        return Optional.ofNullable(s);

    public static void main(String[] args) {
        /* Get Home Services handle */
        Optional<HomeServices> homeServices = HomeServices.get();
        if(homeServices != null) {
            Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();

    public static void switchItOn(Service s){

Source :
Cartoon Image source :

Saturday, April 4, 2015

Java doesn't have "Diamond" problem : Really ..?

Java doesn’t have “Diamond” problem : Really ..?

We have been confidently telling that Java doesn’t have diamond problem even if it support multiple inheritance.

In object-oriented programming languages with multiple inheritance and
knowledge organization, the diamond problem is an ambiguity that
arises when two classes B and C inherit from A, and class D inherits
from both B and C.

But do you that the diamond problem is now there in newly introduced Java 8. It is because of the introduction of default methods in Interface. In Java8 Interfaces not only have method declaration but their default implementation. Any class implementing can either use default implementation from interface or provide its own implementation. Since Java class can implement multiple interfaces it is possible that two interfaces has same default methods, that brings diamond problem.

How do we overcome diamond problem ?

Consider following code snippet

public interface InterfaceA {
    default long calculateArea(long height, long width) {
        return height * width;
public interface InterfaceB {
    default long calculateArea(long height, long width) {
        return height * width;
public class ImplClass implements InterfaceA, InterfaceB {

    public static void main(String[] args) {
        ImplClass obj = new ImplClass();
        System.out.println(obj.calculateArea(10, 10));

Trying to compile this code, Java8 compiler throws errors

Duplicate default methods named calculateArea with the parameters
(long, long) and (long, long) are inherited from the types InterfaceB
and InterfaceA

Java8 compiler forces the implementing class to choose either of default implementations from Interfaces or provide its own implementation. The final code would be

public class ImplClass implements InterfaceA, InterfaceB {
    /* Compiler forces to provide implementation for ambiguous 
     * default methods from multiple imterfaces */
    public long calculateArea(long height, long width) {
        /*Programmer have option to either select one the default 
         * implementation
         * */
        //return InterfaceA.super.calculateArea(height, width);
        //return InterfaceB.super.calculateArea(height, width);
        //Own implementation 
        return height * width * 2;
    public static void main(String[] args) {
        ImplClass obj = new ImplClass();
        System.out.println(obj.calculateArea(10, 10));

Why do we need default methods…?

A default method is a method declaration and implementation, and it is
denoted with the default keyword preceding the declaration. Any class
that extends an interface containing a default method can choose to
implement and override the default implementation or simply use the
default implementation.

The default methods are being introduced to have additional methods in existing without breaking existing code base ( backward compatibility) .You can to add a new method to an existing interface without breaking backward compatibility with other code.Develop a default method (a.k.a. defender method) within the interface so that any classes implementing the interface are not required to provide an implementation of the new method.

Why now … ?

You must be thinking why do Java 8 needs to introduce the default methods, although this problem is there from very version of Java. The main motive could be introduction of Lambda expressions

lambda expressions are a convenient way to create anonymous functions.
They provide an easy way to create a single method interface using an
expression or series of statements. Lambda expressions are built upon
functional interfaces, which are interfaces that contain a single
abstract method.They can be applied in many different contexts, ranging from simple anonymous functions to sorting and filtering Collections. Moreover, lambda expressions can be as signed to variables and then passed into other objects.

Default methods were added in order to provide a way to change interfaces without breaking backward compatibility. Many interfaces needed to be changed to accommodate Java 8 API updates, and in doing
so, these interfaces would possibly break functionality of code that was written for prior releases of Java. By adding default methods to interfaces, engineers were able to add new functionality to existing interfaces without breaking the code that relied on those interfaces.

The main purpose of this post is to introduce ‘Default methods’ in Java8, but I though it would be interesting to start with this article with consequences. It is very fun fact that one of the base we defend Java over other OOPS languages like C++, it no more valid :)
So keep in mind that Java is not diamond problem proof.

Saturday, January 31, 2015

Overloaded function in Javascript

Coming from Java background, it is happened to be searched java language constructs while coding javascript. One of such construct is overloaded methods/function. Take a look following code snippet
//Normal sum
var intergerSum = sum(10, 20);
//Expecting item price sum
var objectSum = sum(
  {item_id:'01',name:'abc', price:100},
  {item_id:'02',name:'xyz', price:200}

As per above code snippet, implementation of ‘sum’ has been abstracted from the user. In the world of type safe language like Java, it is very straight forward, but in case of javascript we need to have our custom implementation. Lets see how can we achieve above in javascript.
Lets start with defining a constructor function which introduce a common function to all our custom object so that we can extract integer value for summation.

//constructor function to introduce new function to custom object
function item(options) {
  var instance = Object.create(item.prototype);
  for(property in options) {
      instance[property] = options[property];
      instance[property] = options[property];
  return instance;

item.prototype = {
  valueOf : function() {
    console.log('Inside prototype');
    return this.price;
  type: 'item'

As per above code snippet, item() construction function return new object with special function valueOf(). Lets execute our initial code snippet with little modification

//Normal sum
var integerSum = sum(10, 20);
//Expecting item price sum
var objectSum = sum(
  item({item_id:'01',name:'abc', price:100}),
  item({item_id:'02',name:'xyz', price:200})
console.log(integerSum);//=> 30
console.log(objectSum);//=> 300

So we have overloaded sum() which seamlessly return summation for literal to custom object.