gpt4 book ai didi

c# - 验证公共(public)/私有(private)方法的函数参数时的最佳实践

转载 作者:太空狗 更新时间:2023-10-30 00:15:07 25 4
gpt4 key购买 nike

<分区>

做一些研究,似乎人们普遍认为应该验证公共(public)方法的参数,而私有(private)函数通常不需要。这让我产生了一些疑问,但到目前为止我还没有找到满意的答案。

例子:

public void DoSomething(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");

double d = DoWork(i);
}

private double DoWork(int i)
{
double ret = ...; // some calculation
return ret;
}

想法:

  1. 如果 i 的要求在 DoWork() 内部发生非负变化怎么办?该设计存在遗留过时验证检查的风险。我知道,程序员负责调整已更改函数的用法,但这让我想知道是否有更好的方法来最大程度地降低错误风险。

  2. DoWork() 不是来自 DoSomething() 的不同调用怎么样?我们必须冗余地验证参数吗?

public void DoSomething(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");

double d = DoWork(i);
}

public void DoSomethingElse()
{
int i = 5;
if (i < 0)
throw new ArgumentOutOfRangeException("i");

double d = DoWork(i);
}

private double DoWork(int i)
{
double ret = ...; // some calculation
return ret;
}

这可以通过将检查放入它自己的函数中来稍微清理一下。然后存在调用 DoWork(int i) 的新函数将忘记验证 i 的风险。

public void DoSomething(int i)
{
ThrowIfIntegerIsNegative(i);

double d = DoWork(i);
}

public void DoSomethingElse()
{
int i = 5;
ThrowIfIntegerIsNegative(i);

double d = DoWork(i);
}

static void ThrowIfIntegerIsNegative(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
}

private double DoWork(int i)
{
double ret = ...; // some calculation
return ret;
}

那比这更好吗?

public void DoSomething(int i)
{
double d = DoWork(i);
}

public void DoSomethingElse()
{
double d = DoWork(5);
}

private double DoWork(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");

double ret = ...; // some calculation
return ret;
}

根据情况,这些是我试图同时实现的一些目标:

  1. 在一个地方进行参数验证(并且可能在使用参数的函数内部)
  2. 尽早报告错误(可能不想让一堆代码运行一个小时只是为了在最后因一些错误的用户输入而失败)
  3. 避免多次验证参数
  4. 避免发布代码中的性能影响

您如何取得平衡?哪种方法最适合您?我将不胜感激任何见解。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com