Сколько переменных конструктор должен иметь?

КОЛИЧЕСТВО (*) факты и мифы:

МИФ : "InnoDB не обрабатывает количество (*) запросы хорошо":

Большая часть количества (*) запросы выполняются тот же путь всеми механизмами устройства хранения данных, если у Вас есть оператор Where, иначе Вы, InnoDB должен будет выполнить полное сканирование таблицы.

ФАКТ : InnoDB не оптимизирует количество (*) запросы без где пункт

32
задан SuperSized 16 September 2009 в 17:46
поделиться

11 ответов

Generally I've found if there's more than 3, that's a sign to do a quick sanity check on the design. If there's more than 5, that's a major warning that something is probably wrong with the design.

However, note the word "probably" - in the end, the only real rule is use as many as needed to function, no more and no less. There are always exceptions and cases where more parameters makes the most sense.

If the parameters are related somehow, you should encapsulate them into a container class.

If the parameters are not related - e.g. it makes no sense to group them into a container class - your class is probably doing too many things. There's generally no reason a single class should be aware of 7 totally disparate pieces of information. Break your class apart into separate classes. It might make sense to delegate parameters 3 and 4 to a subclass and 5, 6 and 7 to another class for example - and your parent class simply coordinates the operations between them.

34
ответ дан 27 November 2019 в 20:11
поделиться

For me, the correct answer is:

You should pass in as many variables as is required to setup the object in a state that is not invalid.

Anything else that is "option", I prefer to leave as properties, especially now that C# provides object initializers.

38
ответ дан 27 November 2019 в 20:11
поделиться

Its difficult to put a hard, fast number to what is "too much". The real question is this: What is your class doing? Is the class doing too much? If so, it is time to break the class into smaller, more concise classes.

Constructor parameters should include as many as necessary to define the dependencies/inputs for the class. If the class is reduced to have one job in life, then your constructor parameters will probably be correct.

5
ответ дан 27 November 2019 в 20:11
поделиться

As others have said, there is no hard rule on this, it really depends. However, there is concrete evidence as to how many things a person's brain can grasp at once: that's the 7 + or - 2 rule.

This type of question is very well answered in Code Complete by Steve McConnell. I recommend you read this book if you haven't already.

2
ответ дан 27 November 2019 в 20:11
поделиться

One thing I love about the 3.5 framework...

new Foo {
    Street = "909 Rose Ave",
    City = "San Diego",
    State = "CA",
    FName = "Joe",
    LName = "Wazowski",
    ID = "987665454"
};

No more worrying about too many constructors, or too many constructors with too many parameters.

1
ответ дан 27 November 2019 в 20:11
поделиться

My personal rule of thumb is 5

If you need more, wrap them in a structure or object.

This changes when you do not have to initialize the object. If I initialize an object using a IOC container the number of constructure parameters are basically unlimited.

1
ответ дан 27 November 2019 в 20:11
поделиться

Especially since the newer features that allow you to set variables in a block with the instantiation, I tend to only use parameters on creation for things that HAVE to be set when the class is created, in which case I make the basic constructor private or protected.

For example, if you had a class Rectangle, it might make sense to make the constructor Rectangle(double width, double height), and make the Rectangle() constructor private.

0
ответ дан 27 November 2019 в 20:11
поделиться

A system has too many parameters as soon as it becomes hard to remember how to use them. If they are all ints, 3 is too many. If they are different types you can have more.

This is a smell in Martin Fowler's Refactoring book. This web page contains links to standard refactorings that help.

In your case, you might want to consider a builder object (where you can gradually add the parameters and the builder figures out the class) or a parameter object.

0
ответ дан 27 November 2019 в 20:11
поделиться

Also, you might put a parameterless private constructor, if you believe that your class should only set it's properties values through the constructor.

0
ответ дан 27 November 2019 в 20:11
поделиться

IMHO, использование TDD - полезная перспектива для оценки этой проблемы. Если ваш ctor трудно применить к модулю тестирования ctor или SetUp (), аргументов инициализации / фабрики слишком много и они относительно слишком тесно связаны.

0
ответ дан 27 November 2019 в 20:11
поделиться

Вам нужно передать все необходимое для создания класса. Что я часто делаю, когда обнаруживаю, что передаю множество переменных, так это создаю класс «Конфигурация» для объекта, который содержит информацию, необходимую для его создания, передавая это конструктору. Это значительно упрощает создание экземпляров объектов и делает дизайн более чистым.

0
ответ дан 27 November 2019 в 20:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: