Monday, May 23, 2011

I hate ignorant incompetent programmers.

I really hate when this thing happens. Yes I know that Java can be quite verbose with its boilerplate codes but please, as a developer, we should be responsible to write proper codes.

My current gripe right now is related to closing I/O streams. Please do close your streams at the proper place!

Bad example:



public void readFile(String filePath){
  
  try {


    FileInputStream fis = new FileInputStream("inputFile.txt");
    FileOutputStream fos = new FileOutputStream("outputFile.txt");

    ...whatever file processing here...

    fis.close();
    fos.close();

  } catch (Exception e) {


    e.printStackTrace();


  }



} //end of readFile method


Okay, now why do I say that this is a bad example of code? First thing, if there is anything that happens in the try block, rest assured that the program flow will jump directly to the catch statement and the close method invocation will never be reached and the files will be stuck on system unless the app was terminated.

The code was supposed to be written like this:


public void readFile(String filePath){
  
  FileInputStream fis = null;
  FileOutputStream fos = null;

  try {

    fis = new FileInputStream("inputFile.txt");
    fos = new FileOutputStream("outputFile.txt");

    ...whatever file processing here...

  } catch (Exception e) {

    e.printStackTrace();

  } finally {

    try {

      fis.close();
      fos.close();

    } catch (Exception e) {

      e.printStackTrace();

    }

  }

} //end of readFile method


Now, the changes are highlighted in blue and the font was made bold. Right now, no matter what happens, the streams will always be closed unless you put a System.exit() somewhere before the finally block is reached.

I really hate when my app causes memory leak from using a third party API because of this. And this is also the cause of people saying that Java programs are causing memory leaks. The actual fault lies at bad codes written by incompetent developers. If you are writing an API, make sure that the code is well written! be responsible!

Now, time to get some sleep. Urgh!