Creating Immutable Objects with Many Parameters in C#

cimmutabilityinitialization

I need to create an immutable object but it requires several parameters to work like:

class FooRepo
{
    public string ConnectionStringName { get; }
    public string SchemaName { get; }
    public string TableName { get; }
    public Dictionary<string, int> ColumnLengths { get; }
    public Dictionary<Type, SqlDbType> TypeMappings { get; }

    // some queries...
    public IEnumerable<string> GetStrings(object param1) { ... }
}

I find there are too many parameters to pass them all via the constructor (I might add more later).

The idea of locking the object after it's been setup doesn't sound good either.

I thought about creating a FooBuilder but this would only hide a huge constructor.

The only resonable solution I can think of is to define default values for some properties like ColumnLengths and TypeMappings and allow the user to override/customize them by deriving from the original class.

What would you say? Or maybe there are better ways for such a task?

Best Answer

Assumed your class is not "too large" (which you should check first), instead of having a huge constructor argument list in FooRepo, you can pass the values in by utilizing a mutable DTO object as a form of "helper object". This might be a class FooRepoDTO, or when you follow the builder pattern, it could be the FooRepoBuilder itself (which must provide access to all the data passed in by the "Set..." methods.

Related Topic