Multi-field class management

I have a class as follows:

public class Foo {
    private double A;
    private double B;
    ...
    private double K;
}

It should contain 11 closely related parameters, AK, which describes the movement of a point in the Earth’s orbit (a kind of coordinate). I mean that they cannot be divided into subclasses or other significant parts, since they all have the same purpose and meaning. All these parameters must be created together inside the constructor, so another class can perform the necessary calculations using Foothose 11 fields. I was given a comment that the number of parameters inside the constructor is too large.

Is there any other way to initialize an object Foowithout using a giant constructor, a kind map? I hope I will be clear enough, if not, I will tell you more.

+4
source share
4 answers

You can use your constructor as a parameter and check its size to make sure that it is the expected one.varargs double

Sort of:

public class Foo {
    private double A;
    private double B;
    ...
    private double K;

    public Foo(double... coordinates) {
        if (coordinates == null || coordinates.length != 11) {
            throw new IllegalArgumentException("Unexpected size of coordinates");
        }
        this.A = coordinates[0];
        this.B = coordinates[1];
        ...
        this.K = coordinates[10];
    }
    ...
}

This way, you only have one parameter defined in your constructor , but you can still provide values 11for simplicity as follows:

Foo foo = new Foo(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0);

And you can still provide it as arrayof doubleas follows:

Foo foo = new Foo(new double[]{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0});
+2
source

11, , , Array List.

11 , Foo Factory. Factory 11 11 .

Factory 11 .

+1

, , A, B.

.

, , , :

interface FooData {
    double getA();
    ...
}

.

" " , Factory Builder . Factory, , (, A 1,0 0,0). Builder .

, Factory , 11 , .

+1

, , 11 . , :

public class AValue {
  public final double val;
  public AValue(double val) { this.val = val; }
}

, , ( ?) : 10 , 11 AValue KValue.

public Foo(AValue a, BValue b, ... and so on) {

, Foo.

, Foo 11 ; - , 11 . , ,

AValue getA()

Foo.

, :

interface ValueType { public double getValue(); }
class AValue implements ValueType {
  ...
  @Override
  double getValue() { return value; }

public class Foo {

  public Foo(AValue a, BValue b, ... KValue k) {
     this((ValueType) a, ..., (ValueType) k);
  }
  Foo(ValueType... values) {
    ... push values into double[]
0

Source: https://habr.com/ru/post/1659818/


All Articles