How do you return two values from a single method?

后端 未结 22 781
谎友^
谎友^ 2020-12-11 00:58

When your in a situation where you need to return two things in a single method, what is the best approach?

I understand the philosophy that a method should do one t

22条回答
  •  春和景丽
    2020-12-11 02:02

    You should also consider whether the design of your method is primarily returning a single value, and you are getting another value for reference along with it, or if you really have a single returnable thing like first name - last name.

    For instance, you might have an inventory module that queries the number of widgets you have in inventory. The return value you want to give is the actual number of widgets.. However, you may also want to record how often someone is querying inventory and return the number of queries so far. In that case it can be tempting to return both values together. However, remember that you have class vars availabe for storing data, so you can store an internal query count, and not return it every time, then use a second method call to retrieve the related value. Only group the two values together if they are truly related. If they are not, use separate methods to retrieve them separately.

提交回复
热议问题