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..

Sunday, October 5, 2014

Using GIT effectively

This article is about some of the good practices I learnt from the industry when using the GIT..

Git-logo.svg     Lets briefly see what is GIT. It is a distributed version controlling system. You can find a wikipedia article from here. In simple words when you are developing a system, you might need to keep track of the changes/modifications you did to the code and once in a while you might need to revert to a previous working state of a code. GIT is a handy tool for that task.
You might be developing a system as a project where each members contribute to the code, So how can you support this? GIT is the solution, you can have you code in a GIT repository and you all can work on the same code without interfering to others (given that you use GIT effectively).
Hope you got enough motivation ;)

I will explain basics of the GIT in a later article.

In this article I'll introduce you GIT best practices

Hack 1 : Every day before you start your work take a pull from the repository
git pull origin
This will make sure your code is up to date

Hack 2 : Every day before you finish you page push all your changes to the repository
this has few steps let me explain them to you in below
This will make sure the code in the repository contains all the up to date modifications

Hack 3 : Use separate branches to implement separate features/ functionalities
git branch branchName
git checkout branchName
Use a meaningful for every branch, so that your life would be easy, with separate branches you have a lot of flexibility to even to hold current work and start implementing another feature on another branch.

Hack 4 : Never work on the 'master' branch
git checkout branchName
If you work on the master branch you are in a big trouble when pulling the changes. If you code got broken due to the pull, it wouldn't be easy to solve the conflicts and merge the changes.


Hack 5 : Steps to push changes
Here I assume you are in a branch called my branch.
git add --all                                <-- stage all the modified/created files
git commit -m "commit message"
git checkout master              <-- go to the master branch, note none of you new changes are
                                                                    visible in the master branch
git pull origin                        <-- pull and get the up to date code from the repo
      If conflicts are there, resolve them and merge the code. Now you have up to date code in the      
      master branch
git checkout myBranch        <-- go to myBranch
git rebase master                <-- take the changes in the master to myBracnch
      If conflicts are present
git mergetool                           <-- using the mergetool to resolve confilcts
git commit -m "message"   <-- commit the changes in resolving the confilcts
git rebase --continue       <-- command to continue the rebase process
git checkout master               <-- go to master branch
git pull origin                    <-- check whether the code in the repository has been changed while we were working on the rebase process of myBranch, if the code is up to date we can continue the process, if any changes have been pulled, we need to again do the rebase process.
git merge myBranch                 <-- merge the changes of the myBranch to master
git push origin master       <-- push the code to the repository, now the repository has
                                                                  your code

Hack 6 : Add meaning full comments to commits
git commit -m "commit message"
Adding meaning full commit messages will make your life so easy when you want go back to a previous state. It is advised to use the commit message in present tense.

Here is a nice Git Guide
Ok those are the things I wanted to share, happy coding folks :D



Thursday, January 23, 2014

The 1-Minute Trick - A Productivity Hack:

Are you feeling your everything is messed up..? Here is a cool productivity hack, it's simple, easy and efficient.. Just give it a try


When you are doing your day to day life. You encounter a lot of things which can be completed within a minute. For example keeping your shoes in the right place, replying an e-mail or a SMS message, keeping a book at the right place. But we usually neglect those tasks and postpone that task. The result is a messed up and untidy life. This trick is simple

Any task you can do within a minute, Do it at that time, without any delay.

Just give it a try and see how beautiful and easy you life would be :)

for more info http://www.linkedin.com/today/post/article/20140121122045-6526187-productivity-hacks-the-1-minute-trick?trk=mp-details-rc

Monday, January 13, 2014

Do I really need to use 'safely remove' feature for USBs?

Safely remove hardware and Eject Media feature is beneficial in three ways

  1. Removing the USB drive when some files are being writing into the drive will definitely corrupt data. That feature will prevent it
  2. Operating Systems use a write cache to speed up writing into drives, Sometimes OS would not write all the date at the time it receives the write request, but OS might keep it in a cache and write once substantial amount of data is present to write. When we use the safely remove feature OS flushes the cache and writes all the date to the drive.
  3. A stable supply of power is required for  a small time period for a USB device to properly write all the date. It is actually an electrical requirement. That time is not very significant. Therefore this will not affect most of the time

The Good news is

Most operating systems including Windows do not use a write cache for removable drives, which means your removing without using this feature would not do much harm
to your data in the USB drive. But it is better to use that feature unless you are in a big hurry :D
More Info