I want to write add(), subtract(), and equals() methods for my simple objects, allowing for nulls in fields. I end up using python to generate boilerplate code, and this tells me I am doing something wrong. What is the DRYer way to write a class like this?
package com.blicket.parser;
/**
* Created by steve on 8/22/16.
*/
public class Foo {
public Integer bar;
public Integer baz;
public Integer qux;
public boolean equals(Foo b){
if(
(this.bar == b.bar || this.bar.equals(b.bar) &&
(this.baz == b.baz || this.baz.equals(b.baz) &&
(this.qux == b.qux || this.qux.equals(b.qux) &&
){
return true;
} else {
return false;
}
}
public Foo add(Foo a, Foo b){
Foo c = new Foo();
c.bar = a.bar + b.bar;
c.baz = a.baz + b.baz;
c.qux = a.qux + b.qux;
return c;
}
}
EDIT: I was using == for null checks, but it is redundant. Don't do that, reader. I am leaving the bad code sample to ensure the comments make sense.
EDIT 2: Trying to strip out the == checks, if bar
, baz
, or qux
is null, doesn't
public boolean equals(Foo b){
if(
this.bar.equals(b.bar) &&
this.baz.equals(b.baz) &&
this.qux.equals(b.wux)
){
return true;
} else {
return false;
}
}
throw NullPointerException
?
EDIT 3 Electric Jubilee: Looks like the right answer is
public boolean equals(Foo b){
return Objects.equals(this.bar, b.bar) &&
Objects.equals(this.baz, b.baz) &&
Objects.equals(this.qux, b.qux);
}