The Coded One

programming, algorithms, discrete math, open-source

Posts Tagged ‘coding practices

Writing Better Conditional Statements

leave a comment »

1. Use 1 == foo instead of foo == 1.  Srsly.

At a glance, you might think that the following statements are the same as dictated by logic and the property of commutativity.

if( foo == 1 ) {
...

and

if( 1 == foo ) {
...

Well logically yes, but in a pragmatic point of view, the second one is better because it makes the compiler barf an error whenever you’re in a zombie programming mode and you write = (which assigns the value to the variable instead of checking for equality) in lieu of ==.
I just can’t imagine how much time I spent debugging before, only to find out that I missed a single character.

2. Proper use of .equals

First of all, when comparing strings, always use .equals. The == operator compares references and not values.
Now, if you're checking for a "" or a null string, use the following form:

if( "".equals( foo ) ) {
...

This way, you do not get a Null Pointer Exception whenever the variable is null.

Written by Mark Basmayor

February 28, 2009 at 4:49 pm

Applying the Pareto Principle in Coding

leave a comment »

The Pareto principle (also known as the 80-20 rule, Haddad’s Theorem, the law of the vital few and the principle of factor sparsity) states that, for many events, 80% of the effects come from 20% of the causes. (http://en.wikipedia.org/wiki/Pareto_principle)

In programming this translates to, avoiding 20% of the bugs when writing code will reduce the effects of horrible bugs by 80%.

Less code = less bugs, no code = no bugs ? LOL

Written by Mark Basmayor

July 13, 2008 at 9:28 pm

Best Coding Practices List

leave a comment »

These are some of the things that I learned from the talks made by our lead programmer Travis Low.

  1. If you find it too cumbersome to use very long variables, it’s ok to use shorthands or abbreviations but remember to refactor them later.
  2. Don’t use variables for multiple purposes.
  3. Avoid ifs.
  4. Use existing code .
  5. Publish code up into API/superclass.  Generalize to allow future changes.  E.g. wrappers, etc.
  6. Less code, less bugs.
  7. Think ahead.  Provide blank method definitions for very common methods or procedures.  E.g. checkForm()  Similarly, if you expect to use a parameter in the future, include it beforehand.
  8. If you’re as smart as you can be, how can you debug it?  Don’t try to put very fancy/technical codes because if something goes wrong in that code, you won’t be able to debug it.
  9. Be forgiving in your code, do not try to fix some data which will cause the system to break… instead try to correct the problem as you go or when instantiating
  10. Make someone want to use your code
  11. Don’t use double negatives when naming booleans.

Written by Mark Basmayor

April 3, 2008 at 2:50 am

Follow

Get every new post delivered to your Inbox.