break
is only valid to make the execution flow exit a loop ( for
, while
or do
- while
) or a switch
- case
. >
In functions you can use return
:
if (!price()) {
QMessageBox( ... );
return;
}
if (!date()) {
QMessageBox( ... );
return;
}
//Algoritmo principal
...
This is a widely used pattern. Checking for special conditions and eliminating them as early as possible leaves the code more readable as it eliminates these cases from the main algorithm.
Another alternative is to throw an exception. This alternative is particularly interesting if the code in question is in the constructor of an object. This way the object is never created in an invalid state;
//Construtor
Object(Arg1 a1, Arg2 a2) attrib1(a1), attrib2(a2) {
if (!price()) {
throw InvalidPrice();
}
if (!date()) {
throw InvalidDate();
}
//Se chegou até aqui o objeto é válido, continua a inicialização dele
...
}
Using the object:
try {
Object obj(arg1, arg2);
//Se passou do construtor, o objeto é 100% válido
obj.use();
}
catch (InvalidPrice const &) {
QMessageBox( ... ); //Avisa sobre preço inválido
}
catch (InvalidDate const &) {
QMessageBox( ... ); //Avisa sobre data inválida
}