What is the most efficient design for numerous classes with similar but no congruent constructors?

I work with a library of classes that have, first of all, huge constructors, with fifteen or twenty arguments missing. There are twenty or so, and they have similar, but not quite the same arguments. In some, argument twelve is omitted, while in others it is indicated, but not required ...

I am going to put these arguments into objects because many of them are related to each other, for example, FirstName, LastName and the email address in the Person object. But this, apparently, leads to several classes of monsters in which NO using an object never uses ALL arguments, and most applications will use only a few.

Currently, all the validation logic is in all constructors ... if I can crack the problem of the chain of constructors located along the inheritance chain, then I can create an abstract Validate () method that each class can override and simplify the design. I checked Refactoring for Templates, but I did not see anything similar to this question.

Note: this is not a hoax for this - I'm talking about similar constructors, not about similar objects. I have abstract base classes from wazoo.

+4
source share
1 answer

I am going to compose these arguments into objects, because many of them are related to each other.

That sounds like a good step for me.

But this, apparently, leads to several classes of monsters

I donโ€™t understand why they should be classes of โ€œmonstersโ€ in general - you can save them as simple DTO classes, although you probably want to provide some verification that if an email address is specified, this is really a valid email address, etc. d.

in which NO use of an object never uses ALL arguments

Well, using an object never uses all the properties. This is good - multiple uses of DateTime use each individual property, for example.

You do not need to specify all the values โ€‹โ€‹when constructing Person - work out, which ones are really necessary for all applications, and put them in the constructor ... then either use the optional parameters for the parameter, or simply properties to make the Person type mutable. So you could:

 Person person = new Person("Jon", "Skeet", // Required parameters email: " skeet@pobox.com "); // Optional 

Or:

 Person person = new Person("Jon", "Skeet") { Email = " skeet@pobox.com " }; 

Personally, I like the first approach, as this means that your object can be immutable, but it depends on how you feel about the optional parameters.

In any case, your other classes now just need to take these big drops (for example, two Person links and a Location link instead of 12 different links). They can assume that all the required values โ€‹โ€‹in large blocks are already filled (since they will be checked in the constructor), and then they can simply check that all the additional values โ€‹โ€‹they require are also filled.

+3
source

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


All Articles