Reputation: 6095
I've got a class that I want make sure the Complete method complete gets called ...somehow. For example:
public class Order
{
public Guid TransactionId {get; private set;}
public void Complete(Guid transactionId)
{
TransactionId = transactionId;
}
}
How can i ensure that the Complete method gets called by clients?
public class Cart
{
public void Process()
{
Order o = new Order();
// Do stuff
o.Complete(GetTransactionId());
}
}
The above code seems weak in that its feasible that the complete methods does not get called:
public class Cart
{
public void Process()
{
Order o = new Order();
// Do stuff
}
}
Heard about events but not too sure if that is the correct solution...Any ideas?
Upvotes: 1
Views: 115
Reputation: 1093
You want to force the user of an Order to remember to complete it, is that it? If it is the user's choice when to call Complete() then that's gonna be hard. I guess that you either want the complete to be automatically done after something else that is done with the order or you have to somehow make sure that it will be obvious to the user that he forgot to complete it.
It is hard to know without more details of what an order is and how it is used.
Upvotes: 0
Reputation: 32438
You could make it implement IDisposable
and always create a new order within a using statement. That way you can control when the Complete
method gets called.
Upvotes: 2
Reputation: 56408
The only way that would not get called is if there was an exception or some other behavior that caused it not to progress to the next statement (ie, catastrophic failure).
You can guard against an exception preventing it from happening by putting it in a finally
block:
public void Process()
{
try {
Order o = new Order();
// Do stuff
} finally {
o.Complete(GetTransactionId());
}
}
Upvotes: 0