Sunday, April 20, 2014

SOLID design principle

When it comes to OO designing, it is a good idea to have a strategy to follow. A strategy allows you to think and organize ideas in a particular fashion that is comfortable to you. I’ve found SOLID principle easy enough for beginners and experts to understand and practice. This was originally put forward by Rober C. Martin, who is a pioneer in agile software development and extreme programming. Checkout Cleancoders to know more.

Chances are, you may be already using SOLID principle, just without giving it a name.

tl;dr

S - Single Responsibility Principle (SRP)

O - Open/Closed Principle (OCP)

L - Liskov Substitution Principle (LSP)

I - Interface Segregation Principle (ISP)

D - Dependency Inversion Principle (DIP)

Thats right, SOLID stands for a bunch of other acronyms.

Read on

S - Single Responsibility Principle (SRP)

The single responsibility principle states that every class should
have a single responsibility, and that responsibility should be
entirely encapsulated by the class. All its services should be
narrowly aligned with that responsibility.

Fairly simple. A Student class should manipulate Student properties and not the the properties of School. Specification of the class remains mostly untouched unless there is a big change in requirement of your software.

It is good to keep in mind that, there can be some exceptions to this. For example a utility class may provide methods for managing both Students and Schools.

O - Open/Closed Principle (OCP)

Software entities should be open for extension, but closed for modification.

The idea is that once a class is implemented completely, it should not be modified for including new features. Bugs and error correction must be done as and when required. Adding a new feature will require new specification and release of newer version.

http://en.wikipedia.org/wiki/Open/closed_principle

L - Liskov Substitution Principle (LSP)

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. See also design by contract.

That right there is the basic use of Dependency Injection, right? You define a parent interface and replace them by concrete implementation which are derivatives.

class Animal {
    public void makeNoise() {
        System.out.println("noise");
    }
}

class Dog extends Animal {
    @override
    public void makeNoise() {
        bark();
    }

    public void bark() {
        System.out.println("bow bow bow");
    }
}

Dog dog = new Animal();
dog.makeNoise();

@Inject
Animal animal; // can be replaced by Dog

http://en.wikipedia.org/wiki/Liskov_substitution_principle

I - Interface Segregation Principle (ISP)

Many client-specific interfaces are better than one general-purpose interface.

Interfaces provide abstraction no implementation. When developing client interfaces, it should be kept at minimum and should only expose those methods which are essential for that client.

http://en.wikipedia.org/wiki/Interface_segregation_principle


interface Jumbable {
    void jump();
}

interface Climbable {
    void climb();
}

class Dog extends Animal implements Jumbable {
    @override
    void jump() {
        //jump
    }
}

class Monkey extends Animal implements Jumbable, Climbable {
    @override
    void jump() {
    }

    @override
    void climb() {
    }
}

D - Dependency Inversion Principle (DIP)

One should “Depend upon Abstractions. Do not depend upon concretions.”

Dependency injection is one method of following this principle.


interface JumpringService {
    public void jump();
}

public class JumpingServiceImpl implements JumpingService {

    @Inject
    private Jumpable jumbable;

    @override
    public void jump() {
        jumpable.jump();
    }
}

http://en.wikipedia.org/wiki/Dependency_inversion_principle

Sunday, April 6, 2014

map() function in JavaScript, Scala etc

These are absolutely awesome functions. They allow you to apply a function on every element of an array and return a new array with the result of the function.

In theory these are called higher-order functions, i.e they can take one or more function as an argument.

Consider the following JavaScript function:

var array = [1,2,3,4,5];
var twoTimesArray = array.map(function(n) {return n*2;});
console.log(twoTimesArray);

output: [2, 4, 6, 8, 10]

So that just multiplies every element of array by 2 and returns the resulting array.

Without map functions you would have done something like this:

var array = [1,2,3,4,5];
var twoTimesArray = [];
for(var i = 0; i < array.length; i++ ) {
    twoTimesArray[i] = array[i] * 2;
}
console.log(twoTimesArray);

Clearly, that is a lot of code compared to the previous one.

And, if you use Scala, code becomes much more concise.

scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)

scala> l.map(x => x*2)



Imagine doing the same thing in Java. First we will look at Java 6

List<Integer> array = Arrays.asList(1,2,3,4,5);
List<Integer> twoTimesArray = new ArrayList<Integer>();
for(Integer i: array) {
    twoTimesArray.add(i*2);
}



