Have only one exit point from the method. Also, despite being old school, I would iterate using a while loop with a stop condition instead of the for-each.
public boolean checkNamesStartWith(List<Foo> foos, String prefix) {
boolean ret = true;
int index = 0;
while (index < foos.size() && ret) {
ret &= foos.get(index).getName().startsWith(prefix);
}
return ret;
}
Here the while loop will only iterate as long as it doesn't find a foo that starts with the prefix - or will iterate through the whole list. I would also rename the method from checkNameStart
to checkNamesStart
as it iterates through a whole collection, so usually more than one names will be checked.
Or, to preserve readibility, you can use an if condition with a break from the for-each loop:
public boolean checkNamesStartWith(List<Foo> foos, String prefix) {
boolean ret = true;
for (Foo foo : foos) {
if (!foo.getName().startsWith(prefix)) {
ret = false;
break;
}
}
return ret;
}