Friday, January 28, 2011

Enumeration improved with Generics

Google is your friend, Wiki is your teacher is very true. I have been reading on the bus ride during the CNY trip and learnt some power concept for OOP in java especially the use of generics. Below is the code I improved on AbstractEnum class which will now be even more flexible than ever.

public abstract class AbstractEnum<INPUT_TYPE>{
    private final INPUT_TYPE k;
    private static int nextOrdinal = 0;
    private final int ordinal = nextOrdinal++;
   
    protected AbstractEnum(INPUT_TYPE k){
      this.k = k;
    }
   
    public INPUT_TYPE getValue(){
      return this.k;
    }
   
    public int getOrdinal(){
      return this.ordinal;
    }
   
    //override equals method   
    public boolean equals(Object o){
        AbstractEnum objE =  (AbstractEnum) o;
        return ( this.ordinal == objE.getOrdinal() );
    }
}

Here's the implementation. Look much cleaner than before isn't it?

public class DayImpl extends AbstractEnum<String>{

    protected DayImpl(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }
   
    //creating your enum
    public static final DayImpl Mon = new DayImpl("monday");
    public static final DayImpl Tue = new DayImpl("tuesday");
    public static final DayImpl Wed = new DayImpl("wednesday");
    public static final DayImpl Thur = new DayImpl("thursday");
    public static final DayImpl Fri = new DayImpl("friday");
    public static final DayImpl Sat = new DayImpl("saturday");
    public static final DayImpl Sun = new DayImpl("sunday");
}

Sunday, January 23, 2011

Finished Java 2 unleased. Goodies included

I've finally finished the book of almost a thousand page long! It took me close to 30 hours to finish everything. I think a do learn a great deal more as compared to just doing what work has required me. Even though Java might be a dying program, I still think there is a market for Cheapo peeps like me who feel cost might be the determinant of a successful project continuation.

As of now, there are many people complaining to me how Java is going downhill after Oracle bought over it. I do not have a crystal ball so I would rather not comment. Probably I will learn more about it before jumping to next language, which will be dot Net.

I will be writing my own framework, so that I can improve and showcase my stuff! Below is the helper class to do encryption and decryption for a String. Hope you like it!


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class CipherHelper {
   
    public static final String CIPHER_TYPE = "DES/ECB/PKCS5Padding";
    public static final String KEY_GEN_TYPE = "DES";
   
    public static SecretKey genKey() throws NoSuchAlgorithmException{
        KeyGenerator kg = KeyGenerator.getInstance(KEY_GEN_TYPE);
        return kg.generateKey();
    }
   
    public static byte[] encrypt(String o, SecretKey k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        Cipher cip = Cipher.getInstance(CIPHER_TYPE);
        cip.init(Cipher.ENCRYPT_MODE, k);
       
        return cip.doFinal(o.getBytes());
    }
   
    public static String decrypt(String s, SecretKey k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        Cipher cip = Cipher.getInstance(CIPHER_TYPE);
        cip.init(Cipher.DECRYPT_MODE, k);
        byte input[] = cip.doFinal(s.getBytes());
       
        return new String(input);
    }
}

Wednesday, January 19, 2011

Coding configurable software

A summary of what I had learn in writing requirement-changeable software.
  1. Use of properties file
  2. Configuration to be refactored into another class for rendering component input
  3. Spring framework for tier division
  4. Anymore?

Tuesday, January 18, 2011

Programming: how to do it better

2 nice video on how to program better. All in all, I think I got some ideas on how to do better testing. 2 types of testing packages will be created. One for object testing, another packages will be multiple situation testing for the following routine as an example (login, search, read email, delete mail, refresh inbox, search). Probably another for bug fixes?

I've got doubt in formal prove as you may prove within a system, things are bug-free. However, what if, multiple systems do interact and something right on one system might result in fault at the other.  However if I can prove program is bug-free formally, it will be great! But life would probably be very sucky looking back at discrete maths. Noooooo!!!

