2

I have the method which returns java.util.Date inside the hibernate-entity class:

package ua.com.winforce.loto_partner.commons.db.entity;

@Entity
@Table(schema = "pr", name = "publice")
public class Pr {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "reg_date")  
    private Date regDate;

    //GET, SET
}

And in a method I need to create the local variable which will be hold getRegDate(); value, or to invoke that method twice. What would be more appropriate in that case? I mean, in the first case we're potentially closing the moment when GC will be triggered, but in the first we waste our time to the second method invocation.

1 Answers1

5

There are three reasons* to cache a function return in a variable:

  • You know or suspect that the function has side effects.
  • The function can return different values on every call, and you need a consistent result. Normally this is due to the function having side-effects, but it can also be due to reading volatile data.
  • The repeated function call would make the code less clear. This is the "extract explanatory variable" refactoring.

Your example doesn't appear to fit any of these cases.

* there is a fourth, but it's reserved for Doug Lea and Martin Thompson, and is arguably a combination of #1 and #2.

kdgregory
  • 5,270