Sunday, October 08, 2006

A lot of complexity in programs comes from complex if-then-else statements. If it takes you a long time to read and understand an if-then-else statement you should take a look at the Decompose Conditional refactoring.

To show you how powerful this can be, from the example below choose which code you think is easier to understand:

Public Sub ProcessPayment() If _view.PaymentType = PaymentType.Cash Then 'payment type is cash Try _task.SaveCashPayment(_view.Amount) Catch ex As Exception _view.ShowMessage("There was a problem saving the payment.", False) End Try _view.CloseView() End If Else 'payment type is credit card If PreAuthorized(_view.Amount)) Then Try _task.SaveCreditCardPayment(_view.Amount) Catch ex As Exception _view.ShowMessage("There was a problem saving the payment.", False) End Try _view.CloseView() End If End If End Sub

Or this code:

Public Sub ProcessPayment() If PaymentTypeIsCash() Then SaveCashPayment() Else SaveCreditCardPayment() End If End Sub

In the first block of code, notice how it takes you a long time to figure out what the code is trying to accomplish while the second block of code reads like a couple of lines of comments.

Also, notice how the first block has a lot of code duplication. Once the SaveCashPayment and SaveCreditCardPayment are moved into their own methods it is a lot easier to recognize this duplication and refactor it

If there are other ways you can think of to refactor this code please post in the comments, I am always looking for ways to make code better.

Update: Check out Jean-Paul Boodhoo's response on how to further  refactor this code.

 

[ Currently Playing : Reign On - The Brian Jonestown Massacre - Bringing It All Back Home Again (4:31) ]

Sunday, October 08, 2006 5:10:59 AM (GMT Standard Time, UTC+00:00)  #    Comments [3]  |  Tracked by:
"Refactoring Ahoy!!" (Jean-Paul S. Boodhoo's Blog) [Trackback]
http://www.jpboodhoo.com/blog/PermaLink,guid,ca05b6e6-4cee-41fc-b0ef-e598308b835... [Pingback]

Theme design by Jelle Druyts

Pick a theme: