Class c = new Class( { Prop = "Initial" } );
I have the class above. How would you create a method to modify it?
public Class ModifyIt(Class c)
{
c.Prop = "changed";
return c;
}
or
public void ModifyIt(Class c)
{
c.Prop = "changed";
}
Then called like this...
Class c = ModifyIt(c);
Console.WriteLine(c.Prop);
// changed
or this
ModifyIt(c)
Console.WriteLine(c.Prop);
// changed
Whats your preference?
Personally, I prefer command-query separation -- i.e., methods returning a result should not be mutators, and vice versa. I understand the arguments for the return this
crowd, i.e., the ease of "chaining" calls:
foo.ChangeThis(23).ChangeThat(45).AndAlso(67);
but it's definitely not too bad to code those cases as
var x=foo;
x.ChangeThis(23); x.ChangeThat(45); x.AndAlso(67);
meanwhile, the advantages of "command-query separation" (in the vast majority of cases, though admittedly not 100% of them), as discussed at that wikipeida URL, endure...
The choice of returning an instance of the object or not would depend on the situation.
A common case for the returning the object by the method is seen in the builder pattern, such as the StringBuilder
class:
new StringBuilder("Hello").Append(" ").Append("World!").ToString();
But in general, if such method chaining isn't going to be performed, I would choose not to return anything. If the common use-case is to not use the object that is returned (and just dropping it), which would seem to be a waste.
The cool thing about doing it the first way, in which you're actually returning the item after changing it, is that it allows method chaining. Meaning you can do something like this:
c.ModifyIt("hello").MessWithIt("World").ReallyScrewWithIt("!!!");
If it makes sense with your specific class where you can foresee a need for chaining, then return the instance. If not, then you can just make it void. A good example of this is the StringBuilder class which allows you to do something like:
myStringBuilder.Replace("!", "?").Append("Something").Remove(4,3);
I would personally prefer to build a function like ModifyIt and put it on the class I'm creating if it's possible. The reason I say that is in both methods I'm modifying the calling variable cause I'm passing it by reference. Naturally, I can't do that for all functions, but putting ref in the function call helps clarify that I'm passing an variable by reference, not not passing a variable by value. Example:
public Class ModifyIt(ref Class c)
Why? Cause I'm liable to forget when I come back and read the code that I passed the value by reference and am then more likely do something "bad" to the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With