Sunday, 4 March 2012

Do it short but do it right !! (Java Best Practices)

Writing concise, elegant and clear code has always been a difficult task for developers. Not only will your colleagues be grateful to you, but you would also be surprised to see how exciting it is to constantly look forward to refactoring solutions in order to do more (or at least the same) with less code. One used to say that good programmers are lazy programmers. True, true... But really good programmers are adding beauty to it.
You can easily improve the readability of your code, exploiting the power of the Java language, even for pretty basic things.

Let's start with a concrete example:
1String color = "green";
2...
3if  ( color!=null && color.equals("red") ) {
4    System.out.println("Sorry, red is forbidden !");
5}
One of the first lessons you probably learned from your Java (or Object-Oriented programming) teacher is the importance of testing the nullity of an object before invoking a method on it. Null pointer exceptions (NPEs) are indeed among the most common (and irritating) faults raised in the code of object-oriented languages.

In the above example, it is safe to ensure the 'color' String object is not null before comparing it to a constant. I personally have always considered this as an unnecessary burden on the programmer – especially for modern OO languages such as Java. As a workaround, there exists a (really stupid) trick for rewriting the condition without having to test for nullity. Remember, the equals() method is symmetric (if a=b then b=a).
1if  "red".equals(color) ) {
2    System.out.println("Sorry, red is forbidden !");
3}
At first glance, it might be seen a bit contra-natural when read, but eliminating the polluting code is certainly not worthless.

Let's continue our example, and imagine we now want to compare our color with multiple values. Java beginners would usually write something like:
1if "red".equals(color) ||
2     "yellow".equals(color) ||
3     "blue".equals(color) ) {
4    System.out.println("This is a primary color");
5}
Sometimes met more experienced Java programmers shortening such long if statement with: 
1if "red|yellow|blue".indexOf(color)>=0 ) {
2    System.out.println("This is a primary color");
3}
Smart isn't it ? Not that much actually. Playing with substrings can be a dangerous game. For instance the following code might not give the expected results, especially if you are a man:
1String type = "man";
2...
3if "woman|child".indexOf(type)>=0 ) {
4    System.out.println("Women and children first !");
5}
If you are looking for a good balance between elegance and readability, you had better opt for one of the following alternatives.
01import java.util.HashSet;
02import java.util.Set;
03
04public static final Set<string> PRIMARY_COLORS;
05static {
06    PRIMARY_COLORS = new HashSet<string>();
07    PRIMARY_COLORS.add("red");
08    PRIMARY_COLORS.add("yellow");
09    PRIMARY_COLORS.add("blue");
10}
11...
12if ( PRIMARY_COLORS.contains(color) ) {
13    System.out.println("This is a primary color");
14}
Few people know it, but there is still a way to reduce code verbosity when initializing the Set of primary colors:
1public static final Set<string> PRIMARY_COLORS = new HashSet<string>() {{
2    add("red");
3    add("yellow");
4    add("blue");
5}};
In the event concision of code becomes an obsession, the Java Collections Framework can also come to the rescue:
1import java.util.Arrays;
2import java.util.Collection;
3
4public static final Collection<string> PRIMARY_COLORS = Arrays.asList("red""yellow", "blue");
5...
6if ( PRIMARY_COLORS.contains(color) ) {
7    System.out.println("This is a primary color");
8}
The final keyword prevents the PRIMARY_COLORS variable from being re-assigned to another collection of values – this is particularly important when your variable is defined as public. If security is a major concern, you should also wrap the original collection into an unmodifiable collection. This will guarantee a read-only access.
1import java.util.Arrays;
2import java.util.Collection;
3import java.util.Collections;
4
5public static final Collection<string> PRIMARY_COLORS =
6   Collections.unmodifiableCollection( Arrays.asList("red""yellow", "blue") );
7</string>
It must be noticed that, though more readable, using a collection of values (especially with large collections) will generally remain slower than classical lazy OR's (ie using '||' instead of '|') because of theshort-circuit evaluation. Nowadays such considerations become futile.

After 16 years of complaints, Java 7 has - at last! - introduced the support of String in switch-case statements. This allows us to code things such as:
01boolean primary;
02switch(color) {
03 case "red":
04     primary=truebreak;
05 case "green":
06     primary=truebreak;
07 case "blue":
08     primary=truebreak;  
09 default:
10     primary=false;
11}
12if (primary) System.out.println("This is a primary color");
Let us finally end with what is probably the most object-oriented solution to our (so to say) problem. Java enumerations are primarily classes, and can therefore have methods and fields just like any other classes. By applying the Template Method design pattern, one can define an abstract method (modeling the test) which has to be implemented by all subclasses (modeling the response of the test applied to a particular item of the enumeration):
01Color c = Color.valueOf("RED");
02if ( c.isPrimaryColor() ) {
03  System.out.println("This is a primary color");
04}
05
06public enum Color {
07     RED() {
08          @Override
09          public boolean isPrimaryColor() {
10              return true;
11          }
12     },
13     BLUE() {
14         @Override
15         public boolean isPrimaryColor() {
16               return true;
17          }
18     },
19     YELLOW() {
20         @Override
21         public boolean isPrimaryColor() {
22               return true;
23          }
24     };
25     GREEN() {
26         @Override
27         public boolean isPrimaryColor() {
28               return false;
29          }
30     };
31     public abstract boolean isPrimaryColor();
32}
The resulting code is clear and self-documenting. Using this pattern is a great alternative in many cases to the more common “if - else if” logic since it is easier to read, extend, and maintain.

