I'm making an "adapter" base class that instantiates a private struct. The struct is exposed to inheritors via an abstract Configure() method, so they can set properties on it. Implementation as follows:
public abstract class PaymentAdapter {
private PaymentObject p = new PaymentObject();
protected PaymentObject CreditCardPayment {
get { return p; }
}
protected abstract void Configure(PaymentObject payment);
public MyResponse ProcessPayment() {
// Run the adapter's setup
Configure(p);
// Charge the customer
var chargeResult = p.DoSomething();
return new MyResponse {
MyResult = chargeResult
};
}
}
Those of you who are observant will see what the following line needs some attention:
protected abstract void Configure(PaymentObject payment);
When overridden in a concrete class, this method (almost) gives the consumer the opportunity to modify the struct's properties directly. This is the desired result.
My question is - should I use a ref argument, or change the void to PaymentObject, making the consumer return an instance themselves?
Method 1:
protected abstract PaymentObject Configure(PaymentObject payment);
Method 2:
protected abstract void Configure(ref PaymentObject payment);
So, when inheriting the class, the consumer would have to do the following:
Method 1:
public class MyConsumer : PaymentAdapter {
#region Overrides of PaymentAdapter
protected override PaymentObject Configure(PaymentObject payment) {
payment.AProperty = "Something";
return payment;
}
#endregion
}
Method 2:
public class MyConsumer : PaymentAdapter {
#region Overrides of PaymentAdapter
protected override void Configure(ref PaymentObject payment) {
payment.AProperty = "Something";
}
#endregion
}
Apart from the slight change in syntax, are there any other differences at all? Is this a preference thing, or are there benefits I can't see to using one over the other?
As there's slightly less code, I would be inclined to use the "ref" method, contrary to all my years of exclusively returning objects from methods. This seems like a perfect case for a ref argument - it makes the consumer's job slightly easier, and means I'm not setting objects all over the place.