简体   繁体   中英

Common method for null check

I want to create a common method which will check for null on primary keys of database tables.

I have two type of datatype

  1. String

  2. Date

Want to create a common function which will take parameters on the run time and check for null. Table 1:

private boolean checkForNullEntries(Table1 table1) {
    if (StringUtil.isNullOrEmpty(table1.getName())) {
        return true;
    } else if (table1.getLastUpdateTime() == null) {
        return true;
    }
    return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
    boolean nullValueFound = checkForNullEntries(table1);
    if (nullValueFound) {
        //skip db operation
    } else { 
        // save to DB
    }
}

Table 2:

private boolean checkForNullEntries(Table2 table2) {
    if (table2.getTimeSlot == null) {
        return true;
    } else if (table2.getDate() == null) {
        return true;
    }
    return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
    boolean nullValueFound = checkForNullEntries(table2);
    if (nullValueFound){
       //skip db operation
    } else {
        // save to DB
    }
}

I want to create a common method for both the tables. Any suggestion experts

Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:

private static boolean checkForNullEntries(Map<String, Table> map) {
    if(map.get("String") != null) {
        if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
            return true;
        } else if (map.get("String").getLastUpdateTime() == null) {
            return true;
        }
        return false;
    }
    if(map.get("Date") != null) {
        if (map.get("Date").getTimeSlot == null) {
            return true;
        } else if (map.get("Date").getDate() == null) {
             return true;
        }
        return false;
    }
    return false;
}

Then you can call the function like this:

    Map<String, Table> map = new HashMap<>();
    map.put("Date", table2);
    boolean result = checkForNullEntries(map);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM