Skip to content

Gendarme.Rules.Smells.AvoidSwitchStatementsRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

AvoidSwitchStatementsRule

Assembly: Gendarme.Rules.Smells
Version: 2.10

Description

This rule checks for the Switch Statements smell. This can lead to code duplication, because the same switch could be repeated in various places in your program. Also, if need to do a little change, you may have to change every switch statement. The preferred way to do this is with virtual methods and polymorphism.

Examples

Bad example:

int balance = 0;
foreach (Movie movie in movies) {
    switch (movie.GetTypeCode ()) {
        case MovieType.OldMovie: {
            balance += movie.DaysRented * movie.Price / 2;
            break;
        }
        case MovieType.ChildMovie: {
            //its an special bargain !!
            balance += movie.Price;
            break;
        }
        case MovieType.NewMovie: {
            balance += (movie.DaysRented + 1) * movie.Price;
            break:
        }
    }
}

Good example:

abstract class Movie {
    abstract int GetPrice ();
}
class OldMovie : Movie {
    public override int GetPrice ()
    {
        return DaysRented * Price / 2;
    }
}
class ChildMovie : Movie {
    public override int GetPrice ()
    {
        return movie.Price;
    }
}
class NewMovie : Movie {
    public override int GetPrice ()
    {
        return (DaysRented + 1) * Price;
    }
}
int balance = 0;
foreach (Movie movie in movies) {
    balance += movie.GetPrice ()
}

Notes

  • This rule is available since Gendarme 2.4
Clone this wiki locally