Recent Post

Categories

Archives

Cow Computing

09 Sep 6

JAVA Substring Bug!

Sometimes, when we are working with string in java, we are always tempted to use the substring method for extracting part of a string. It’s neat and efficient when you are working with small program or little string processing. However, this method is evil. It is actually causing you whole lots of problem. The substring returns the part of the original string rather than a new one. Thus, GC wont collect the original string. So when the file or string get larger and larger, it’s actually taking up more and more memory, and thus OutOfMemory Error. To solve this, there’s nice workaround which is simple.

String newString = new String( oldString.subString(0, 5) );

Simple, Right?!

09 Sep 6

How to Write Better Code

1. Use Descriptive Variable Names.

Never ever try to use meaningless or single-character name for variables. This could mess up the whole class. Even when doing temporary storage, we should stick to some kind of rules like, having a prefix of “tmp” followed by meaningful name.

2. Remove unnecessary header

Not only will this save the time of code compilation but also reduce the ambiguity when using certain implementation type.

3. When reusing code, NO CUT & PASTE

There’s always moments when we want to perform some sort of operation that has been coded before. DON’T COPY & PASTE. Rather, we should create a function to encapsulate them, and reuse it. This does not only reduce lines of code, but also provide more clean and generic approach on refactoring code which could ease the trouble of test-case writing.

4. Know what you are CATCHING

Catching exception has been widely adopted in java and it’s sort of compulsory. In CECID’s code base, this is true as well. So one important thing to note is that, we should understand what we are catching when writing “catch”. Often eclipse and other IDE will generate codes for you. But, do you know why? Always include useful error code/warning rather than empty catch blocks.

5. Don’t retain something useless

Often functions are written to return value. However, this does not necessary mean you MUST store that return value. Sometimes, in certain circumstances, return value are useless, don’t keep them, it could create confusion. When you keep them, i would expect it to be used somewhere.