jeudi 3 juin 2021

Is there a better way to handle nested if?

Currently I am having a hard time trying to figure out if there is a better way to refactor the following code.

Given the following:

String detail = "POTATORANDOMFOOD";

Lets say I want to assign variables with different parts of detail, the end result would look something like this.

String title = detail.substring(0, 6); // POTATO
String label = detail.substring(6, 12); // RANDOM
String tag = detail.substring(12, 16); // FOOD

Now lets say the string detail length constantly changes, sometimes it only contains "POTATORANDOM" and no "FOOD", sometimes it contains even more characters "POTATORANDOMFOODTODAY", so another variable would be used.

String title = detail.substring(0, 6); // POTATO
String label = detail.substring(6, 12); // RANDOM
String tag = detail.substring(12, 16); // FOOD
...
String etc = detail.substring(30, 40); // etc value from detail string

The issue with this, is that since the string sometimes is shorter or longer, we would run into the StringIndexOutOfBoundsException which is not good.

So currently I have a naive way to handle this:

if (detail != null || !detail.isEmpty()) {
    if (detail.length() >= 7) {
        title = detail.substring(0, 6);

        if (detail.length() >= 13) {
            label = detail.substring(6, 12);

            if (detail.length() >= 16) {
                tag = detail.substring(12, 16);
                .
                .
                .
            }
        }
    }
}

This can get really messy, especially if lets say the string were to grow even more.

So my question is, what would be a good design pattern that would fit for this type of problem? I have tried the chain of responsibility design pattern but, the issue with this one is that it only returns a single value, while I am trying to return multiple ones if possible. This way I can assign multiple variables depending on the length of the string.

Any help/hints is greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire