jeudi 1 novembre 2018

What is the best way to handle sequential if statements before proceeding with further action?

I have a list of IF statements that are validating user input before proceeding onto a dialog box, which then leads to using the inputs to add to a database.

What I want is for the IF statements to halt progressing if a criteria isn't met, the best way i've found to do this (without a huge IF statement containing multiple ands/ors) is to run it in a while loop as follows:

private void btnSave_Click(object sender, EventArgs e)
{
    while (true)
    {
        if (txtScriptName.Text == "" || txtScriptName.Text == null)
        {
            MessageBox.Show("You must enter a script name before saving." +
                            "\nScript name should start with 'OH' or 'RE' and be separated with underscores (_)");
            break;
        }

        if (!txtScriptName.Text.StartsWith("OH") && !txtScriptName.Text.StartsWith("RE"))
        {
            MessageBox.Show("The script name must start with 'OH' or 'RE'");
            break;
        }

        if (txtScriptName.Text.Contains(" "))
        {
            MessageBox.Show("The script name must not contain spaces, use underscores instead.");
            break;
        }

        if (cmbLine.Text == "" || cmbLine.Text == null)
        {
            MessageBox.Show("You must select a line of agents for this to effect.");
            break;
        }

        if (cmbDesk.Text == "" || cmbDesk.Text == null)
        {
            MessageBox.Show("You must select a desk for this to effect.");
            break;
        }

        DialogResult DR = MessageBox.Show("Are you sure you wish to save these details to the database for use?",
                                            "Final check",
                                            MessageBoxButtons.OKCancel,
                                            MessageBoxIcon.Question);

        if (DR == DialogResult.OK)
        {
            // Take inputs and add them to the database
            break;
        }

        break;
    }
}

This allows me to break out of the loop, stopping any progress before it reaches the final SQL statements which I've excluded, with a final break at the bottom of the loop in case it ever reaches that stage as a redundancy to prevent any infinite looping.

Is this an efficient way of doing it or am I using a hack method?

Aucun commentaire:

Enregistrer un commentaire