Question

There are quite a few of IRC server codes

I am working on a small IRC client for Adobe AIR, and I started out by supporting only a few of these initially, and then a switch statement didn't seem like a bad idea. But as I support more and more, the switch statement is getting longer and it feels like it's a little out of control. One issue is that I've kept the low level IRC handling code in a file on its own so that it can be reused. I would like to keep everything in one file. Another issue is that code blocks in the switch statements currently assume to be part of this IRC class and there's frequent use of the this statement. Making changes now would be a lot of work and introduce regressions. The only problem really is my distaste for a long switch statement, otherwise you know it works, and it's kind of easy to read, but not really making it more difficult to maintain. But it's such a long switch statement. And the function that contains the switch statement is obviously long too. ://

One thing I sometimes do in lieu of a switch is that I define functions that are named after the value the switch evaluates. Instead of a switch:

switch ( val ) {
  case: "alert":
    alert( "yo" );
    break;
}

I check to see if a method exists in scope and execute it:

obj.alert = function ( ) {
  alert( "yo" );
}

if ( val in obj && isFunction( obj[ val ] ) ) { 
  obj[ val ]( );
}

But again in this case I've feel like there's a high risk in regressions and I'm not sure it's worth the effort only to avoid having a long switch statement, for the sake of its length.

Was it helpful?

Solution

Why don't you keep a hash (a JavaScript {} object) with the code as the key and the function as the value? Then, for small pieces of code you could use an anonymous function, and for bigger pieces of code you could just have a reference to an already written function. I don't know anything about IRC, but here's a small example:

var CodeHash = {
    001: function() { /* Do something... */ },
    002: BigImportantObject.someFunction
}

Kind of a bad example, but you get the idea.


Edit: If you believe that you can maintain such a long switch statement easily and without problems, then I think it's ridiculous to rewrite your program just to remove the switch. But I know that I, personally, would much rather maintain a hash table like above than a huge switch statement, for many reasons. So it's up to you. Seems like a rhetorical question if you keep insisting that the only reason you'd rewrite your code is to get rid of the switch statement.

OTHER TIPS

why not keep the switch in a parameter file with predefined exit points along with their arguments read the file at the startup and keep in in memory

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top