开发者

Class design: Passing values via Property(Set var) vs Function vs Constructor argument

This is a kind of open question. I always keep scratching my head when deciding between these. I can pass values to a class by:

Passing an argument to class function:

MyClass m = new MyClass();
m.DoSomething(arg);

Passing argument when creating object:

MyClass m = new MyClass(arg);
m.DoSomething();

Setting the value using a different function/Property

MyClass m = new MyCla开发者_开发百科ss();
m.SetArg(arg);
m.DoSomething();

I understand it depends on weather the object needs to retain the argument but again I think there is a fine line here? If you pass too many variables it becomes a regular functional call.


Some rule of thumbs I use:

If the argument is vital to the operation of the class, you should pass it in through the constructor.

If it is vital only to that function, pass it in through the function.

If it is simply class data, use setters/properties to populate it.

If there are many such arguments, refactor the arguments to a container class of their own (MyClassSettings, for example).


Use constructor parameters to provide dependencies used by the class.

Use method parameters when passing messages between objects.

Avoid getters and setters when possible (see Why getter and setter methods are evil for a full discussion of this topic).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