Friday, November 7, 2014

Scala Vs Java

Scala has a set of features, which differ from Java. Some of these are:
note: few of them got introduced in Java 1.8
  • All types are objects. (Int, Short, Long, Byte etc.)
  • Type inference. (val s = "scala". s is of type string which will be determined by scala compiler at runtime)
  • Nested Functions. def f { def b { ) }  } )
  • Functions are objects.
  • Domain specific language (DSL) support.
  • Traits. 
  • Closures. ( val s = "is awesome"; val o = Option("scala").map { _ + s} ) 
  • Lambdas 

  • Concurrency support inspired by Erlang. { package scala.actors.Actor._ }

  • Case Class

  • Implicit conversion ( implicit def toString(i: Int) = i.toString )


Thursday, November 6, 2014

6 constraints of RestFul Architecture

REST

A client-server communication architecture(not a protocol). 

Why it can't be a protocol? 
AFAIK, there is no industry defined standards and it has only guidelines for those who want to create a web service using Rest concept. 

What are all the guidelines?

Uniform Interface

This is the basic fundamental constraint for the REST web service architecture. This states that all services and service consumers within a REST-compliant architecture must share a single, same interface.

The interface between client and service is defined based on HTTP verbs (GET, POST, PUT/PATCH, DELETE), Resources (URI) and Representations. 

In a payroll web service, the interface could look like

<uri> -> /api/identity/employees (identity is the service name and employee is the resource name and plural notation is preferred)

GET /api/identity/employees will return a json response in the following format,

                                  {
                                    {
                                      id: "123AD232"
                                      first_name: "suresh babu"
                                      last_name:  "prakasam"
                                      ................................
                                      ................................
                                   },
                                   {
                                     id: "456AD232"
                                     first_name: "kokila"
                                     last_name:  "suresh babu"
                                     ................................
                                     ................................
                                   }
                                }

Stateless

Each request to the server should contain enough information to get the response back to client.

Why the hell, server need to maintain the state of a client application? 

Cacheable

Add Last-Modified header with RFC-1123 timestamp format. It is preferred over ETag as the value is more meaningful. Please note If-Modified-Since header, which is used to validate against Last-Modified, may send the timestamp inthree different formats and the server side needs to handle all of the three formats.

Client-Server

Client and Server have a formal contract for communication so the client implementation or server implementation can be replaced without any impact for the service interface.

Layered System

Client should not assume that it has direct connection to the server. The server side system includes CDN caching, Load balancer, Web server filters etc.,

Code on Demand (Optional)


References

  • http://www.restapitutorial.com/lessons/whatisrest.html

Monday, January 20, 2014

Data Structures in FP


It's really interesting to design & implement the commonly used data structures like LinkedList, BinaryTree etc., in functional style. The following link will take you to my own repository in GitHub. The comment section of each method clearly explains what the piece of code is doing..

Take a look at

https://github.com/sprakasam/scala-coding-fun/tree/master/complex-data-structures

Friday, January 3, 2014

Scala Design Tips

In this section, I would like to share some useful tips for Java developers,

Tip 1 - Trait, or not to Trait

What is a Trait? - Trait contains set of methods (not functions) and each method defines a behavior of an object. Mix-in this trait into a class gives that class a new set of behavior.
RULE 1
If the behavior will not be reused, then make it a concrete class. It is not a reusable behavior after all.
RULE 1 Example,
class Account {
def withdraw(...) = {}
def deposit(...) = {}
}
trait AccountManager {
def withdraw(accountId: Long, amount: Int) = {. . } // this behavior doesn't seems like re-usable by other classes except by the Account 
class
def desposit(accountId: Long, amount: Int) {.. } // this behavior doesn't seems like re-usable by other classes except by the Account  class
}
RULE 2
If a set of behavior makes a class definition lengthy, to increase the readability define a trait with self reference to that superclass. The self reference will ensure that any trait or class 'mixin' this trait must have self reference to super class.

RULE
2 Example,
trait EmployeeManagement {
self: Employee =>
def add: Employee = {...}
def remove: Employee = {...}
}
class Employee extends EmployeeManagment {
val name = ""
val address =""
}
RULE 3
If efficiency is very important, lean towards using a classMost Java runtimes make a virtual method invocation of a class member a faster operation than an interface method invocation. Traits get compiled to interfaces and therefore may pay a slight performance overhead

Tip 2. Data Encapsulation: Case Class or Class?

When the Scala compiler sees a case class, it automatically generates copy(), toString(), hashcode(), equals() . This is the design of a "Case Class" in Scala. 

case class EncapsulateUsingCaseClass(a: Int, b:Int) {}
class EncapsulateUsingClass(a: Int, b:Int) {}




Tip 3. Maintain Immutability with Case Class

// You may want to change the address after the object is created. Even though Scala allows you to declare 'var' for case class parameters,
// this piece of code is conflicting with Immutability concept.
case class Student(id: String, name: String, var address: Int)
// Use 'Successor Value' Pattern to modify any of the fields in an object. The above case class can be written using successor value pattern
case class Student(id: String, name: String, age: Int) {
def modifyAge(newAge: Int): Student = Student(id, name, newAge)
}

Thursday, January 2, 2014

Scala Course - Inter Level

Notes from Programming in Scala (by Martin Odesky)

This section contains a link to the google doc spreadsheet. And this spread sheet has organized by topics from the book "Programming in Scala". This is one of the nice books for Scala Developers. It may take days to read through this book. I come up with an idea putting down the notes which will help you to understand all the concepts from that book without reading it.



Wednesday, December 25, 2013

Understanding Function literal and Function value

Function Literal and Function Value

This is one of the nice ingredients of Scala that allows developers to write an unnamed (or anonymous) function and assign it to a variable. This unnamed function is called as a Function Literal. Look at the below example,

val vowels = List ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', U)
val hasVowelChar = (s: String) =>  s.toCharArray.exists(vowels.contains(_))

The variable hasVowelChar have been assigned an unnamed function with string parameter and returns true if string contains vowel character.

The above said unnamed function gets instantiated at run time when this function is invoked which is called Function Value (hasVowelChar).  

Thursday, October 31, 2013

Self Type in Trait

Self type can be used in Trait to make sure the classes that mix in this trait contain the reference to the object of type declared as a self reference in the Trait.

Is it so confusing, let me explain with a simple example,

trait A {
def print(message: String) = println(message)
}

class B {
self: A=>
}

the above class B declares the trait A as self type. The fields and methods of the trait can be used in the class B only if A is mixed in while B is instantiated.

val instance1 = new B with A    ---> CORRECT

val instance2 = new B ---> ERROR: class B cannot be instantiated because it does not conform to its self-type B with A


More examples,

class C extends B {                    ----> WRONG. because self type of B is not mixed in here.
}

class C extends B with A {        ----> CORRECT
}

class D extends B {
self: A =>                                   ----> CORRECT
}