Refactoring large constructors

后端 未结 3 935
情深已故
情深已故 2021-01-18 04:04

We have a few objects in our domain model with what you would comically term offensively large constructors, so large that IntelliSense gives up tr

相关标签:
3条回答
  • 2021-01-18 04:32

    There's one thing that I'm not sure about your question, and that is why do you want all such parameters in the constructor? Are you using all of the parameters in the constructor code? Your problem with the intellisense is probably coming from having too many parameters on a single method. Having many number of fields / properties on a single type won't cause any issues.

    It seems that you've seen some ways to manage the number of args, but if you can explain why you need to receive all of them in a constructor, we can think outside this box. There might be something there to look at.

    0 讨论(0)
  • 2021-01-18 04:45

    I would go with the container types and use the immediate properties assignment of C# 4.0. This way one could easily use Intellisense on the resulting type, while still retaining a decent decoupling from the original type.

    For example:

    public class MyLegacyType
    {
        public MyLegacyType(MyConfiguration configuration) // etc
        {
          // ...
        }
    }
    
    public class MyConfiguration
    {
       public int Value1 { get; set; }
       public int Value2 { get; set; }
       // ...
    }
    

    And then:

    var myInstance = new MyLegacyType(new MyConfiguration
    {
      Value1 = 123,
      Value2 = 456
    });
    
    0 讨论(0)
  • 2021-01-18 04:56

    Obviously we don't have much context here, but at 50+ parameters my interpretation is that this class is doing too much, and is too complex. I would start by looking for ways to split chunks out into simpler, more focused types - and then encapsulate instances of each of those concepts into the composite class. So it becomes:

    public MyLegacyType(SomeConcept foo, AnotherConcept bar, ...)
    {
    }
    

    where only the logic necessary for orchestrating between the concepts remains in MyLegacyType (any logic particular to SomeConcept goes there, etc).

    This is different to your "reduce constructor parameters with container types that have properties for what used to be constructor arguments", since we are fundamentally restructuring the logic - not just just using an object to replace the constructor arguments.

    0 讨论(0)
提交回复
热议问题