user image

Rahul Pandit.
Published in : 2022-03-05

Method refactoring to avoid to many npe checks

Javascript

I have created the following method which returns a Triple of strings. However, I don't like the way I've written it because I think I've put in too many Npe checks making it unreadable.

private Triplet<String, String, String> getInfoFromTable(Person person) {
    StringBuilder idWithText = new StringBuilder();
    String idText;
    Date time = null;
    Level level;

    Exercise exerciseRecord = getExercise(person);
    if (exerciseRecord != null && exerciseRecord.getId() != null) {

        if(exerciseRecord.getLevel1() != null &&  exerciseRecord.getLevel2() != null){
            level = new Level(exerciseRecord.getLevel1(), exerciseRecord.getLevel2());
        } else {
            level = new Level("1", "1");
        }
        idText = getIdText(level, exerciseRecord.getId());

        if(!Strings.isNullOrEmpty(idText)) {
            idWithText = idWithText.append(exerciseRecord.getId()).append(" " + idText);
        }

        if (exerciseRecord.getTime() != null) {
            time = exerciseRecord.getTime().toDate();
        }

        return new Triplet<>(idWithText.toString(), "1", formatTime(time));
    }


    return new Triplet<>("", "", "");
}

Ηow can I make the above code look simpler? I've seen a little use of Optional but I don't know if it's good to use them in my case. Could someone help with the method refactor?

Comments

There is no comments yet

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

How to move a div with its content to TinyMEC editor?
Publish date: 2022-02-11 | Comments: 0

Tag: Javascript

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript

Javascript: Filtering arrays by it properties?
Publish date: 2022-03-05 | Comments: 1

Tag: Javascript

JavaScript variable for Changing CSS Height
Publish date: 2022-02-12 | Comments: 1

Tag: Javascript

Adding an id number at the first index to an array of objects
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

jquery undefined function
Publish date: 2022-02-28 | Comments: 1

Tag: Javascript

Javascript Add (+) issue
Publish date: 2022-02-26 | Comments: 1

Tag: Javascript