views:

1763

answers:

23

I find myself repeating some mistakes over and over again. Some language-dependent, some not. Here are some of mine I could think of right away.

PHP:

  • Inside a class method, forgetting that I have to say "$self->some_method()" or "$self->some_attribute" instead of "some_method()" or "$some_attribute" to refer to my instance.

  • Having a deservedly global object like $db or $facebook, then trying to call it from inside a function and wondering why that doesn't work. Oh yeah, "global $facebook".

  • Trying to return multiple values from a function by saying "return list($a, $b)" instead of "return array($a, $b)".

Python:

  • Getting wrong argument count errors because forgetting that "self" has to be first arg.

Actionscript:

  • Creating a MovieClip object, wondering why it doesn't appear at all. Oh yeah, forgot to do "addChild(obj)".

Objective-C:

  • After switching back after coding a while in some other language, I find myself trying to call methods using dot notation "object.method", instead of "[object method]".

Javascript:

  • Manipulating DOM styles but forgetting to say "style". For example "document.getElementById('thing').opacity = 0.5;"

Perl:

  • echo "hello world". Huh, what's wrong? ;)

Any language:

  • Adding a new argument to a method, but forgetting to add that to the place(s) calling it.

  • Creating a method, but forgetting to call it at all.

I could go on and on, but I would rather be reading about what your common little mistakes are :)

Related:

What is your (least) favorite syntax gotcha?

+1  A: 

General:

Using unit test framworks which don't have automatic registration of the tests, so when you add a new test you forget to add it to the suite and your test never runs.

PHP:

Stupid scoping rules causing me to modify variables instead of creating new ones

e.g.


$x = 5;

if(...)
{
  foreach($something as $x) // OOPS MODIFIED the $x outside the current context
  {
   ...
  }
}

//$x is probably no longer 5
grepsedawk
Always see your tests fail! You don't forget the registration (or other dumb things) if you have seen it run.
Dustin
+6  A: 

Pitfalls of C-style Syntax

Although I usually catch myself, here are some common mistakes that can be caused in many languages with C-style syntax:

if (condition = true)
    some_function();

(This can be circumvented by putting the condition first and the variable second, i.e. true == condition, so mistyping the = for the == will cause a compile error rather than a runtime bug.

The Misplaced Semicolon

for (i = 0; i < some_value; i++);
    function_always_performed();

This is probably an example of just having to keep a close eye for that semicolon. I suspect good compilers will catch this one.

As Software Monkey pointed out in the comments, requiring the use of braces for all instances of if and for will reduce the risk of causing these types of errors, and at the very least will allow the compiler to catch unreachable code blocks.

That reminds me of another danger.

Danger of Indentation and Its Intention

It's nice shortcut to be able to leave off braces when writing a if or for statement with one line of execution connected to it:

if (condition == true)
    do_something();

However, when adding a line or two to that statement, it's possible to mistakenly do the following:

if (condition == true)
    do_something();
    do_something_new();

And, there will be a bug where the do_something_new() is executed everytime, regardless of condition. The indentation seems to have the intention to have the do_something() and do_something_new() functions executed as a block, but the code itself says otherwise due to the lack of braces.

The most painful could be:

some_condition = true;

while (some_condition == true);
{
    do_something();
}

Hello infinite loop! (Althought, this one seems to be caught as "unreachable code" by javac.)

coobird
Both of the first two problems are habitually eliminated by *always* requiring {} for if's, loops, etc; even the empty loop case is best done with for(...) {;} to honor the {} requirement. IMHO.
Software Monkey
You're absolutely correct, I was thinking about writing that as a way to avert the problem, but got caught up in thinking of more examples. Thanks for pointing that out!
coobird
@Software Monkey : adding {} after ifs and loops wont resolved the problem of the misplaced semicolon (at least in java, I'm pretty sure in C/C++ also) since it will be considered as a new level of scope.ex: if(something ==true);{ //something can be false here}
Julien Grenier
The other way of handling the single-line for/if/other is to require that a single-statement block always be on the same line as the for/if/other. If that ends up being hideously long for a single line, then use the curly braces.
Paul Marshall
If you have a bool data type, there's really no reason to check for condition == true, if you just use the bool as in if(condition) you're never going to use the assignment operator by mistake. Fortunately some languages such as C# doesn't even allow assignment in this context.
Brian Rasmussen
@brian: do you mean something like Boolean myBool = true; if(myBool) SomeMethod(); ? If so, then that's perfectly valid in C# - and I do it all the time.
SnOrfus
@SnOrfus, no, he means that you can't do if(mybool = true) in C#, the compiler will warn you. SO ALL YOU C AND C++ OLDIES CAN STOP WRITING if(true == mybool) !!
Benjol
+2  A: 

Not checking for null would be the most common mistake I see.

The first person who manages to write a static analysis tool to eliminate this type of defect entirely will quickly find themselves in Cyril Sneer territory.

Simon Johnson
Two answers to that, mutually contradictory: (1) yes, because in particular they will have solved the Halting Problem, which is provably impossible (Turing, 1936), or (2) just use references instead of pointers ;-)
Steve Jessop
...The Raccoons will come in and thwart him?
Ryan Fox
ReSharper can do this fairly well.
Joe Behymer
+1  A: 

Re Python.

  • Use a decent editor that integrates pyChecker and you will not make that mistake.

Here are some of the python quirks I've spent countless hours debugging.

  • from my_module import * also imports not only classes/methods that are defined in that file but also ones imported by that module
  • It's too easy to hurt yourself when overriding _ getattr _. Also always forget which of _ getattr _ vs _ getattribute _ are OK to use and which is not.
  • Why do I have to implement _ _ne __ when I already implemented __ eq __
Kozyarchuk
+2  A: 

This is a common mistake that I've seen a couple of times in C#:

private int myVariable;
public int MyVariable
{
    get
    {
        return MyVariable;
    }
    set
    {
        MyVariable = value;
    }
}

The code will compile without problems but you'll get a nice stack overflow at runtime :P

Fortunately, this disappears with C# 3 auto properties!

CMS
I am not that familiar with C# - why does this SO?
Software Monkey
Look the uppercase M on the MyVariable public property, when you access that property though the getter, it returns itself (this makes another get recursive call) and you get there an endless call stack loop (notice also the private field myVariable it's unused),
CMS
We use a different naming convention, and I have never seen this mistake in actual code, so maybe you should consider a different convention.
Brian Rasmussen
If the property name is MyVariable then I use _MyVariable or MyVariablePropertyHolder to store the private property values.
Stefan
Yeah this one catches me plenty. Something to do with too little sleep and too much coffee:).
MBoy
don't have my ide on me, but iirc, won't the ide throw a cyclic dependency error at compile time?
SnOrfus
Jeff
@Brian, we have naming convention as well, but I got caught out by this one when overriding a property - wanted base.MyVariable but put this.MyVariable...
Benjol
+8  A: 

Cut and paste errors. I often cut and paste a snippet of code to modify elsewhere (often as small as single line), and forget to change some crucial part of it for the new usage.

Scotty Allen
Or worse, you copy the comment with the code, and change the code, but not the comment :(
Benjol
A: 

Accidentally defining a new local variable when I meant to refer to a class variable:


public class Thing {
  private int value;

  public void setValue(int n) {
    int value = n;  // Oops...
  }
}
David
+2  A: 

Not actually overriding a method from a superclass, because the method signature is wrong:

public class Object {
  public boolean equals(Object o) {
    // ...
  }
}

public class Thing extends Object {
  public boolean equals(Thing t) {  // Oops, this doesn't override equals(Object)!
    // ...
  }
}

(Fortunately in Java, the @Override annotation and generics can both help make this problem go away)

David
A: 

Heyall,

Since I program in a few different languages for different projects, the basics spooks me, like the most common: using . instead of + or using + instead of . to append strings.

A not common mistake but happens sometimes is getting an old code in PHP after a few days working with Java and write a few lines of code using the arrays as collections...

<?php
  // old code

  $itemList = array()
  $itemList[0] = "spoon";
  $itemList[1] = "fork";

  ... several lines and days later ...

  // Can't figure why this do not work :p RTFM later
  // $itemList.add("knife");
?>
Fernando Barrocal
When switching back and forth between languages, i've developed the habit of actually checking the proper string append operator by actually pulling up an interactive interpreter and trying it. Days of my life i'll never get back.
TokenMacGuy
A: 

I can think of two things in C

if( x = 5)  //Whats wrong here :p 

{

  //your code goes here

}



switch(variablename)

{

  case 1:

     //your code here

     break;

  case 2:

      //your code here

      //forget break here

  case 3:

      //your code here

      break;

   default:

      break;

}
hmm
+11  A: 

In my initial days of programming, I frequently made this mistake. Apparently its not only me !! Java Puzzlers has the following code snippet saying that someone reported this as a Java platform bug :)

public class ApplePie {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++); {
            count++;
        }
        System.out.println(count);
    }
}
Vijay Dev
Youch! Danged semicolon!
David
Good one! It took a moment to spot.
Brian Rasmussen
I've never done this but since it took me way too long to spot, I definitely up-voted it.
Dinah
but with if statement!!
yesraaj
There's actually quite a few mistakes there. For example, i and count both serve as a loop counter (if you hadn't misplaced the semi-colon). Use one or the other. That loop does nothing. And you have a useless argument "args".
Wallacoloo
Having i and count is not a logical bug. Also, args is part of the signature of the main method in Java, even if it's not used.
Vijay Dev
+17  A: 

