Many experienced programmer will lament that GOTO is a bad practice that result in Spaghetti code. Generally a GOTO statement is accompanied by a label argument that been placed within the same method and invoking GOTO will return to the preceding statement where the LABEL is located. GOTO can be a very effective tool in Java that can reduce the number of code, making it more concise and beautiful. Java does not explicitly support GOTO keyword but the BREAK statement is synonymous.
so the format is
LABEL:
{
IF statement
BREAK LABEL;
……
IF statement
BREAK LABEL;
……
}
One of the most commonly uses of this technique is when performing validation.
public class TestGoto
{
public static String getErrorMsg(String _data)
{
String _errMsg = “”;
VALIDATION:
{
if (_data.length() > 10)
{
_errMsg = “ERR: Data length exceed 10 chars”;
break VALIDATION;
}
if (_data.indexOf(“@”) == -1)
{
_errMsg = “ERR: Data did not include @ char”;
break VALIDATION;
}
// Rest of validation statement …
}
// Centralised handling of ErrMsg.
if (_errMsg.length() != 0)
{
_errMsg += “\nPlease fix the error.”;
}
return _errMsg;
}
public static void main(String[] _args)
{
System.out.println(getErrorMsg(“hello today”));
}
}
As can be seen, this technique actually bypass the rest of validation IF statements when preceding IF condition fails. It makes the code more concise without resorting to nested IF-ELSE statement, and also centralised handling of common statement.
Therefore do use GOTO where necessary.
please tell me how can i do something like “repeat VALIDATION”.
i need it in a kind of interface for a program… for example: if the user inserts a wrong character, then “repeat the reading of the character”
thanks in advance
There you want to use a while loop. Have your while conditioned on bad input.
You could easily use a else if instead of breaks here…
Indeed there are lot of ways to accomplish the same task, I just highlight one of the ways (which perhaps quite rarely used as most tend to use if else and other common construct). Use whichever way you feel comfortable with, although sometimes it might be helpful to use different variation just for learning and for widening perspective.
Does your code have a infinite loop ?
seems like in basic
10 goto 10;
As an example, it shows HOW the code is used, but not why you would. The particular section of error handling above looks like it should have been written using Exceptions.
Is there a better example of a place where using this construct can be justifiably better than other means?
There’s no infinite loop. The semantics are not exactly what might be expected: Execution jumps to the statement after the one with the label marked on it.
Because blocks are considered single statements in Java, execution jumps to right brace after the the point after // Centralised handling of ErrMsg