Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Philip G
14,600 PointsJava 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); // <---
}

Philip G
14,600 PointsHi 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

Steve Hunter
57,684 PointsHi 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.

Philip G
14,600 PointsHi Steve, Thanks for confirming that to me. I think it's clear for me now

Steve Hunter
57,684 PointsNo problem! :-)

Craig Dennis
Treehouse TeacherYep +1, like Nike said "Just Return It" ... or something like that.
Scott Evans
4,236 PointsScott Evans
4,236 PointsAs 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.