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) ]
Theme design by Jelle Druyts
Pick a theme: BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2 BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Steven Rockarts
E-mail