Too many tiny functions?

Posted on July 29, 2012 | 2 minute read

When do you have too many functions? For me breaking things down into functions makes it easier to read in many cases, but I’ve been hesitant to separate out everything into tiny bits and pieces. Let’s say someone else is looking at my code - does it get to a point where generally it’s just too much? For example, what would generally be considered better, this:

init: function( x, y, settings ) {
        this.parent(x, y, settings);
        this.vel.y = this.maxVel.y;
        if( !ig.global.wm )    {
            if (this.kind === null) {
                var rand = ig.game.Controller.randomFromTo(0,2);
                switch (rand) {
                    case 0: 
                        this.kind = 'grenade';
                        break;
                    case 1:
                        this.kind = 'rewind';
                        break;
                    case 2:
                        this.kind = 'flash';
                        break;
                }

            }

        }
        this.setAnimations(this.kind);
    },

Or this:

    init: function( x, y, settings ) {
        this.parent(x, y, settings);
        this.vel.y = this.maxVel.y;
        if( !ig.global.wm )    {
            if (!this.kind) {
                this.kind = this.setKind();
            }
        }
        this.setAnimations(this.kind);
    },
	
    setKind: function() {
        var rand = ig.game.Controller.randomFromTo(0,4);
        switch (rand) {
            case 0: 
                return 'rewind';
                break;
            case 1:
                return 'grenade';
                break;
            case 2:
                return 'flash';
                break;
            case 3: 
                return 'speedup';
                break;
            case 4: 
                return 'slowdown';
                break;
        }
    },

(I know the second version has more in the list of options, that’s just because the first version was taken from an older commit).

I know that different people might do things differently, but in general is one of the above options considered better than the other? To me option two seems more readable personally, but I’ve been staying away from doing this sort of thing because is it really worth putting just one switch statement into its own function? Would it just create a big mess of little functions in the long run?




Categories:game dev dev games
comments powered by Disqus