break
is only valid to make the execution flow out of a loop (for
, while
or do
-while
) or a switch
-case
.
In functions you can use a 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 soon as possible makes the code more readable as it eliminates these cases from the main algorithm.
Another alternative is to make 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
}
Would not be
return
where isbreak
? You could complete the code you posted.– Lucas Lima
@Lucas Nunes: No. because if is in the builder.
– Hy-brazil
You can give
return
in a manufacturer (in functionvoid
), no problem. Just writereturn;
.– C. E. Gesser
Blz. Thank you :)
– Hy-brazil