Friday, January 28, 2011

Practical API design Guidelines - with Technical inputs in Java

Good API  design helps developers to breathe longer and comfortable in an organisation.
Especially , if you are in product developement , putting right foucs at the time of API design helps you a lot in the long run.
Poor APIs call for a vicious circle of  unhappy customers, developers cribbing - " this should not be used like this " - customer doesn't know how to use this , fixing and re-fixing continuously etc.,
In this article, I will try to put the best practices for an API design which i have read in books and from my experience .Lets begin with a small example.

The spirit of writing an API :
APIs are to be designed with not what implementor feels , but what the customer wants.
The moment API discussion starts, the focus shifts so much onto what data structure to be used,algorithms etc.,   which often undermines what the developer who calls your API expects.

 Lets take an example :

  makeDrink(false, true) is in the code.
  It is clear that this API is for making a drink, but what does the paramters convey.
  compare it with the following:
   makeDrink(coffee,hot);
  
  much more clear and no manual is needed, it is clear that it creates a hot coffee.
  But from implementor even the first one is usable as well when creating the api :
  makeDrink (boolean isTea , isHot) but this information is lost to caller.

  The Second Version needs Implementor to do more vork , but adding enumerations viz.,
  enum drinkcategory {Coffee, Tea}
  enum drinktype{ hot,cold)
    This makes it, void makeDrink(drinkcategory dc, drinktype dt); which is more writing an API in the view point of caller.
lets read more


  2. API should be designed to one particular task and do it well.IT must be "absloutely" correct in what it is supposed to do.
3. Set clear expectations of what it will do and what it will not - can't please eveyone in this world with your single api ( sounds a bit exaggearated , but get the spirit of it)
4. API should be treated like a little language designed by you. Give proper naming and symmetry to the API with proper documentation.
5. Mimic patterns in core APIs of the language.
6. Fail-fast behaviour when some error occurs .
7. If you are new to api design, best way is to write code with your apis.use your experiences to remove what is not needed.
8. Keep Exceptions unchecked. A checked exception reflects a problem in interaction with the outside world, such as the network, filesystem, or 0S.
  If the exception signals that parameters are incorrect or than an object is in the wrong state for the operation you're trying to do,   then an unchecked exception (subclass of RuntimeException) is appropriate.
9. Most important of all is having the testability approach for your apis in mind. Its a fact that has to be accepted that one of the  key reasons of why   springs worked ahead of EJB is api unit-testability for developers.
10. APIs should be documented , before they are implemented.


Some Technical inputs  in Java  :


1. Make classes and members private as much as possible. The fields that are visible only should be static and final.
2. Keep Classes immutable as much as possible . Though it means an object for each value, It makes objects thread safe and reusable.
   calendar is an example of a bad design.

3. subclass if and only when "is-a" relationship holds . Just for ease of implementation , public classes should not subclass other public classes.
   Eg : Stack extends vector. - a bad one,.

4. Appropriate Parameter and return types -
Specific Input Parameters moves the errors from runtime to compile time
Use double ahead of float , dont use string if a better a type is possible since strings are slow and error prone.

5. Limit the parameters to a max of 3. Incase of longer parameters use helper classes to hold parameters
6. Interface when it is needed . Just imagine if String is an interface, it would be 1000 times diffuclt to get a semantically correct string.
   on saying that interface has some good advantage if there are fewer methods. I still love runnable interface for having a single method.
7.Interfaces cannot have static methods and constructors.

Hope you like this article, keep posting your comments and suggestions.

Thursday, January 27, 2011

Most frequently used Regular Expressions in Java.


Username :
------------


 ^[a-z0-9_-]{3,15}$

Notes :

 ^             Start of the line
[a-z0-9_-]   supported chars and symbols in the list:  a-z, 0-9 , underscore ,hyphen
{3,15}         Length at least 3 characters and maximum length of 15
$         End of the line.


Password :
----------

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

