Consolidate Duplicate Conditional Fragments

The same fragment of code is in all branches of a conditional expression.

Move it outside of the expression.


		if (isSpecialDeal()) {

			total = price * 0.95;

			send();

		}

		else {

			total = price * 0.98;

			send();

		}


		if (isSpecialDeal())

			total = price * 0.95;

		else

			total = price * 0.98;

		send();

For more information see page 243 of Refactoring

Additional Comments

Using with try/catch blocks

Paul Haahr rightly took me to task for being far too glib when I talked about consolidating with exceptions. You can only pull repeated code into a final block if all non-fatal exceptions are caught. This is because the finally block is executed after any exception, including those that don't have a catch clause. (Of course you may prefer that to happen, but that's not a semantics preserving change.)

Contributors

| Refactoring Home | | Alphabetical List |