Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
Calculate members during construction in records

I've created a Java record, and would like to have a constructor that takes in a reduced number of arguments compared to the default constructor, and calculate and initialise all members based on the given arguments.

However, I've found this difficult to achieve given the first line of the custom constructor must call the default constructor. My current approach is to call my calculation functions as needed, but this results in unnecessary processing.

Surely there must be a better way to achieve this?

public record MyRecord(double a, double b, double c) {
     public MyRecord(double a) {
          this(a, calculateB(a), calculateC(a, calculateB(a)));
     }

     private static double calculateB(double a) {
          // Some calculations 
          return b;

     }

     private static double calculateC(double a, double b) {
          // Some calculations 
          return c;
     }
}

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

An alternative solution is to add a static factory method to your record instead of an additional constructor.

For example:

public record MyRecord(double a, double b, double c) {

    public static MyRecord newMyRecord(double a) {
        var b = calculateB(a);
        var c = calculateC(a, b);
        return new MyRecord(a, b, c);
    }


    private static double calculateB(double a) {
        // Some calculations 
        return b;

    }

    private static double calculateC(double a, double b) {
        // Some calculations 
        return c;
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

Using a static factory method is a solution but your API starts to get messy.

It's not possible to lessen the default record constructor visibility by design (https://stackoverflow.com/a/67627794/4425643) so using an external factory class would also be messy.

In your case it would be best if you used a regular class to gain the option of having multiple independent constructors.

over 4 years ago · Santiago Trujillo Relatório

0

The constructor’s first statement must be a constructor invocation, but it doesn’t have to be the canonical constructor. This allows to construct a chain which ends up at the canonical constructor, but introduce local variables (parameters) in-between to avoid redundant calculations:

public record MyRecord(double a, double b, double c) {
     public MyRecord(double a) {
          this(a, calculateB(a));
     }

     private MyRecord(double a, double b) {
          this(a, b, calculateC(a, b));
     }

     private static double calculateB(double a) {
          // Some calculations 
          return b;
     }

     private static double calculateC(double a, double b) {
          // Some calculations 
          return c;
     }
}

But using a factory method, like suggested by this answer might be preferable. The advantage is that factory method can have a clarifying name. E.g.

public static MyRecord fromA(double a) {
…

which even allows to have, e.g.

public static MyRecord fromB(double b) {
…

in the same class. Overloading constructors, on the other hand, requires more care. It should only be used when it is expected to be obvious to the users of the class which parameters have been omitted and in which way they will be generated from the given values.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda