David Edgar
David Edgar

Reputation: 505

Transform these verbal rules into conditions

I am applying certain conditions on data from 4 html fields, these fields are divided into two categories: category A (fields A1 and A2) and category B (fields B1 and B2)

N.B: I'm confused on how to achieve this with an elegant way

Rules:

1) When the 4 fields are empty, I return a message that the fields are empty.

2) When fields A1, A2 are valid and B1, B2 are empty I apply an action according to category A

3) rule exeption (2): When field A1 is valid and field A2 is empty, A2 assigns a value to A2 (e.g A2 = A1 ++)

4) When fields B1, B2 are valid and A1, A2 are empty I apply an action according to category B

5) exeption of rule (4): When field B1 is valid and field B2 is empty, B2 I assign a value to B2 (e.g B2 = B1 ++)    6) If all the fields are valid, I apply an action according to all the fields

if ( A1 == '' && A2 == '' && B1 == '' && B2 == '' ) {
    System.out.println("empty fields");    
}else if () {

} else {

} 

Upvotes: 1

Views: 30

Answers (2)

JoeG
JoeG

Reputation: 7652

You could leverage the powers of two to generate a unique combination for any field input set. You could (should) even hide the values in an enum. This will easily allow you to deal with ANY possible set of inputs.

However, just to illustrate, it would look something like:

// assign values to rules to each and accumulate:
static final int ALL_EMPTY = 0;
static final int RULE_3 = 1;
// ....rest of the rules
static final int RULE_4 = 12;    // this is 0 + 0 + 4 + 8
int settings = 0;
if (A1.isValid()) {
    settings += 1;
}
if (A2.isValid()) {
    settings += 2;
}
if (B1.isValid()) {
    settings += 4;
}
if (B2.isValid()) {
    settings += 8;
}
switch (settings) {
case ALL_EMPTY:
    // output message
    break;
case RULE_3:
    // do rule 3
    break;
// etc, etc (for each rule you need)
}

Upvotes: 1

Adam
Adam

Reputation: 2440

Something similar to this?

if( A1 == "" && A2 == "" && A3 == "" && A4 == "")
    System.out.println("empty fields")
else if(A1.IsValid() && A2.IsValid() && B1.IsValid() && B2.IsValid()
    DoSomethingElseAB();
else if( A1.IsValid() )
{
    if(A2 == "")
        A2 = A1++;
    else if ( B1 == "" & B2 == "")
        DoSomethingElseA();

    if( A2.IsValid() && B2 == "" )
        B2 = B1++;
    else if ( B1.IsValid() && B2.IsValid() && A1 == "" && A2 == "")
        DoSomethingElseB()
}

Upvotes: 1

Related Questions