borgmater borgmater - 28 days ago 8
Java Question

Managing class with many fields

I have a class as follows :

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


It should contain 11 tightly bound parameters, A-K, which describes movement of a point in earths orbit (a sort of coordinate). By that, I mean they cannot be divided into subclasses or other meaningful parts since they all share the same purpose and meaning. All of those parameters should be instantiated together inside a constructor, so another class could make necessary calculations with
Foo
and those 11 fields.
I've been given a comment about the quantity of parameters inside constructor being too many.

Is there another way to initialize a
Foo
object without using the giant constructor, a map of sorts ? Hopefully I am being clear enough, if not, I will provide more details.

Answer

You could use a varargs of double as parameter of your constructor and check its size to ensure that it is the expected one.

Something like:

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 have only one parameter defined in your constructor but you can still provide 11 values for the sake of simplicity as next:

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 an array of double as next:

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});
Comments