Andrew
Andrew

Reputation: 1650

How can I refactor a conditional statement that happens twice?

Can I remove the second conditional to check if a course is full and improve readability?

...    
if (course.isFull()) {
  attemptStudentCapacityIncrease(course);
  if (course.isFull()) {
    // could not increase course student capacity
    return;
  }
}
// course is not full
...

Upvotes: 0

Views: 92

Answers (3)

tim
tim

Reputation: 2039

You could also throw a custom exception.

if (course.isFull()) {
    try {
        attemptStudentCapacityIncrease(course);
    } catch (IncreaseCourseException ice) {
        return;
    }
}

I think that it is nicer than returning a boolean vlaue in attemptStudentCapacityIncrease, but it is less efficient, so it depends on how often the method is called in pratice (and what you think looks better)

Upvotes: 0

clime
clime

Reputation: 8885

Make the function so that it returns false upon fail and true upon success.

if (course.isFull()) {
    if (!attemptStudentCapacityIncrease(course)) {
        // could not increase course student capacity
        return;
   }
}

You might also consider to modify the function to throw an exception upon failure, which you then handle like this:

if (course.isFull()) {
    try {
        attemptStudentCapacityIncrease(course);
    } catch (Exception ex) {
        // could not increase course student capacity
        return;
    }
}

But remember to use exceptions only for exceptional situations ;).

Upvotes: 2

harald
harald

Reputation: 6126

Or if you can't change the API's:

int attempts = 3;
while (attempts-- && course.isFull())
    attemptStudentCapacityIncrease(course);

if (attempts == 0)
    return;

Upvotes: 0

Related Questions