HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Using if else statements correctly

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
statementscorrectlyusingelse

Problem

I have the following code, but I'm looking for a way to make the code read easier.

public void synchronizePageAndExcecuteVerifyNode() throws Exception {
    String nameTestcase = this.getClass().getSimpleName();
    WriteTo.testgoal(nameTestcase, TestgoalState.nvt, "");

    Boolean testDataGenerated = eventTestData.eventDetailMultipleDays;
    Boolean currentPage = driver.getTitle().contains(Value.TITLE_EVENT_MULTIPLE_DAYS);

    if (testDataGenerated == true) {
        if(currentPage == true){
            this.verifyEventDetailFull();
        }else{
            WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                    "Page synchronize failed");
            throw new Exception("PAGE SYNCHRONIZE FAILED");
        }
    } else {
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "testdata is not generated");
        throw new Exception("NO TESTDATA GENERATED");
    }
}

Solution

if (condition == true)

Instead of

if (testDataGenerated == true) {


just write

if (testDataGenerated) {


Rewriting ifs

You can move your checks to the top of the method like this to avoid nested ifs:

if (!testDataGenerated) {
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "testdata is not generated");
        throw new Exception("NO TESTDATA GENERATED");
    }
    if(!currentPage){
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "Page synchronize failed");
        throw new Exception("PAGE SYNCHRONIZE FAILED");
    }
    this.verifyEventDetailFull();

Code Snippets

if (testDataGenerated == true) {
if (testDataGenerated) {
if (!testDataGenerated) {
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "testdata is not generated");
        throw new Exception("NO TESTDATA GENERATED");
    }
    if(!currentPage){
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "Page synchronize failed");
        throw new Exception("PAGE SYNCHRONIZE FAILED");
    }
    this.verifyEventDetailFull();

Context

StackExchange Code Review Q#61324, answer score: 18

Revisions (0)

No revisions yet.