When to use out arguments rather then a return value

55 views Asked by At

While going through some public API's (for instance android.view.View.getLocationOnScreen), I noticed that it's quite common to use an approach of void function with out parameters rather then simply returning a value.

I see the benefits of this approach when there are multiple return values, and it doesn't make sense to create a dedicated complex type to hold them. It is also useful in OOP when a function returns some interface and the user is allowed to choose the implementation most suitable for his case.
In many of the examples I have seen (the one above for instance), this was not the case.

Other then such two specific cases, I see only drawbacks with such approach:

  • It tends to be confusing for rookie developers / users.
  • Every caller must allocate the out parameters memory on its own, which leads to code duplication and possible slippery bugs.
  • It requires the function to perform extra checking for uninitialized out parameters and decide a default behavior when it's not initialized (internal initializing / throwing exception / returning empty or default value).

    So, can you think of any benefits, or a general criteria for cases that should return out values?

  • 0

    There are 0 answers