I don't think I have ever seen any code which does this, so I was curious, because it seems fairly sound. I need someone to pick a hole in it!:D
public String function() {
String result = "Default Result";
MethodBody:
{
if (condition 1) {
if (condition 2) {
result = "Failure";
break MethodBody;
}
// Do stuff here
result = "Success";
break MethodBody;
}
// Do some other stuff
result = "asdasd";
break MethodBody;
}
return result;
}
Essentially, the important part is the labelled block of code called 'MethodBody'. Instead of having multiple points in the code where I return a result from, I 'break' from this block of code and always return in the same place (at the end of the function). This has the benefit of allowing me to have a 'cleanup' section of the code. For example, I don't need to close a stream 10 different times on different lines of code, I can instead close everything at the end of the function, because I know I'll end up there eventually.
Can't see why this is bad, but I never see it, and I don't know what the pattern would be called, if it is even a pattern. Specifically, using the labelled break statement - is this bad?
Aucun commentaire:
Enregistrer un commentaire