【问题标题】:How to apply combine technique with if condition如何在 if 条件下应用组合技术
【发布时间】:2017-05-07 16:02:21
【问题描述】:

C#代码语法如下

        public void Cancel()
        {

            // If reservation already started throw exception
            if (DateTime.Now > From)
            {
                throw new InvalidOperationException("It's too late to cancel.");
            }
//for gold customer IsCanceled= false
            if (IsGoldCustomer() && LessThan(24))
            {
                IsCanceled = false;
            }
//for not gold customer IsCanceled= true
            if (!IsGoldCustomer() &&LessThan(48))
            {

                IsCanceled = true;
            }

        }

        private bool IsGoldCustomer()
        {
            return Customer.LoyaltyPoints > 100;
        }

        private bool LessThan(int maxHours)
        {
            return (From - DateTime.Now).TotalHours < maxHours;
        }

注释描述的业务逻辑,想结合 if (IsGoldCustomer() && LessThan(24)) 和 if (!IsGoldCustomer() &&LessThan(48)) 条件。有什么建议吗?

如果条件如下,修改了两者,但修改不符合我的要求。

//for gold customer IsCanceled= false
            IsCanceled = !(IsGoldCustomer() && LessThan(24));
//for not gold customer IsCanceled= true
            IsCanceled = !IsGoldCustomer() &&LessThan(48);

【问题讨论】:

  • 看起来应该重构为返回布尔值的CanCancel 函数。 Cancel 函数可能不应该在非异常情况下失败。

标签: c# coding-style code-cleanup


【解决方案1】:
IsCancelled = IsGoldCustomer()? !LessThan( 24 ) : !LessThan( 48 );

甚至:

IsCancelled = !LessThan( IsGoldCustomer()? 24 : 48 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 2020-02-14
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多