Forum

Refactoring if/else logic

2 Replies Posted since 26/05/2010

  • Adam Gent's profile image

    Member
    Adam Gent

    1 Posts

    Refactoring if/else logic

    I have a java class with a thousand line method of if/else logic like this:

    if (userType == "admin") {
    if (age > 12) {
    if (location == "USA") {
    // do stuff
    } else if (location == "Mexico") {
    // do something slightly different than the US case
    }
    } else if (age < 12 && age > 4) {
    if (location == "USA") {
    // do something slightly different than the age > 12 US case
    } else if (location == "Mexico") {
    // do something slightly different
    }
    }
    } else if (userType == "student") {
    if (age > 12) {
    if (location == "USA") {
    // do stuff
    } else if (location == "Mexico") {
    // do something slightly different than the US case
    }
    } else if (age < 12 && age > 4) {
    if (location == "USA") {
    // do something slightly different than the age > 12 US case
    } else if (location == "Mexico") {
    // do something slightly different
    }
    }

    How should I refactor this into something more managable?

  • martin's profile image

    Member
    martin

    2 Posts

    Replied at 17:25 - 23/07/2010

    Re: Refactoring if/else logic

    I'm not a Java developer, but I'm guessing finding logical breaks in the if/else statements that can be encapsulated into their own methods, or even their own classes.

  • Stephen Dryden's profile image

    Member
    Stephen Dryden

    1 Posts

    Replied at 17:24 - 30/07/2010

    Re: Refactoring if/else logic

    I'm also not a Java developer but is there not some sort of switch case statement which might make it more manageable. For example in c# it's something like this...

    switch (values to be tested)
    {
    case (value outcome 1):
    //do something
    case (value outcome2);
    //do something
    }



  •  

    You must be logged in to post replies

  • Page 1 of 1

Back to top

Sunderland Software City, Evolve Business Centre,
Cygnet Way, Rainton Bridge South Business Park,
Houghton Le Spring, DH4 5QY

Site by SUMO