To conclude, as very often - and this is the power of the Java language – for one problem, there exist so many different solutions in terms of implementation. But deciding which one is the best is another story...

Saturday, 3 March 2012

20 Database Design Best Practices


  1. Use well defined and consistent names for tables and columns (e.g. School, StudentCourse, CourseID ...).
  2. Use singular for table names (i.e. use StudentCourse instead of StudentCourses). Table represents a collection of entities, there is no need for plural names.
  3. Don’t use spaces for table names. Otherwise you will have to use ‘{‘, ‘[‘, ‘“’ etc. characters to define tables (i.e. for accesing table Student Course you'll write “Student Course”. StudentCourse is much better).
  4. Don’t use unnecessary prefixes or suffixes for table names (i.e. use School instead of TblSchool, SchoolTable etc.).
  5. Keep passwords as encrypted for security. Decrypt them in application when required.
  6. Use integer id fields for all tables. If id is not required for the time being, it may be required in the future (for association tables, indexing ...).
  7. Choose columns with the integer data type (or its variants) for indexing. varchar column indexing will cause performance problems.
  8. Use bit fields for boolean values. Using integer or varchar is unnecessarily storage consuming. Also start those column names with “Is”.
  9. Provide authentication for database access. Don’t give admin role to each user.
  10. Avoid “select *” queries until it is really needed. Use "select [required_columns_list]" for better performance.
  11. Use an ORM (object relational mapping) framework (i.e. hibernate, iBatis ...) if application code is big enough. Performance issues of ORM frameworks can be handled by detailed configuration parameters.
  12. Partition big and unused/rarely used tables/table parts to different physical storages for better query performance.
  13. For big, sensitive and mission critic database systems, use disaster recovery and security services like failover clustering, auto backups, replication etc.
  14. Use constraints (foreign key, check, not null ...) for data integrity. Don’t give whole control to application code.
  15. Lack of database documentation is evil. Document your database design with ER schemas and instructions. Also write comment lines for your triggers, stored procedures and other scripts.
  16. Use indexes for frequently used queries on big tables. Analyser tools can be used to determine where indexes will be defined. For queries retrieving a range of rows, clustered indexes are usually better. For point queries, non-clustered indexes are usually better.
  17. Database server and the web server must be placed in different machines. This will provide more security (attackers can’t access data directly) and server CPU and memory performance will be better because of reduced request number and process usage.
  18. Image and blob data columns must not be defined in frequently queried tables because of performance issues. These data must be placed in separate tables and their pointer can be used in queried tables.
  19. Normalization must be used as required, to optimize the performance. Under-normalization will cause excessive repetition of data, over-normalization will cause excessive joins across too many tables. Both of them will get worse performance.
  20. Spend time for database modeling and design as much as required. Otherwise saved(!) design time will cause (saved(!) design time) * 10/100/1000 maintenance and re-design time.

Thursday, 1 December 2011

Liskov Substitution Principle




SOLID - Liskov Substitution Principle

Liskov Substitution principle (LSP) states that,
Methods that use references to the base classes must be able to use the objects of the derived classes without knowing it

This principle was written by Barbara Liskov in 1988.
The idea here is that the subtypes must be replaceable for the super type references without affecting the program execution.

This principle is very closely related to Open Closed Principle (OCP), violation of LSP in turn violates the OCP. Let me explain:


If the subtype is not replaceable for the supertype reference, then in order to support the subtype instances as well we go ahead and make changes to the existing code and add the support. This is a clear violation of OCP.

This is mostly seen in places where we do run time type identification and then cast it to appropriate reference type. And if we add a new subtype implementation then we would have to edit the code to test for instance of for the new subtype.

Let me give a subtle example:

class Bird {
    public void fly(){}
    public void eat(){}
}

class Crow extends Bird {} 
class Ostrich extends Bird{
    fly(){ 
        throw new UnsupportedOperationException();
    }
}
public BirdTest{
    public static void main(String[] args){
        List<Bird> birdList = new ArrayList<Bird>();
        birdList.add(new Bird());
        birdList.add(new Crow());
        birdList.add(new Ostrich());
        letTheBirdsFly ( birdList );
    } 
    static void letTheBirdsFly ( List<Bird> birdList ){
        for ( Bird b : birdList ) {
            b.fly();
        }
    }
}  

What do you think would happen when this code is executed? As soon as an Ostrich instance is passed, it blows up!!! Here the sub type is not replaceable for the super type.

How do we fix such issues?

By using factoring. Sometimes factoring out the common features into a separate class can help in creating a hierarchy that confirms to LSP.

In the above scenario we can factor out the fly feature into- Flight and NonFlight birds.   

class Bird {
    public void eat(){}
}

class FlightBird extends Bird{
    public void fly()()
}

class NonFlight extends Bird{}

So instead of dealing with Bird, we can deal with 2 categories of birds- Flight and NonFlight.

How can we identify LSP violation?

Derived class may require less functionalities than the Base class, so some methods would be redundant.
We might be using IS-A to check for Super-Sub relationships, but LSP doesn't use only IS-A, but it also requires that the Sub types must be substitutable for the Super class. And one cannot decide the substitutability of sub class in isolation. One has to consider how the clients of the class hierarchy are going to use it.