Class with too many parameters: better design strategy?

后端 未结 13 896
醉酒成梦
醉酒成梦 2020-12-04 08:29

I am working with models of neurons. One class I am designing is a cell class which is a topological description of a neuron (several compartments connected together). It ha

相关标签:
13条回答
  • 2020-12-04 08:52

    You could create a class for your parameters.

    Instead passing a bunch of parameters, you pass one class.

    0 讨论(0)
  • 2020-12-04 08:52

    Want to reiterate what a number of people have said. Theres nothing wrong with that amount of parameters. Especially when it comes to scientific computing/programming

    Take for example, sklearn's KMeans++ clustering implementation which has 11 parameters you can init with. Like that, there are numerous examples and nothing wrong with them

    0 讨论(0)
  • 2020-12-04 08:53

    I'd say there is nothing wrong with this approach - if you need 15 parameters to model something, you need 15 parameters. And if there's no suitable default value, you have to pass in all 15 parameters when creating an object. Otherwise, you could just set the default and change it later via a setter or directly.

    Another approach is to create subclasses for certain common kinds of neurons (in your example) and provide good defaults for certain values, or derive the values from other parameters.

    Or you could encapsulate parts of the neuron in separate classes and reuse these parts for the actual neurons you model. I.e., you could write separate classes for modeling a synapse, an axon, the soma, etc.

    0 讨论(0)
  • 2020-12-04 08:56

    I have never had to deal with this situation, or this topic. Your description implies to me that you may find, as you develop the design, that there are a number of additional classes that will become relevant - compartment is the most obvious. If these do emerge as classes in their own right, it is probable that some of your parameters become parameters of these additional classes.

    0 讨论(0)
  • 2020-12-04 08:59

    This is similar to the other solutions that iterate through a default dictionary, but it uses a more compact notation:

    class MyClass(object):
    
        def __init__(self, **kwargs):
            self.__dict__.update(dict(
                arg1=123,
                arg2=345,
                arg3=678,
            ), **kwargs)
    
    0 讨论(0)
  • 2020-12-04 09:00

    Having so many parameters suggests that the class is probably doing too many things.

    I suggest that you want to divide your class into several classes, each of which take some of your parameters. That way each class is simpler and won't take so many parameters.

    Without knowing more about your code, I can't say exactly how you should split it up.

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