2

I have some constructors like these where I must handle with parameters being null.

    public Element(int value1, String value2, String value3, String value4) {
        this.value1 = value1;
        this.value2 = value2 != null ? value2 : "";
        this.value3 = value3 != null ? value3 : "";
        this.value4 = value4 != null ? value4 : "";
    }

Yes I know, I could write a utility-method or my own annotation to reduce the boiler plate code for params 2,3,4

But is there any existing solution? Something like @DefaultOnNull("") on the parameter or even the class?

Datz
  • 3,156
  • 3
  • 22
  • 50
  • Related, but not a satisfactory solution: [Default value in lombok. How to init default with both constructor and builder](https://stackoverflow.com/questions/47883931/default-value-in-lombok-how-to-init-default-with-both-constructor-and-builder) – Lino Jun 08 '21 at 09:54
  • 2
    A potential helper method which exists in the jdk would be `java.util.Objects.requireNonNullElse(value2, "")` – Lino Jun 08 '21 at 09:55
  • 1
    If you wish to do the null check and setting `""` after the usual `this.x=x` initialization steps, then this is a kind of workaround for a similar problem - https://stackoverflow.com/a/67815143/7804477 – Gautham M Jun 08 '21 at 13:23

2 Answers2

0

Thanks for all comments. I solved it this way to reduce the boiler plate code at least a little bit:

    public Element(int value1, String value2, String value3, String value4) {
        this.value1 = value1;
        this.value2 = Objects.requireNonNullElse(value2, "");
        this.value3 = Objects.requireNonNullElse(value3, "");
        this.value4 = Objects.requireNonNullElse(value4, "");
    }
Datz
  • 3,156
  • 3
  • 22
  • 50
  • How does this "reduce" boilerplate code? :-) This is same as the code in your question but done in a different way. – Gautham M Jun 09 '21 at 06:24
  • That's why I said "a little bit". I only have to write value2, value3, ... once and therefore this reduces the risk of copy & paste errors. – Datz Jun 09 '21 at 06:29
  • Yes. Maybe a method `getDefault(value){ return Objects.requireNonNullElse(value, ""); }` so that it may look a bit compact and also you need not pass `""` as well (if you want `""` as default in all cases) – Gautham M Jun 09 '21 at 07:37
-1

You can use below code

this.value2 = StringUtils.defaultString(value2);

StringUtils is an Apache commons library and is widely used and standard library for String related operations. Maven - https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.10

PumpkinX
  • 67
  • 1
  • Thanks, but this a) requires an additional library and b) works only for `""` as default string. – Datz Jun 09 '21 at 05:00