Core Java

Comments Suggesting Refactoring

Allow me to share with you one of my favourite refactorings.

This comment in the code indicates a missing extract method refactor

A simple example:

const customer = getCustomer();

// find the customer's discount rate
const customerPoints = customer.loyaltyPoints + customer.weeklyPoints;
const discountRate = customerPoints > 100 ? 0.1 : 0;

return price - (price * discountRate);

The interesting part of the above is the two lines in the middle. There’s a short deviation in the implementation of THIS function to go off and work something out that’s needed later.

The comment find the customer's discount rate tells you the name of the function you wish you had:

const customer = getCustomer();

const discountRate = findCustomerDiscountRate(customer);

return price - (price * discountRate);

And the implementation can go and live in that function. That function is single responsibility and operates at its own level of abstraction.

Job’s a good’un.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: Comments Suggesting Refactoring

Opinions expressed by Java Code Geeks contributors are their own.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button