使该代码递归的最佳方法是什么
我必须编辑一些具有 suggestDate (作为名为 minDate 的 DateTime 对象)和一组中断日期的代码。给定一个提议的日期,它会尝试查看该日期是否有效(不是限制日期)。如果这是一个限制日期,请继续检查第二天,直到找到不是有效结账日期的日期。现有的代码看起来像这样
if ( blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
if ( blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
if (blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
}
}
}
显然这里有一个重复的模式,我试图找出清理这段代码并使其优雅的最佳方法。
I have to edit some code that has a proposedDate (as a DateTime object called minDate) and an array of blackout dates. Given a proposed Date, it tries to see if this is valid (NOT a blackout dates). If it is a blackout date, then keep checking the next day until you find a date that is not a valid checkout date. The existing code looks like this
if ( blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
if ( blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
if (blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
}
}
}
Clearly there is a repeated pattern here and I am trying to figure out the best way to clean up this code and make it elegant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不需要递归。您可以循环执行此操作。
我不知道这是什么语言,但首先检查是否已经有一个标准 API 可以完成您需要的操作。
No need for recursion. You can do this in a loop.
I don't know what language is this, but check if there is already a standard API for doing what you need first.
我不会让它递归。我会将其设为 while 循环:
递归可以表达循环,但循环结构在其设计的上下文中使用时通常会更清晰。它们还使得访问循环范围之外的数据比递归(特别是局部变量)更简单。
I wouldn't make it recursive. I would make it a
while
loop:Recursion can express loops, but looping constructs are usually clearer when used in the context they are designed for. They also make it a bit simpler to reach data that is outside the scope of the loop than recursion does (specifically local variables).