Introduction

You are currently browsing the weblog archives for November, 2004.

Archive for November, 2004

Sunday, November 21st, 2004

Naming a method ’set’

Be careful when you name a method ’set’ because this could cause unexpected behaviour. I stumbled across this when trying to figure out why my setAll-method in the org.as2lib.data.holder.list.PriorityList-class was not working. All I did was looping over a list and calling the set-method for each element. But the set-method strangely never got invoked.

  1. /**
  2. * @author Simon Wacker
  3. */
  4. class PriorityList {
  5.   public function set(index:Number, value):Void {
  6.     trace("About to invoke set(..).");
  7.   }
  8.   public function setAll(Void):Void {
  9.     set(0, "value");
  10.   }
  11. }

As you can see there are only two methods ’setAll’ and ’set’. And the setAll-method calls the set-method. One would expect the output ‘About to invoke set(..).’ when using the following test code.

  1. var list:PriorityList = new PriorityList();
  2. list.setAll();

But what happens is actually - nothing. You must change the call to the set-method as follows.

  1. /**
  2. * @author Simon Wacker
  3. */
  4. class PriorityList {
  5.   public function set(index:Number, value):Void {
  6.     trace("About to invoke set(..).");
  7.   }
  8.   public function setAll(Void):Void {
  9.     this.set(0, "value");
  10.   }
  11. }

Note the added ‘this’.
So, be careful when naming your methods like a keyword.