0

This is my code. I try to return object with including different parameters.

public class A{

 ResponseObj responseObj = null;
 public ResponseObj test(){
    if(something){
       responseObj = new ResponseObj("k","l");
    }
    else{
       responseObj = new ResponseObj("x","y","z");
   }
 }

 return responseObj;
}

Created ResponseObj class with two constructors.

public class ResponseObj{

   String a;
   String b;
   String c;
   String d;

   public ResponseObj(String a, String b){
     this.a = a;
     this.b = b;
   }
   public ResponseObj(String a, String b,String c){
     this.a = a;
     this.b = b;
     this.c = c;
   }

}

By if condition pass,

a:"k",
b:"l",
c:null,
d:null

By else condition pass,

a:"x",
b:"y",
c:"z",
d:null

But I need to remove null values from the output

Outputs

Call if condition,

a:"k",
b:"l",

Call else condition,

a:"x",
b:"y",
c:"z"

If this is not correct way please inform me. Thank you

Priyantha
  • 4,839
  • 6
  • 26
  • 46
  • 2
    How do you generate the output? Please edit your question to include the code which generates the output. – Progman Jun 18 '18 at 19:53
  • Also, the code you've given for `class A` is invalid – lucasvw Jun 18 '18 at 19:54
  • what do you mean by "*But I need to remov these null values from output.*"? Do you mean from the `toString()`-representation or from the object? – Turing85 Jun 18 '18 at 19:55
  • "How do I not print null values" <--- is this the question? If so, check the state before printing, or use `Optional`s. You either enforce null safety upfront, or handle appropriately when you don't or can't enforce it. – Mark Jun 18 '18 at 19:56
  • @Turing85 thanks your comment. I return ResponseObject type object. I need to return this object without null values. – Priyantha Jun 18 '18 at 19:58
  • Alternately, if printing is the problem, then most of Java's output classes will check for null and print "null" if you send it a null parameter. – markspace Jun 18 '18 at 19:58
  • If you simply want the values to not be null, you can always set them to "" in the constructor. For example, `this.d = "";`. – FlexEast Jun 18 '18 at 20:01
  • 1
    @FlexEast - look at the required output, null values allowed, but not output. – Mark Jun 18 '18 at 20:04
  • @ FlexEast thanks our comment. Actually I don't need to pass d to output when d is null. Please check whick output I need.Thank yo – Priyantha Jun 18 '18 at 20:04
  • @MarkKeen Thanks, I misunderstood. Dev4World, You'll either need to keep your values in an array or some collection, or edit the code where the values are printed out. – FlexEast Jun 18 '18 at 20:08

4 Answers4

3

It is not the role of the constructors to remove the displayed values performed by another method.
The object has a state and null fields make part of this state.
What you are looking for is implementing a method that outputs only the not null fields.

Try something like :

public class ResponseObj {
   ...
    public void displayNotNullValues(){
       StringBuilder finalMsg = new StringBuilder();
       appendIfNotNull(finalMsg, "a", a);
       appendIfNotNull(finalMsg, "b", b);
       appendIfNotNull(finalMsg, "c", c);
       appendIfNotNull(finalMsg, "d", d);
       System.out.println(finalMsg.toString());
    }

    private void appendIfNotNull(StringBuilder finalMsg, String name, String value){
       if (value != null){
          if (finalMsg.length()>0){
            finalMsg.append(",");
            finalMsg.append("\n");
          }
         finalMsg.append(name + " : ");
         finalMsg.append("\"");
         finalMsg.append(value);
         finalMsg.append("\"");
       } 
    }
}

Example of use :

new ResponseObj("k","l").displayNotNullValues();
System.out.println("----");
new ResponseObj("x","y","z").displayNotNullValues();

Output :

a : "k",

b : "l"


a : "x",

b : "y",

c : "z"

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • thanks your reply. new ResponseObj("k","l").displayNotNullValues(); is ok. But ResponseObj obj = new ResponseObj("k","l").displayNotNullValues(); is not correct. I return ResponseObj type object. How to solve this. Thank you. – Priyantha Jun 18 '18 at 20:58
  • @Dev4World, in your second case you should do `obj.displayNotNullValues();` – Joakim Danielson Jun 19 '18 at 16:38
1

You can return an array containing your response rather than using a response object in this case.

public class Mystery {
    public boolean something = true;

    public String[] getState() {
        String[] s = null;
        if (something) {
            s = new String[2];
            s[0] = "k";
            s[1] = "l";
        } else {
            s = new String[3];
            s[0] = "x";
            s[1] = "y";
            s[2] = "z"; 
        }
        return s;
    }
}

public static void main(String[] args) {
    Mystery m = new Mystery();
    String[] response1 = m.getState();
    System.out.println(Arrays.toString(response1)); // out: [l, k]
    m.something = false;
    String[] response2 = m.getState();
    System.out.println(Arrays.toString(response2)); // out: [x, y, z]
}
Tiago Redaelli
  • 560
  • 5
  • 17
0

In your ResponseObj class you override toString() to get the output you need

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    if (a != null) {
        builder.append(String.format("a:%s\n", this.a));
    }
    if (b != null) {
        builder.append(String.format("b:%s\n", this.b));
    }
    if (c != null) {
        builder.append(String.format("c:%s\n", this.c));
    }
    if (d != null) {
        builder.append(String.format("d:%s\n", this.d));
    }
    return builder.toString();
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

I would use Java Optional - something like this :

public class ResponseObj {

    private String a;
    private String b;
    private String c;
    private String d;

    public ResponseObj(String a, String b) {
        this.a = a;
        this.b = b;
    }

    public ResponseObj(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public Optional<String> getA() {
        return Optional.ofNullable(a);
    }

    public Optional<String> getB() {
        return Optional.ofNullable(b);
    }

    public Optional<String> getC() {
        return Optional.ofNullable(c);
    }

    public Optional<String> getD() {
        return Optional.ofNullable(d);
    }

    public static void main(String[] args) {

        ResponseObj responseObj = new ResponseObj("k", "l");

        responseObj.getA().ifPresent(s -> System.out.println("a:" + s));
        responseObj.getB().ifPresent(s -> System.out.println("b:" + s));
        responseObj.getC().ifPresent(s -> System.out.println("c:" + s));
        responseObj.getD().ifPresent(s -> System.out.println("d:" + s));


        ResponseObj responseObjb = new ResponseObj("x", "y", "z");

        responseObjb.getA().ifPresent(s -> System.out.println("a:" + s));
        responseObjb.getB().ifPresent(s -> System.out.println("b:" + s));
        responseObjb.getC().ifPresent(s -> System.out.println("c:" + s));
        responseObjb.getD().ifPresent(s -> System.out.println("d:" + s));

    }
}

This requires no utility methods, and as a user implementing this class you know that these values could be null.

Mark
  • 9,604
  • 5
  • 36
  • 64
  • 1
    [Citing Brian Goetz](https://stackoverflow.com/a/26328555/4216641): "*You should almost never use it [`Optional`] as a field of something or a method parameter.*" - And I have a feeling that this is not one of the rare cases you should. – Turing85 Jun 18 '18 at 20:55