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

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

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

Tag: Javascript

Check if div have touch another div
Publish date: 2022-03-02 | 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

Required to convert Obj {} to Arr [] from key-value pairs using javascript
Publish date: 2022-03-06 | Comments: 2

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript