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 trialPavel Razuvayev
4,128 PointsWhy not switch statement?
Why not use switch statement here instead of multiple else ifs? Is this arbitrary decision?
4 Answers
Kevin Haube
12,265 PointsIt may be bcause this video is still a beginner video, and thet may have not been covered (not too sure, but it's a guess). I went ahead and used a switch:
public int getIconId() {
int iconId;
switch (mIcon) {
case "clear-day":
iconId = R.drawable.clear_day;
break;
case "clear-night":
iconId = R.drawable.clear_night;
break;
case "rain":
iconId = R.drawable.rain;
break;
case "snow":
iconId = R.drawable.snow;
break;
case "sleet":
iconId = R.drawable.sleet;
break;
case "wind":
iconId = R.drawable.wind;
break;
case "fog":
iconId = R.drawable.fog;
break;
case "cloudy":
iconId = R.drawable.cloudy;
break;
case "partly-cloudy-day":
iconId = R.drawable.partly_cloudy;
break;
case "partly-cloudy-night":
iconId = R.drawable.cloudy_night;
break;
default:
iconId = R.drawable.clear_day;
break;
}
return iconId;
}
Edward C. Young
10,323 PointsI'd love to see this integrated into the video, even for beginners, as it prevents what I like to call the "nesting syndrome." Thanks as this is the approach I chose.
Ruan Lopes de Souza
4,854 PointsI couldn't find the release date of this video to confirm @Stefan answer but I personally think he optionally decided to use elseIf instead of Switch case
Samuel Tissot-Jobin
7,350 PointsI had a different approach (see: alternative-ways-of-getting-the-icon-id) that would be good if we had lots of possibilities. However, I think the swith/case statement in this case will be less resource intensive, especially compared to my implementation.
cheers
Taylor Bryant
7,395 PointsI see that you used an int variable of iconId and set it to that and returned it later. Why did you opt for this instead of having each case use a return statement?
Edward C. Young
10,323 PointsBecause the last bit of the switch structure contains the return statement. Notice that each case contains a break statement, and after breaking the return statement is executed.
Stefan Kaczmarek
21,228 PointsStefan Kaczmarek
21,228 PointsIt is probably because switching on a String is actually a fairly recent addition to Java / Android: http://stackoverflow.com/questions/14367629/android-coding-with-switch-string