Notes :

  (?=.*\d)  must contains one digit from 0-9
  (?=.*[a-z])  must contains one lowercase characters
  (?=.*[@#$%])  must contains one special symbols in the list "@#$%"

Let us see more

Wednesday, January 26, 2011

SQL Joins Tutorial: Joins are easy. Lets play cricket with them


The Different Types of Joins in SQL Server

Inner join or Equi join
Outer Join
Cross join
Let's suppose we have two tables Emp and Dept whose description is given below:-



CREATE TABLE [Emp](
[Empid] [Int] IDENTITY (1, 1) NOT NULL Primary key,
[EmpNumber] [nvarchar](50) NOT NULL,
[EmpFirstName] [nvarchar](150) NOT NULL,
[EmpLastName] [nvarchar](150) NULL,
[EmpEmail] [nvarchar](150) NULL,
[Managerid] [int] NULL,
[Deptid] [INT]
)
CREATE TABLE [Dept](
[Deptid] [int] IDENTITY (1, 1) NOT NULL primary key,
[DeptName] [nvarchar](255) NOT NULL
)

After the creation of the tables we need to insert the data into these tables. To insert the data the following queries are used:-

insert into Emp (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E1','Sachin','Tendulkar','Sachin@mycomp.com',2,2)
insert into Emp (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E2','Zaheer','Khan','Zaheer@mycomp.com',1,1)
insert into Emp(EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E3','Gambhir','Gautam','Gambhir@mycomp.com',1,2)
insert into Emp (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E4','Dhoni','MS','Dhoni@mycomp.com',1,NULL)

insert into Dept(DeptName)
values('Bowling')
insert into Dept(DeptName)
values('Batting')
insert into Dept(DeptName)
values('Coach')
insert into Dept(DeptName)
values('Allrounder')

Inner Join

This type of join is also known as the Equi join.
This join returns all the rows from both tables where there is a match.
This type of join can be used in the situation where we need to select only those rows
which have values common in the columns which are specified in the ON clause.

Now, if we want to get Emp id, Emp first name and their Dept name
for those Emps which belongs to at least one Dept, then we can use the inner join.

Query for Inner Join

 SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DeptName 
 FROM  Emp 
  INNER JOIN dept 
     ON Emp.Deptid=Dept.Deptid

Result

Empid EmpFirstName  DeptName
1     Sachin                  Batting
2     Zaheer                 Bowling
3     Gambhir              Batting

Explanation

In this query, we used the inner join based on the column "Deptid" which is common in both the tables "Emp" and "Dept".
This query will give all the rows from both the tables which have common values in the column "Deptid".
Gambhir Guatam and Sachin Tendulkar has the value "2" in the Deptid column of the table Emp.
In the Dept table, the Dept "Batting" has the value "2" in the Deptid column.
Therefore the above query returns two rows for the Dept "Batting", one for Gambhir Guatam and another for Sachin Tendulkar.

Lets understand more joins

Tuesday, January 25, 2011

Junit Best Practices with detailed examples - Must for every Java Developer

This is second in our tutorial series of junit.
If you wish to retouch junit basics : http://codingbasics.blogspot.com/2011/01/junit-tutorial-1-junit-with-example.html
In this blog, we will touch up some very important best practices for junits.

Unit Test cases need to be independent:

Each unit test should be independent of all other tests.  A unit test should execute one specific behavior for a single method.
Validating behavior of multiple methods is problematic as such coupling can increase refactoring time and effort.

 Consider the following example:

void testAdd(){
     int val1 = myClass.add(1,2);
     int val2 = myclass.add(-1,-2);
     assertTrue (val1 - val2 == 0);
}

If the assertions fails in this case, it will be difficult to determine which invocation of add() caused the problem.

If you want to test a method for multiple behaviors then one test method must be written for each scenario.
This will make the unit test case focus on the particular behavior of the method with great clarity and maintainability.
Please see the self-explanatory following example in testing a method called divide()

public void testNegativeValues()
{
// This method is used to test for negative values scenario.
}

public void testDivideByZero()
{
// The name very well explains what is this test all about.
}

Lets see some more

Junit Tutorial 1 : Junit with an example


Junit is very useful for  unit testing java code.
Let us understand with a simple example that will illustrate the basic concepts involved in testing with JUnit.


The Goal :

Creating a java file named Calculator.java which has a method named sum() which takes two int parameters
and return addition of these two numbers.
So here we have to check whether this method is functioning well in all the conditions or not.

Creating Calculator.java :
This class has sum method which takes two int parameters to add them and return it . Save and compile this file.

public class Calculator{
    int sum(int num1,int num2){
        return num1+num2;
    }
}
Creating CalculatorTest.java :
To test that method sum() is working fine we need to check it.
For this we create another class named CalculatorTest. Save and compile this file.
Before proceeding further we should first have a look over JUnit coding convention.

        Coding Convention :
                1. Name of the test class must end with "Test".
                2. Name of the method must begin with "test".
                3. Return type of a test method must be void.
                4. Test method must not throw any exception.
                5. Test method must not have any parameter.

In our example, the class name which we are going to test is "Calculator" so we have created class "CalculatorTest" here.
Let us write the test case.

Sunday, January 23, 2011

Test Driven Development . Does Your code have GUTs


Lets try to put in simpler sentences on what is Test Driven Development .

  1. Understand the scope of your feature or requirement
  2. Create a test that you know will fail
    • Call a method that doesn't exist or behave correctly yet
    • This is important because you don't want your tests to pass by accident
  3. Make your failed test pass by adding a minimal amount of code
    • Change the code so that it will pass, but don't go overboard
    • Writing minimal code helps enforce not writing code you don't need
  4. Modify your code to make any necessary improvements
    • This is the point at which you can refactor into methods, rename variables, redesign your interfaces, and so on

Characterstics of Good Unit Test ( GUTs)
---------------------------------------------
  • Runs fast ..simple it should run really fast.
  • Keep the unit test  scope simple and clear. If the test fails, it's obvious where to look for the problem. Use few Assert calls so that the offending code is obvious. It's important to only test one thing in a single test.
  • "It works on my machine " syndrome : It should Run and pass in isolation. If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests. Change them for simplicity and reliability. Tests should run and pass on any machine. It
  • Mock and Stub : Often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.

Qunit- Unit Testing JQuery and JavaScript


QUnit is a powerful JavaScript unit testing framework that helps you to debug code

HOW TO SET-UP THE UNIT TESTS

So what do you need to get started with jQuery Unit Testing? To begin with download both of the following files, Qunit.js, & Qunit.css, and include them in the head of your HTML document along with the latest version of jQuery. Then add the following HTML to the body of your document so that Qunit can render the test results properly:
2
3
4
5
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
As you can see, getting set up with a basic testing environment is easy and pretty simple. With this set-up you can then include your own Qunit tests either in a SCRIPT tag or in your own JavaScript external include.

WRITING YOUR OWN UNIT TESTS

So now you’re ready to start writing your own tests, lets keep it clean and simple. The unit testing API is split into 3 sections:
  1. Setup – The basics for defining tests, grouping them and getting them started.
  2. Assertions – The Yay and the Nay of whether conditions have the met with boolean tests, comparison tests and recoursive comparison assertions for arrays, objects, etc.
  3. Asynchronous Testing – Functions to stop and start the test runner
Read More..

subversion video