I use C#, and these are my approaches. Consider:
class Foo
{
// private fields only to be written inside a constructor
private readonly int i;
private readonly string s;
private readonly Bar b;
// public getter properties
public int I { get { return i; } }
// etc.
}
Option 1. Constructor with optional parameters
public Foo(int i = 0, string s = "bla", Bar b = null)
{
this.i = i;
this.s = s;
this.b = b;
}
Used as e.g. new Foo(5, b: new Bar(whatever))
. Not for Java or C# versions before 4.0. but still worth showing, as it's an example how not all solutions are language agnostic.
Option 2. Constructor taking a single parameter object
public Foo(FooParameters parameters)
{
this.i = parameters.I;
// etc.
}
class FooParameters
{
// public properties with automatically generated private backing fields
public int I { get; set; }
public string S { get; set; }
public Bar B { get; set; }
// All properties are public, so we don't need a full constructor.
// For convenience, you could include some commonly used initialization
// patterns as additional constructors.
public FooParameters() { }
}
Usage example:
FooParameters fp = new FooParameters();
fp.I = 5;
fp.S = "bla";
fp.B = new Bar();
Foo f = new Foo(fp);`
C# from 3.0 on makes this more elegant with object initializer syntax (semantically equivalent to the previous example):
FooParameters fp = new FooParameters { I = 5, S = "bla", B = new Bar() };
Foo f = new Foo(fp);
Option 3:
Redesign your class not to need such a huge number of parameters. You could split its repsonsibilities into multiple classes. Or pass parameters not to the constructor but only to specific methods, on demand. Not always viable, but when it is, it's worth doing.