Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java Best Practises - Create variable for return statement?

Assume there is no further (manipulating) action taken on the variable and it is just used for holding the return data. Is it better to create a variable or directly return the data here?

Example:

/* Is this considered ok? */

public String getFormattedTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
        formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone()));
        Date dateTime = new Date(getTime() * 1000);
        String timeString = formatter.format(dateTime);
        return timeString; // <---
    }

/* Or should I use that? */

public String getFormattedTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
        formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone()));
        Date dateTime = new Date(getTime() * 1000);
        return formatter.format(dateTime); // <---
    }

Craig Dennis Ben Jakuben

Scott Evans
Scott Evans
4,236 Points

As far as i'm aware, although I'm not 100% on Java Best practices, the logical part of my brain tells me that the 2nd option would be preferable. This is to save the memory used when assigning the variable in the first option.

This is not a definitive answer, but purely a educated opinion.

Hi Scott, thanks for your answer! I also think that the second one is better and saves resources. Let's see what others have to say :)

2 Answers

Hi Philip,

Just return it, I think. One less variable to worry about and the longer form of it doesn't add much in way of clarity. IDEs will tell you to refactor that variable out and use the direct return method and they're optimised using best practices.

Steve.

Hi Steve, Thanks for confirming that to me. I think it's clear for me now

No problem! :-)

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Yep +1, like Nike said "Just Return It" ... or something like that.