views:

61

answers:

2

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 MyClass();
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.

+5  A: 

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).

Oded
The problem with getters and setters is the caller may call methods without setting required members. Then the question becomes how far do you to validate them..
tvr
@user: if the properties call methods which are dependent on come class member, then those class members must be set in the constructor.
John Saunders
A: 

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).

Derek Greer
-1 for not saying why to avoid getters and setters, and for saying so to begin with.
John Saunders
My appologies for not meeting your personal level of answer criteria.
Derek Greer
+1 It's a great answer... no clue why we need to downvote this one.
Byron Sommardahl