Ask Your Question
2

How to avoid returning null when using if-else-if statements within a sub-function?

asked 2021-10-17 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-03-16 16:00:00 +0000

nofretete gravatar image
  1. Use a default return value: Before the if-else-if block, assign a default return value to a variable. Then, within each if-else-if statement, assign the final return value to that variable. If none of the if-else-if statements are true, the default return value will be returned.

  2. Throw an exception: Instead of returning null, you could throw an exception when none of the if-else-if statements are true. This will alert the caller that something unexpected occurred.

  3. Return an empty object or collection: Depending on your use case, returning an empty object or collection may be appropriate. This can be useful, for example, when you are expecting an array but none of the if-else-if statements are true. By returning an empty array, you avoid a null reference error.

  4. Simplify the logic: If possible, try to simplify the logic of your sub-function. Having too many if-else-if statements can make the code difficult to read and maintain. Consider rearranging the order of the statements or using loops or switch statements instead.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-17 11:00:00 +0000

Seen: 10 times

Last updated: Mar 16 '22