And in Java 8:

List<Integer> array = Arrays.asList(1,2,3,4,5);
List<Integer> twoTimesArray = new ArrayList<Integer>();
array.stream().forEach((string) -> {
    twoTimesArray.add(string*2);
});



The difference between for-each loop and using stream api (collection.stream()) in Java 8 is that we can easily implement parallelism when using the stream api with collection.parallelStream(). Whereas, in for-each loop you will have to handle threads on your own.

Programming becomes fun when we add bit of functional style into OO languages.

Sunday, March 30, 2014

Closures

Closures are a bit hard to understand concept for someone from an Object Oriented programming background, mainly because popular OO programming languages, (Java/C++) does not have this feature (As bjzaba pointed out in reddit, C++ 11 has Closures) haven’t embraced or promoted this feature until recently. It is more of a functional programming concept, although many Object Oriented languages has started to support Closures through first class functions or higher order functions.

I first heard about Closures while developing something in Javascript. If you have used the popular javascript library jQuery, you have already used closures, knowingly or unknowingly.

Here is my attempt to explain Closures, through examples in few programming languages. I will try to be as simple as possible.

From Wikipedia:

In programming languages, a closure (also lexical closure or function
closure) is a function or reference to a function together with a
referencing environment—a table storing a reference to each of the
non-local variables (also called free variables or up values) of that
function. A closure—unlike a plain function pointer—allows a
function to access those non-local variables even when invoked outside
its immediate lexical scope.

What that means:
1. Closure is a function (or a reference to a function)
2. You get a pointer to closure
3. So you can pass it around like an object
4. It knows about non-local variables
5. It can access those non-local variables, even when invoked outside of its scope
6. So we say, closures ‘closes’ on its environment
7. A function may create a closure and return it.

Few programming languages, that support Closures

  • Lisp
  • Javascript
  • Scala
  • Clojure
  • Ruby
  • Python
  • Haskell
  • PHP
  • Go

In closures procedure/method/function contexts become first-class. That means, with closures you can create functions that return functions, although that is only an outcome. An important point to understand here is, the closure methods refer to the context in which it was created, not to the one it was called.

To better understand closures one has to understand a variable’s scope, the best read about that would be understanding javascript variable scope.

Closures store references to the outer function’s variables; they do not store the actual value. So if we change the value of reference in closure it changes value outside of its scope.

You may implement closures using Anonymous functions, but all anonymous functions need not be a closure, although many of them are.

Why would anyone use Closures?

  • Reusability
  • Do more with less code
  • Make functional code stateful

Closures help us to write more expressive and concise code(once you get a hang of it!). We know objects have a state, using Closure we can give state to functions as well.

Now, let us take a look at examples of how to use closures in a few programming languages.

Examples

All of the following examples do the same thing: Create a closure to increment a number by another number.

1. Closure example in Javascript

This would be the easiest to understand code.

var incrementBy = function(x) {
    return function(y) {
        return x+y;
    };
};

// this will remember the value of 'x' forever
var incrementBy2 = incrementBy(2);
var incrementBy3 = incrementBy(3);

console.log(incrementBy2(4));
console.log(incrementBy3(8));
// Here you are creating a closure and calling it immediately
console.log(incrementBy(5)(8));

In the Javascript example above, we define a function incrementBy(x), which returns a function, that accepts parameter ‘y’ and returns sum of x and y. Here the value of ‘x’ will go into the closure of the returned function and will be accessible whenever the function is invoked.

Note that when calling incrementBy2(4) our closure remembers the value 2 (i.e ‘x’) that was passed earlier when doing var incrementBy2 = incrementBy(2);. And when invoking incrementBy2(4) we are actually passing the value of y as 4. Hence the statement return x+y will transform to return 2+4. Cool right!!?

2. Closure example in Scala

object Closure {

    // define the closure using one line of code, power of Scala
    def incrementBy(x:Int) = (y:Int) => x + y        

    def main(args: Array[String]) = {

        var incrementBy3 = incrementBy(3)
        val incrementBy5 = incrementBy(5)

        println(incrementBy3(5))
        println(incrementBy5(10))
        println(incrementBy(20)(20))    
    }    
}

The example in Scala is similar to the example in Javascript except for Scala’s awesome one liner syntax.

3. Closure example in Lisp (Clisp)

(defun increment(y)
    (defun incrementBy(x)
        (+ y x)
    )
)

(increment 4)
(incrementBy 5) ; 9
(incrementBy 10) ; 14

There are several ways of doing this is lisp. This is only one way of doing it. Here you are not getting a pointer to the closure function and will probably make it useless. See this link to see how to return functions is Clisp.

4. Closure example in Clojure

(def increment (fn [y] 
    (def incrementBy (fn [x]
      (+ x y)
      ))
))

(increment 4)
(incrementBy 5) ; 9
(incrementBy 10) ; 14

As you can see, the syntax of clojure and lisp are extremely similar.

5. Closure example in Python

def incrementBy(x):
    def increment(y):
        return x+y
    return increment

incrementBy4 = incrementBy(4)
incrementBy6 = incrementBy(6)

print incrementBy4(5)  # 9
print incrementBy6(10) # 16

The above example in Python is pretty similar to the one in Javascript and is easy to understand. Here we define the closure function increment(y) and then return it. Just remember to take care of the tabs!

6. Closure example in Ruby

class Closure

  # Ruby example using Proc.new
  def incrementBy(x)
    return Proc.new {|y| x+y }
  end

  # Ruby example using lambda
  def incrementByLambda(x)
    lambda {|y| x+y}
  end

end

closure = Closure.new
increment5 = closure.incrementBy(5)
incrementByLambda7 = closure.incrementByLambda(7)

puts increment5.call(6)
puts incrementByLambda7.call(6)

Ruby can do this is in two ways, using Proc and using lambda. The lambda functions in Ruby are similar to lambda’s in lisp.


So that was examples about closures. Hope that gives you at least some idea about Closures. If you know how do the same in any other languages, please feel free to share. Also checkout the references, they are good reads.

References:

Thanks to Craig for sharing Go snippet

Reddit thread here: http://redd.it/223b7p

Tuesday, March 18, 2014

PostgreSQL 9.3 initial setup on Mac OSX 10.9.2

After sudo port install postgresql93 postgresql93-server


# switch to su
sudo su

mkdir /var/lib/pgsql/

chown -R postgres:wheel /var/lib/pgsql

su postgres

export PGDATA=/var/lib/pgsql/9.3/data

initdb

createdb pgdbname

createuser -A -D pgusername

exit

exit

# startdb
sudo -u postgres postgres -D /var/lib/pgsql/9.3/data/

# check if login works
psql -h localhost pgdbname pgusername

\q

# add PGDATA to ~/.bash_profile
echo "export PGDATA=/var/lib/pgsql/9.3/data" >> ~/.bash_profile

Thursday, March 6, 2014

Getty Images just made their 35 million images free to embed

Getty Images just made their 35 million images free for non-commercial use, to fight copy-right infringement. The new embed feature will allow any to embed images from Getty Images, without any ugly watermark on them. However these images will have links to original licensing page.

Read the article on British Journal of Photography.

http://www.bjp-online.com/2014/03/getty-images-makes-35-million-images-free-in-fight-against-copyright-infringement/

Sunday, February 2, 2014

Sample app for Play! 2.2, Spring-data-jpa and Backbonejs

I have made a sample application to demo Play! framework 2.2, Spring data jpa and Backbonejs.

It is available at https://github.com/WarFox/play-spring-data-jpa-backbonejs.

Also a demo app is hosted in Heroku at http://play-spring-data-jpa-backbone.herokuapp.com/

It started as a fork from https://github.com/typesafehub/play-spring-data-jpa and then created a separated repo to include backbonjs.

Feel free to fork and play with it.

Monday, January 20, 2014

Backbonejs in jsFiddle.net

jsFiddle does not provide backbonejs library through its Frameworks & Extensions dropdown. Thankfully, it allows you to add any external resources via External Resources option. I have made this blank template for you guys to start playing with Backbonejs in jsFiddle. Feel free to use it directly or fork it.

Thursday, January 9, 2014

jQuery :: Populate Select box dynamically (plugin version)

In my previous post, I had shown how to populate a select box dynamically using jQurey. Here is the same thing as jQuery plugin.

http://jsfiddle.net/deepumohanp/kNQ6s/

Sunday, January 5, 2014

jQuery :: Populate Selet box options dinamically

Here is an example code to populate select box options dynamically using jQuery

http://jsfiddle.net/deepumohanp/8EQjY/

Related Posts Plugin for WordPress, Blogger...