Reduce cognitive Complexity of a method from 26 to 15

139 views Asked by At

I have the following code:

private void generateKeyList(String pdm, List<Key> uKs,
                                 List<PhysicalKey> pKs) {
        if (pKs == null && uKs == null)
            return;
        JsonObject concepts = getConcepts(pdm);
        String indexTypeRequired = uKs == null ? "PRIMARY-KEY" : "UNIQUE";
        for (String concept : concepts.keySet()) {
            var indexes = concepts.getAsJsonObject(concept).getAsJsonArray("indexes");
            if (indexes == null)
                continue;
            for (JsonElement index : indexes) {
                JsonObject indexO = (JsonObject) index;
                var indexType = indexO.getAsJsonPrimitive("indexType").getAsString();
                var name = indexO.getAsJsonPrimitive("name").getAsString();
                var keys = indexO.getAsJsonArray("key").getAsJsonArray();
                if (indexType.equals(indexTypeRequired)) {
                    for (JsonElement indexKey : keys) {
                        var keyString = indexKey.getAsString();
                        var key = pKs == null ? new Key() : new PhysicalKey();
                        key.setName(name).setType(indexType).setTable(concept).setColumn(keyString);
                        if (uKs == null)
                            pKs.add((PhysicalKey) key);
                        else
                            uKs.add(key);
                    }
                }
            }
        }
    }

I am getting an issue from sonarLint that the Cognitive Complexity of this code is 26 and it should be <=15
Not sure how to reduce the complexity here.
Any ideas of hints?

1

There are 1 answers

0
WLefever On

Below I listed a couple of hints based on your code. Of course, there are many many more. You might find Clean Code by Robert Martin an interesting read.

  1. Extract code that is in for loops to a separate method (in your case you can do this twice)
  2. Extract code that is in if or else conditions to separate methods
if (condition){
   doSomething();
} else{
   doSomethingElse();
}
  1. Avoid continue

Better to change

if (indexes == null)
                continue;

to

if (indexes != null){
    for (JsonElement index : indexes) {...}
}