Tuesday, November 11, 2014

Coding Good Practices : Constants

We'll discuss a good practice in coding which is using Constants.

A constant in Java is used to map an exact and unchanging value to a unique variable name.

Those constants make the code a bit more robust and more human readable. As those constant values can be used in multiple places, it gives you a single point to change the value of the constant if requires.

(public/private) static final TYPE NAME = VALUE;

Where TYPE is the type, NAME is the name in all caps with underscores for spaces, and VALUE is the constant value;
Lets see an example

public final class Consts  {
      public static final int SECONDS_IN_HOUR = 60 * 60 // sure, this will never change, but it will make the code where you use it a lot more readable
      public static final String DEFAULT_USERNAME = "Fernando" // this can be used in several places
      public static final double AVOGADROS_NUMBER   = 6.02214199e23;

      private Consts  () {
      // a private constructor prevents from instantiating the class
      }
}

The static Keyword
The static keyword makes that variable to the class instead of a specific instance (Object).

The final Keyword
When we declare a variable to be final we are telling Java that we will NOT allow the variable’s “pointer” to the value to be changed. In other words the final keyword means that once the value has been assigned, it cannot be re-assigned. So if we tried to put in some code later that tries to change a a final variable we would get a compilation error.

The naming convention
A constant is defined by an UPPER_CASE_LETTERS_WITH_UNDERSCORES_INDICATING_SPACES.
Again, it’s not mandatory to use upper case letters with underscores to indicate spaces, but it’s a convention that programmers use and are familiar with in Java.

private vs public Constants
If a constant is private no other classes can see or use that constant. You may use private constants if those constants are only used in that class. Public constants can be used over multiple classes. It is recommended and practiced to keep the constants in a separate class.

Bad practices
It is bad practice to replace every literal by a constant. For example
private static final int SMALLEST_POSSIBLE_INCREMENTOR = 1 // don't do this; please!
private static final int FIVE = 5 // oh please please don't do this

SO happy coding folks..

Monday, November 3, 2014

Extracting data from Excel (Spreadsheet) files


Do you have a huge spreadsheet file (an excel file) and wanting to take the data out and place it on a database, or process those data to get some results?



Yeah, I faced the same issue couple of months back, had a big excel file with information of people and wanted to extract them to a database. Here's how I tackled it.


JExcelApiJava Excel API - A Java API to read, write, and modify Excel spreadsheets










You can go to its page using this link
You can download the required library from here

Using that API you can,
  • Reads data from Excel 95, 97, 2000, XP, and 2003 workbooks
  • Reads and writes formulas (Excel 97 and later only)
  • Generates spreadsheets in Excel 2000 format
  • Supports font, number and date formatting
  • Supports shading, bordering, and coloring of cells
  • Modifies existing worksheets
So here is how I used it. 

public ArrayList<Person> read(String inputFile) throws IOException {
        File inputWorkbook;
        Workbook w;
        Sheet sheet;
        private ArrayList<Person> peopleList;
    
        peopleList = new ArrayList<>();
        inputWorkbook = new File(inputFile);     // absolute path and name 
                                                       //of the spreadsheet file
        try {
            w = Workbook.getWorkbook(inputWorkbook);
            sheet = w.getSheet(0);//put the sheet number or you can automate this

            int numberOfRows = sheet.getRows();
            for (int i = 0; i < numberOfRows; i++) { //i=0 is the heading
                Person aPerson = new Person();
                aPerson.setName(sheet.getCell(1, i).getContents());
                aPerson.setContactNo(sheet.getCell(2, i).getContents());
                aPerson.setContactNo2(sheet.getCell(3, i).getContents());
                aPerson.setAddress(sheet.getCell(4, i).getContents().replaceAll("'", " "));
                aPerson.seteMail(sheet.getCell(5, i).getContents());
                if(!sheet.getCell(6, i).getContents().isEmpty()) {
                    aPerson.setbDay(new SimpleDateFormat("dd/MM/yyyy").parse(sheet.getCell(6, i).getContents()));
                } else {
                    aPerson.setbDay(new Date(0));
                }
                aPerson.setGroup(sheet.getCell(7, i).getContents());
                aPerson.setGender(sheet.getCell(8, i).getContents().charAt(0));
                peopleList.add(aPerson);
                System.out.println(aPerson);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return peopleList;
    }


PS : if you have a new version excel file, you need to save it as an 'xls' file to work. Read the documentation for more info

You can then use the extracted date to store in a database or for your calculations.

One thing to remember, if you have a problem (any), it is most likely that somebody might had faced the same problem before and has found a solution, So the golden rule is Google before you solve.

Happy coding folks..