tags:

views:

90

answers:

1

Often when we're issuing commands or to querying our objects, there is extra information about the operation that we need to get back to the caller. E.g.

bool IsSomethingOkayToDo()

In this case, if false, we might want the caller to know why it wasn't okay to do.

In C# typically I do:

string reason; foo.IsSomethingOkayToDo(out reason);

(Or in the case of multiple reasons you could pass in a list.)

Is this the best way? Assuming I want to adhere to command/query and side effect free functions, are there other OO approved alternatives?

A: 

One option is to return multiple values. In Python, it's simple and considered idiomatic:

isOK, reason = foo.is_something_ok_to_do()

The topic of multiple return values---and how to use them in different contexts---has come on SO several times:

http://stackoverflow.com/questions/514038/elegant-ways-to-return-multiple-values-from-a-function http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values

Command-query separation can be trivially enforced, by adding state to the object recording the results of an action. However, there can be negative side effects such as concurrency problems (see the Wikipedia page on this). For example:

foo.do_something()
is_ok = foo.did_something_succeed()
reason = foo.something_success_reason()

Each of these is either a command that does not return a value, or a query that returns a value and does not modify state.

zweiterlinde