0

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?

pondermatic
  • 6,453
  • 10
  • 48
  • 63
  • I voted to close this since as zweiterlinde points out http://stackoverflow.com/questions/514038/elegant-ways-to-return-multiple-values-from-a-function contains the same content. – pondermatic Feb 25 '09 at 23:35
  • It's not the same. I'm asking about this in terms of command/query, not returning multiple values. – pondermatic Dec 04 '09 at 00:38

1 Answers1

0

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:

Elegant ways to return multiple values from a function 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.

Community
  • 1
  • 1
zweiterlinde
  • 14,557
  • 2
  • 27
  • 32