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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

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