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

Android Build a Weather App (2015) Working with JSON Setting CurrentWeather from JSON

boog690
boog690
8,987 Points

Custom constructors vs. multiple setter methods

So this is a more general question though it applies to this video.

In the video, Ben Jakuben uses multiple setter methods to populate the member variables of the CurrentWeather object. If I had been doing this without the video, I probably would have created a custom constructor such as:

CurrentWeather currentWeather = (String icon, long time, double temperature, double humidity, double precipChance, String summary) {
    mIcon = icon;
    mTime = time;
    mTemperature = temperature;
    mHumidity = humidity;
    mPrecipChance = precipChance;
    mSummary = summary;
}

My questions are:

1) When should I be using multiple setter methods rather than customer constructors (and vice versa)? Is this a matter of personal preference?

2) Are there any advantages/disadvantages in picking one over the other?

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Recently I read the excellent book Effective Java, and in it he suggests that if your constructor has more than 4 parameters, that you should think about using the builder pattern. This Stack Overflow answer does a really good job explaining the logic.

On the difference between setters and constructors, you should think about whether you want it to be changed, or mutable, after creation. If not you should just initialize it in the constructor keeping the field therefore immutable (unchangeable). It's all about intention and how you expose what people can do with your object.

Hope that helps! Let me know if I just confused matters more ;)