01.02.2013 Views

Software Development Cross Solution - Index of - Free

Software Development Cross Solution - Index of - Free

Software Development Cross Solution - Index of - Free

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

#5. Refactoring<br />

Refactoring is the process <strong>of</strong> modifying the structure <strong>of</strong> your code,<br />

without modifying its behavior. Refactoring is done to increase the<br />

cleanness, flexibility, and extensibility <strong>of</strong> your code, and usually is<br />

related to a specific improvement in your design.<br />

Most refactorings are fairly simple, and focus on one specific design<br />

aspect <strong>of</strong> your code. For example:<br />

public double getDisabilityAmount() {<br />

// Check for eligibility<br />

if (seniority < 2)<br />

return 0;<br />

if (monthsDisabled > 12)<br />

return 0;<br />

if (isPartTime)<br />

return 0;<br />

// Calculate disability amount and return it<br />

}<br />

While there’s nothing particularly wrong with this code, it’s not as<br />

maintainable as it could be. The getDisabilityAmount()<br />

method is really doing two things: checking the eligibility for disability,<br />

and then calculating the amount.<br />

By now, you should know that violates the Single Responsibility<br />

Principle. We really should separate the code that handles eligibility<br />

requirements from the code that does disability calculations. So we can<br />

refactor this code to look more like this:<br />

public double getDisabilityAmount() {<br />

// Check for eligibility<br />

if (isEligibleForDisability()) {<br />

// Calculate disability amount and return it<br />

} else {<br />

return 0;<br />

}<br />

}<br />

Now, if the eligibility requirements for disability change, only the<br />

isEligibleForDisability() methods needs to change—and<br />

the method responsible for calculating the disability amount doesn’t.<br />

Think <strong>of</strong> refactoring as a checkup for your code. It should be an<br />

ongoing process, as code that is left alone tends to become harder and<br />

harder to reuse. Go back to old code, and refactor it to take advantage<br />

<strong>of</strong> new design techniques you’ve learned. The programmers who have<br />

to maintain and reuse your code will thank you for it.<br />

Download at WoweBook.Com<br />

We’ve taken two responsibilities,<br />

and placed them in two separate<br />

methods, adhering to the SRP.<br />

leftovers<br />

Refactoring<br />

changes the<br />

internal structure<br />

<strong>of</strong> your code<br />

WITHOUT<br />

affecting your<br />

code’s behavior.<br />

you are here 4 441

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!