2

I have an object which has 5 getters, but only one getter returns not null value. How can I pass this value to other function in concise way?

fun(
  object.getA() != null ? object.getA() :
  object.getB() != null ? object.getB() :
  object.getC() != null ? object.getC() :
  object.getD() != null ? object.getD() :
  object.getE() != null ? object.getE() : "error"
)

Is it a good way to do it or maybe it can be improved?

ctomek
  • 1,696
  • 16
  • 35
  • You could write a function which does all that work for you, so you don't need to rewrite it every time. – resueman Nov 16 '15 at 15:04
  • @resueman Yeah, I know, my question is about whether piece of code which chooses not nut value is ok or it could be improved – ctomek Nov 16 '15 at 15:06
  • better to post on http://codereview.stackexchange.com/ – RockAndRoll Nov 16 '15 at 15:14
  • Do all getters return value of same type? – Pshemo Nov 16 '15 at 15:21
  • @Pshemo Yes, they are Strings. – ctomek Nov 16 '15 at 15:39
  • What kind of answer do you expect exactly? Do you want to ask [How to get the first non-null value in Java?](http://stackoverflow.com/questions/2768054/how-to-get-the-first-non-null-value-in-java) – Pshemo Nov 16 '15 at 15:43
  • @Pshemo Yes, something like that. – ctomek Nov 16 '15 at 15:48
  • Then do you think I can close your question as duplicate of that one or are there things which you didn't mention yet which make this question different than that one? For now based on that duplicate I imagine answer which you may be looking for as something like `fun(MoreObjects.firstNonNull(object.getA(), object.getB, ...))`. – Pshemo Nov 16 '15 at 15:57
  • @Pshemo I think you can close it, thanks. – ctomek Nov 16 '15 at 16:00

1 Answers1

0

Since one method will return non null, you can omit the last condition check.

fun(
  object.getA() != null ? object.getA() :
  object.getB() != null ? object.getB() :
  object.getC() != null ? object.getC() :
  object.getD() != null ? object.getD() :
  object.getE()
)
HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33