1

Traditionally I have always made by Hibernate entities as follows:

@Entity
@Table(name = "my_table")
@SuppressWarnings("serial")
public class MyEntity extends Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;

@Column(name = "name")
private String someName;

@Column(name = "description")
private String description;

and getters and setters have looked like:

public String getSomeName()
{
    return someName;
}

public void setSomeName(String someName)
{
    this.someName = someName;
}

public String getDescription()
{
    return description;
}

public void setDescription(String description)
{
    this.description = description;
}

followed by Eclipse generated hashcode, equals, and toString methods.

Now I am being asked to change my setters to be as follows:

 public MyEntity setSomeName(String someName)
 {
     this.someName = someName;
     return this;
 }

public MyEntity setDescription(String description)
{
    this.description = description;
    return this;
}

This is so we can do chaining:

MyEntity entity = new MyEntity().setSomeName("x").setDescription("y");

This doesn't break my unit tests for CRUD, the DAO still seems to work fine.

What is annoying that with Eclipse, I can whip out getters/setters very quickly, but now I need to adjust all my setters with "return this;"

First ... I am not sure, but is this the new normal for java 8? Will this have any adverse affects in the long wrong, is this going to take up more memory, or is this going to be highly efficient and I should do this?

I've been doing Java since JDK 1.3 and the past 15 years, and I know each new technology advance has it's quirks. I was just wondering if there were any here?

Thanks!

tjholmes66
  • 1,850
  • 4
  • 37
  • 73
  • 1
    Chaining like this shouldn't have any negative effects and isn't a Java 8 feature either. I'd say `MyEntity entity = new MyEntity().setSomeName("x").setDescription("y");` is not much different from the compiler's point of view that calling each method in a separate statement (as long as the entities look like above, using things like generics might make that more complicated). – Thomas Dec 08 '15 at 15:47
  • Yes ... thanks ... I'll have to edit that. – tjholmes66 Dec 08 '15 at 15:56
  • 4
    I think it will break the beans convention for setter. You can do this, but it is not as the conventions said `public void setX(C x)`. As setters are around since long time, I prefer the `public C withX(K x)` convention. Right now, you have to type it anyway. – PeterMmm Dec 08 '15 at 16:02
  • 1
    BTW, I think Eclipse allows to edit the code generation templates (http://stackoverflow.com/questions/12294627/generate-setters-that-return-self-in-eclipse). – PeterMmm Dec 08 '15 at 16:04
  • 1
    This isn't "java 8"; it's the [Fluent Interface pattern](https://en.wikipedia.org/wiki/Fluent_interface) – Bohemian Dec 08 '15 at 18:23

0 Answers0