3
\$\begingroup\$

The user enters coefficients into input boxes on a form, called GetFunction. Upon clicking an OK button on said form, the input is validated using TryStrToFloat. If all the input boxes are valid,CreateGraphis called. As soon as an invalid input box is found,CreateGraph` should not be called and the user should be able to fix their error.

procedure TfrmGetFunction.btnAddFunctionClick(Sender: TObject);
  var
    i : integer; // Loop counter.
  begin
    for i := 1 to 7 do
      begin
        CoefficientEdit[i].CoValid := CheckCoefficientBoxesValidInput(CoefficientEdit[i].CoEditBox);
        if not CoefficientEdit[i].CoValid then // If any input box is invalid.
          Exit;
      end;
    frmGraphingMode.CreateGraph; // Finally if all input boxes valid.
    frmGetFunction.Visible := false;
    frmGraphingMode.Visible := true;
  end;

Any improvements that I could make? Perhaps removing the Exit may not be a bad idea?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Besides deciding if a coefficient is valid or not the function CheckCoefficientBoxesValidInput can also say what is wrong and suggest how the user can fix it.

In order to communicate such information up to the caller and up to the user interface you can use throwing an exception.

Main success scenario would mean no ifs, just sequence of statements.

Exceptional flow would be encoded in try/except blocks, either in this function or somewhere upwards or in the final Application.OnException handler.

Whether the code would be easier to maintain or not is only opinion-based matter of taste and your established coding conventions.

The main improvement would be that the end-user would know what happened and what to do next.

See also:

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.