简体   繁体   English

如果方法不是我想要的选项,它应该返回什么?

[英]What should a method return if it is not an option I want?

I have this method that takes an array of integers and a target integer.我有这个方法,它接受一个整数数组和一个目标 integer。

It should return an array with the 2 indexes of the 2 items in the array that together sum the target value.它应该返回一个数组,其中包含数组中 2 个项目的 2 个索引,它们共同计算了目标值。

public int[] TwoSum(int[] nums, int target)
{
    for (int x = 0; x < nums.Length; x++)
    {
        for (int y = x + 1; y < nums.Length; y++)
        {
            if (nums[x] + nums[y] == target) { return new int[] { x, y }; }
        }
    }
}

Example:例子:

Input: nums = [3,2,4], target = 6
Output: [1,2]

My question:我的问题:

I get an error because not all paths return something.我得到一个错误,因为并非所有路径都会返回一些东西。 Which is understandable.这是可以理解的。 But what should the method return if it can't find the 2 items?但是,如果找不到这 2 个项目,该方法应该返回什么?

Option 1: return null .选项 1:返回null

Oftentimes viewed as dangerous, outdated, "billion-dollar mistake", you name it.通常被视为危险的、过时的、“十亿美元的错误”,随便你怎么说。 But an option nevertheless.但仍然是一个选择。 Forces the client to perform null -checks, though.不过,强制客户端执行null检查。 More convenient when null actually carries a semantic meaning.null实际上带有语义时更方便。

Option 2: empty Array.选项 2:空数组。

"Better" than null but in this case, you'd need to check if it has the desired length, so equally inconvenient for the scenario at hand. “比null更好”,但在这种情况下,您需要检查它是否具有所需的长度,因此对于手头的场景同样不方便。

Option 3: bool TryTwoSum( int[] nums, int target, out int[] result )选项 3: bool TryTwoSum( int[] nums, int target, out int[] result )

A common pattern when you do not want to throw exceptions.当您不想抛出异常时的常见模式。 The result is only considered valid if the function returns true .仅当 function 返回true时,结果才被视为有效。 You'll see it in a lot of TryParse signatures.您会在很多TryParse签名中看到它。 But this won't help if you must stick with your API.但如果您必须坚持使用 API,这将无济于事。

Option 4: Throw an exception.选项 4:抛出异常。

Not recommended to control flow.不建议控制流量。 Since not finding a result would not really be an exceptional result, it shouldn't be handled as one.由于找不到结果并不是真正的异常结果,因此不应将其作为一个结果处理。 Also, exceptions are considered to be relatively expensive and can be clunky to handle.此外,异常被认为是相对昂贵的并且处理起来很笨重。 Among other drawbacks.除其他缺点外。

An opposing example would be to throw ArgumentNullException if nums is passed as null .一个相反的例子是,如果nums作为null传递,则抛出ArgumentNullException That's clearly an exceptional condition that is indicative of a programming error at the client (= caller).这显然是一种异常情况,表明客户端(= 调用者)存在编程错误。

Option 5: return new int[]{-1,-1}选项 5:返回new int[]{-1,-1}

To indicate "no result" without exceptions, without null and with the expected amount of items.无一例外地表示“无结果”,没有null和预期的项目数量。 A little bit like returning -1 from IndexOf as mentioned in comments by Mong Zhu.有点像孟竹评论中提到的从IndexOf返回-1 Drawback: would really need to be documented because it's not really that obvious that this is how "not found" is represented.缺点:确实需要记录下来,因为“未找到”的表示方式并不是那么明显。

Option 6: A result - object选项 6:结果 - object

Basically a wrapper which contains an indicator if the operation has been successful and the result value.基本上是一个包装器,其中包含操作是否成功的指示器和结果值。 This could be implemented in various ways.这可以以各种方式实施。 Either with properties or with polymorphism... You may have seen this in Web-Controllers for example.使用属性或使用多态性...您可能已经在 Web-Controllers 中看到了这一点。 May be a little overpowered for this scenario.对于这种情况可能有点过分。 But can lead to very readable code.但是可以导致非常可读的代码。


Just to name a few.仅举几个。 Which one is correct?哪一个是正确的? That's up to you and your requirements.这取决于您和您的要求。 Some may be more convenient than others for this specific case.对于这种特定情况,有些可能比其他的更方便。 There is not one option, that is always the best one.没有一种选择,那永远是最好的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 `FindBaseClassWith`方法应该返回什么? - What should the method `FindBaseClassWith` return? 我应该从服务层或几乎任何方法返回什么 - What should I return from service layers or almost any method 我的类应该实现哪种接口或方法以在Console.WriteLine中打印我想要的内容? - What interface or method should my class implement to print what I want in Console.WriteLine? 如果要对以表达式为参数的方法进行单元测试,应该更改什么? - What should I change if I want unit test a method with expression as a parameter? 我应该使用什么方法作为IEnumerable,IList,Collection或方法的返回类型 - What should I use as return type of method IEnumerable, IList, Collection or what 当我调用异步方法时,应使用哪种返回类型来表示成功? - When I call an Async method what return type should I use to indicate success? 如果我想返回WebClient的结果该怎么用 - What to use if i want to return the result of a webclient 如果我将一个方法标记为Obsolete [“…”,true],则返回值应该是多少? 任意值? - If I mark a method as Obsolete[“…”, true], what should be the return value? An arbitrary value? 我应该用这种方法返回什么来获取系和系中存在的学生名单? - What should I return in this method to get department and list of students present in department? 在异步方法结束时,我应该返回还是等待? - At the end of an async method, should I return or await?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM