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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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 ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
Inline Feedbacks
View all comments
Back to top button