Wisdom
  1. design code components so they cant be used incorrectly
  2. make good use of compiler features like -wall and -wextra to find "invisible" errors
  3. Use of tools like valgrind to check for memory leaks
  4. Testing
    1. Core concept
      • automated
      • repeatable
      • as comprehensive as possible
      • seperate code and test
      • new test for new feature or bug fixed
    2. Limitations
      • only show the presence of bug
      • buggy test
      • test coverage is never complete
      • oo testing required per object = no of change state x number of state
      • looking deeper into bug to fix the processes
      1. Future
        • better languages
        • type systems (curry-howard isomorphism)
        • theorem prover to show its bug-free. more code for testing then the original code!

    Part 1, 2

    Monday, January 17, 2011

    Concurrency

    Shortcut to avoiding race condition on threading application with read and write operation.
    1. Use Synchronize
    2. Use Volatile
    3. Follow rule 1 and 2

    Saturday, January 1, 2011

    Installing XAMPP with tomcat plugin

    Doing a quick installation of XAMPP on my macbook now. And if you wonder why I'm doing this post, the reason is simplicity. With a single installation you get Apache and MySql up and running in less than 10 mins. Here comes the difficult part. Tomcat is not part of the default installation. Configuration of the ini and conf files is needed to get it running. Trying out if mac will work with windows configuration tutorial.



    Enumeration (improved version)

    With reference to the previous post. I have try to improve the code so that enum will become extensible. The code will be broken down to 2 parts. The abstract version and the implementation

    Abstract enum class

    public abstract class AbstractEnum {
        private final String name;
        private static int nextOrdinal = 0;
        private final int ordinal = nextOrdinal++;
        
        protected AbstractEnum(String name){
          this.name = name; 
        }
        
        public String getName(){
          return this.name;
        }
        public int getOrdinal(){
          return this.ordinal;
        }
        
        //override equals method    
        public boolean equals(Object o){
            AbstractEnum objE =  (AbstractEnum) o;
            return ( this.ordinal == objE.getOrdinal() );
        } 
    }

    The implementation class for Day enum.
    public class DayImpl extends AbstractEnum {
    
        protected DayImpl(String name) {
            super(name);
            // TODO Auto-generated constructor stub
        }
        
        //creating your enum
        public static final DayImpl Mon = new DayImpl("monday");
        public static final DayImpl Tue = new DayImpl("tuesday");
        public static final DayImpl Wed = new DayImpl("wednesday");
        public static final DayImpl Thur = new DayImpl("thursday");
        public static final DayImpl Fri = new DayImpl("friday");
        public static final DayImpl Sat = new DayImpl("saturday");
        public static final DayImpl Sun = new DayImpl("sunday");
    } 

    Design Patterns: Enumeration

    Enumeration is often used when the list of variable is always fixed. For example the days in a single week can be written as:

    public enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
        THURSDAY, FRIDAY, SATURDAY 
    }

    However there is often a problem of testing the Enumeration. I have to get back to my codes to know the violations of using default enum. I believe enum cannot exist as a class and hence you will have to replicate enum across the class that is using it. I chance upon the following clever get-around solution using Java object class.

    This is the sample code for Java Enumeration:

    class Day{
    
      private final String name;
      private static int nextOrdinal = 0;
      private final int ordinal = nextOrdinal++;
    
      protected Day(String name){
        this.name = name; 
      }
    
      public String getName(){
        return this.name;
      }
      public int getOrdinal(){
        return this.ordinal;
      }
    
      //creating your enum
      public static final Day Mon = new Day("monday");
      public static final Day Tue = new Day("tuesday");
      public static final Day Wed = new Day("wednesday");
      public static final Day Thur = new Day("thursday");
      public static final Day Fri = new Day("friday");
      public static final Day Sat = new Day("saturday");
      public static final Day Sun = new Day("sunday");
      //override equals method
    
      public boolean equals(Object o){
        Day objE =  (Day) o;
        return ( this.ordinal == objE.getOrdinal() );
      } 
    }
    

    There are things to take note:
    1. The use of protected construction to prevent the instantiation of Day class
    2. Use of final ordinal and static nextOrdinal to issue a unique number for a new Enum. Mon will get ordinal 1, Tue get ordinal 2 and so on....
    3. Use of overridden equals method as a more efficient way to compare object instead of using String

    Hope this helps. Have a nice day ahead!

    ps: I have a improved version of Enumeration

    9986 hours: finishing JSP/Servlet chapter

    As of now, I've completed 10 chapters of J2EE unleashed. Not going through the chapter in order, reading in a mix of what I know that can be make better use in my current project and what I will be interested in especially in the direction of EJB and JMS.

    Just finished the JSP/Servlet chapters, it is quite sad they only went through the custom jsp tag. I am currently looking at some online resources and should be able to apply it in another hour.

    At the same time, I am wondering what are the personal projects I can start doing in order to practice the stuff I read. I shall end this post with a quote.

    “Knowing is not enough, you must apply; willing is not enough, you must do.”

    Counting down: 9989 hours

    I feels great to have a new year resolution that span out over several years. So before the start of the new year, I've already been chipping away part of the 10,000 hours I set out to achieved.

    It definitely does give a sense of having your feet on the solid ground and walking step by step towards your goal. My new year resolution at least for this and next 2 years is to become a accomplished J2EE developer.

    Personally, I feel one of the ways to "upgrade your skills" is the copy what others are good at and apply it and become better than what others are doing as time goes by. This is what the Japanese do best and give them the edge over other countries in the 20th century. This comes to the need for design patterns. Design patterns provide developers to better communicate their ideas across and working with designs that are already recommended for its ability to adapt to changes.

    Over the next few post, I will discuss the several popular design patterns. Below is a Amazon link on Head First Design Pattern book. This is one I really enjoy very much. Better than a story book I would say. Stay tune for my next post!