stackoverflow490
stackoverflow490

Reputation: 31

Java code design for nested if conditions

I have a requirement to implement following logic with multiple/nested if-else. Basically i have three tables and i need to insert record in one and delete from others based on different conditions (explained in code snippet below).

I have implemented it as below, just wondering is there a better/maintainable way to do it using OOPS and some design pattern in java

if (conditionA || conditionB || conditionC) {
    deleteRecordFromTableA();

    if (conditionB) {
        insertRecordInTableB();
    }

    if (conditionC) {
        insertRecordInTableB();
    }
} else {
    deleteRecordFromTableB();
    deleteRecordFromTableC();

    if (conditionD) {
        validateRecordInUpdateMode();
        updateRecordInTableA();
    } else {
        validateRecordInInsertMode();
        insertRecordInTableA();
    }
}    

Upvotes: 3

Views: 143

Answers (1)

user5342366
user5342366

Reputation:

Based on your code :-

if (conditionA || conditionB || conditionC) 
{
  deleteRecordFromTableA();

  if (conditionB || condition C)  // can be done together as they both do the same thing
  {
      insertRecordInTableB();
  }
}
else 
{
  deleteRecordFromTableB();
  deleteRecordFromTableC();

  if (conditionD)
  {
    validateRecordInUpdateMode();
    updateRecordInTableA();
  }
  else 
  {
    validateRecordInInsertMode();
    insertRecordInTableA();
  }
}  

An other way (Probably easier to understand) is :-

if(conditionA)
{
  deleteRecordFromTableA();
}
else if (conditionB || condition C)
{
  deleteRecordFromTableA();
  insertRecordInTableB();
}
else if(conditionD)
{
    deleteRecordFromTableB();
    deleteRecordFromTableC();
    validateRecordInUpdateMode();
    updateRecordInTableA();
}
else
{
    deleteRecordFromTableB();
    deleteRecordFromTableC();
    validateRecordInInsertMode();
    insertRecordInTableA();
}

Upvotes: 2

Related Questions