We have "beans" that are meant to be serialized to JSON, to be then returned to our (vue.js based) UI layer. So far, my beans look like this:
public class ExampleBean {
private final int id;
private final String name;
public ExampleBean(int id, String name) {
this.id = id; ...
}
// getter for all fields
}
They are instantiated by some mapper:
public ExampleBean map(SomeInternalThing foo) {
int id = getIdFromFoo(foo);
String name = doSomethingElse(foo.itsBar());
return new ExampleBean(id, name);
}
I then have some unit tests (for the mapper):
@Test
public void testGetId() {
... do some mocking setup so that the mapper can do its job
assertThat(mapperUnderTest.map(someFoo).getId(), is(5));
}
The main advantage of this approach is that bean objects are immutable (and the compiler tells me when I forgot to initialize a field).
But: the number of fields for that bean keeps increasing. That SomeInternalThing context has maybe 30 to 50 "properties", and the number of fields required in the bean ... went from 3 to 5 to 8 by now.
What is really "killing" me is the fact that the mapping code is doing different things for each required field. Which requires me to have more and more "common" mock specifications to deal with.
By now I am wondering if there are better choices to implement such "data only objects".
Personally I prefer lombok ( https://projectlombok.org/ ), when creating data objects. It gets rid of the boilerplate code. You should take a look into the "@Builder" and "@Data" annotation.
Since using lombok is always a team decision, you could start by implementing the builder-pattern by yourself (for such data-objects).
This enables you to set every property seperately, and test every property individually.
That beeing said you probably shouldn't use a constructor with every field. (see @AllArgsConstructor in lombok) As you can see here (https://en.wikipedia.org/wiki/JavaBeans) beans should have a public default constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With