I was wondering if there was a better alternative then using this break implementation. I’m trying to improve my abilities and the following does indeed work. Its just that i keep hearing about Break; as being the easy way out and produces potential spaghetti code which hasn’t happened here but still.
public void getWoodSoldRecently(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -2);
for(Tree t : theTrees){
if(t.getSimpleDateSold().getTime().after(cal.getTime()) && t.getHasBeenSold()==true){
treesSold.add(t);
System.out.println(t.getTreeId() + " " + t.getTreeType());
}
else{
System.out.println("Nothing sold in the last 2 weeks");
break; //Stop the above
}
}
}
Without the break the “Nothing sold in the last 2 weeks” would output the amount stored in the array.
Since you arent doing anything after the break, if it occours. You might aswell replace it with return.
}
I personally have no broblem with breaks, however return forces you to encapsulate code into more functions, wich is always good.