Where I work, we call these "Programming Tips of the Day". They include such gems as:

  • Changes not taking effect? Try compiling!
  • Compile step suspiciously fast? Try saving!
  • Program doesn't do anything when you start it up? Did you spell 'main' correctly?
  • If your data isn't being processed, perhaps it's because you haven't written the part that actually does the work.
  • If the program fails to run the first time, running it a few more times will not "Work the kinks out"
  • When you hear the words "in theory", drink!
Atiaxi
lol @ 1,2, and last one
Gotta love a workplace that, at least in theory, promotes drinking!
Dave Sherohman
What's even worse is if running the program a few more times DOES "work the kinks out". Then you've not only got a bug, you've got a bug that you no longer know how to reproduce :(
Jeremy Friesner
A: 

I use C# on a daily basis and occassionally try to check for a non-null object in a conditional in the C/C++ way:

string foo=GetString();
if(foo)
{
  Console.WriteLine("not null");
}

I kinda miss not being able to do this...!

Sean
A: 

When writing a varargs function in C, I always forget the order of arguments in the va_start macro. Is it:

va_start( last_arg, list );

or

va_start( list, last_arg );

Answer: the second one, but I have to look it up every single time.

Graeme Perrow
+1  A: 

Infinite loops - in classic ASP/JavaScript, I always used to leave out the recordset MoveNext() when looping through results and hang my dev server, even after five years of being an ASP developer...

while(!recordset.EOF)
{
    // Do something here - FOREVER...
}
Mark B
A: 

putting

cout << "wtf?"

in a PHP file, or

echo "wtf?"

in a Perl file, or

for(int i=0;i<100;i++)

in a Verilog file, or....the list goes on :(

Majd Taby
+2  A: 

Blaming the compiler/linker/IDE for a bug, anything or everything except my code.

jpoh
I see this often with new folks, but most senior developers have been proved wrong on this so many times that they blame the language implementation (or compiler, etc) very last.
Joe Behymer
+18  A: 

Thinking I can make an accurate estimate for any period of time over about 4 hours.

le dorfier
I wish I could upmod more than once. I'm equally terrible at this.
SnOrfus
I find the best way to give an accurate estimate is to do the work first, then give the estimate.
Dave Kirby
A: 

these days, closures in javascript:

var foo = "bar"
return function () { twiddle(foo) }

Doesn't work, usually should be

var foo = "bar"
return function() { function() { twiddle(foo) } }()

GAH! had to fix that about 6 times in as many days.

TokenMacGuy
+1  A: 

I like to think that I learn from my mistakes but I often do something like the following:

foreach(MyObject obj in MyObjectCollecion)
{
    remove(obj); // OOPS enumerator no-longer valid now
}
SnOrfus
A: 

VB6: adding an On Error Goto Label, then forgetting the Exit sub before the error label.

All languages: always trying the wrong one (and getting the parameters in the wrong order) for Instr, indexOf, Contains, charIndex (etc..)

Benjol
A: 

I did this just now... I had to test the sign of one number and set the sign of the other number to the same sign.

if(a > 0.0f){
    if(b < 0.0f)
        b -= b;
}
else if(a < 0.0f){
    if(b > 0.0f)
        b -= b;
}

That should have been:

if(a > 0.0f){
    if(b < 0.0f)
        b = -b;
}
else if(a < 0.0f){
    if(b > 0.0f)
        b = -b;
}
Vulcan Eager
Why not just `if (sgn(b) != sgn(a)) b = -b;`? Also, what about 0?
Konrad Rudolph
Good point about 0. Now if only I can find that code somehow...
Vulcan Eager
A: 
typedef unsigned char UINT8;

void Foo( void )
{
    UINT8 i;

    for( i = 0; i < 256; i++ )
    {
     // Do something
    }
}

Oops! - It's an infinite loop

Vadakkumpadath