How to implement "beans" and "bean mapping"?

We have "beans" that need to be serialized to JSON in order to be returned to our (UUE level) at the UUE level. 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 created in some way:

public ExampleBean map(SomeInternalThing foo)  {
   int id = getIdFromFoo(foo);
   String name = doSomethingElse(foo.itsBar());
   return new ExampleBean(id, name);
}

      

Then I have some unit tests (for the display device):

@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 the beans are immutable (and the compiler tells me when I forgot to initialize the field).

But: the number of fields for this bean keeps increasing. This context SomeInternalThing

can contain 30 to 50 "properties", and the number of fields required in the bean ... is now 3 to 5 to 8.

What really kills me is that the display code does different things for each required field. Which requires me to have more and more "general" layout specifications for a solution.

I am currently wondering if there are better options for implementing such "data-only objects".

+3


source to share


1 answer


I personally prefer lombok ( https://projectlombok.org/ ) when creating data objects. It gets rid of the template code. You should look into the @Builder and @Data annotation.

Since using lombok is always a group decision, you can start by implementing the builder pattern yourself (for such data objects).



This allows you to set each property separately and check each property individually.

This means that 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 must have a public default constructor

+1


source







All Articles