-3

Consider the scenario:

List<String> weekdays = Arrays.asList("sun", "mon", "tue");
long sunTemp = 0;
long monTemp = 0;
for(String day : weekdays){
  if(day.equals("sun"){
  sunTemp = getSunTemp();
  }else if(day.equals("mon")){
  monTemp = getMonTemp();
  // use sunTemp ex: totalTemp = sunTemp + monTemp
  }
  //...more code
}

What, if anything is wrong with the above?

The following stand out as awkward to me:
- usage of the for loop
- assigning a value in the 'if block' and use it in the 'else block' the next iteration.
- Code depending on the pre-knowledge of data (order and exact values the list.)

Can someone put in formal terms what is correct or wrong with the above?

Thanks much!

Gadam
  • 2,674
  • 8
  • 37
  • 56
  • 1
    What's the point of this code? Why not just do `long sunTemp = getSunTemp(); long monTemp = getMonTemp(); ... long totalTemp = sunTemp + monTemp + ...`? – shmosel Nov 08 '16 at 03:21
  • 1
    What is the code for, What are you trying to achieve, Can you please provide more details – Venkat Nov 08 '16 at 03:22
  • for loop is for iterating weekdays List's component which is "sun", "mon", and "tue". – KHW1031 Nov 08 '16 at 03:23
  • You can try switch instead of if..else – Venkat Nov 08 '16 at 03:24
  • Also,you can use getTemp() with a parameter passed to know the Day , instead of creating multiple methods like getaTemp(),getbtemp(). – Venkat Nov 08 '16 at 03:25
  • @shmosel, The point is that the first two elements will have some information that will be used to process the remaining elements in the list. I agree a better way would be to pull the first two elements out of the loop, get the data needed to process remaining elements and then loop through 2-n elements. But the above is someone else's code and I am trying to communicate what is wrong with it. The bigger question is, can a pre-knowledge of what is in the list be used to define how to code your loop?Should your logic be dependent on the data values? – Gadam Nov 08 '16 at 04:13
  • I think an enum would be more suited, but it's hard to property answer in the abstract, and I'm not sure this is the right forum altogether. You might want to take some real code and head over to codereview.stackexchange.com. – shmosel Nov 08 '16 at 04:16
  • @shmosel Thanks, that seems a good idea. I will do that. – Gadam Nov 08 '16 at 04:19

1 Answers1

-3

The brackets are not needed for one liner if/else statements, but other than that it seems fine.

Toxxic
  • 85
  • 7