如何避免布尔标志?

时间:2018-03-29 19:38:44

标签: ios swift architecture

我习惯使用布尔标志,他们让我的代码的某些部分只使用一次(但不仅仅是在开头),然后将条件更改为反对值,而不再重复。

例如:

bool isInited = false
var amount: Int = 0

func thatFunctionRunsManyTimes() {


    if !isInited && amount > 3 {
        isInited = true
        // some additional code
    }

    // some code
    amount += 1
}

我的问题是:这是一个糟糕的解决方案和代码味道吗? 如果答案是肯定的,你能告诉我如何避免使用它吗?

2 个答案:

答案 0 :(得分:0)

您要解决的具体问题是什么?如果您要执行一次代码并重复执行代码,为什么不将代码封装在多个函数中?

func once() {
    // Do stuff once
}

func repeatedly() {
    // Do stuff repeatedly
}

func do() {
    once()
    while(condition) {
        repeatedly()
    }
}

答案 1 :(得分:0)

检查此解决方案一次。         bool isInited = false         var amount:Int = 0

    func thatFunctionRunsManyTimes() {

  //  This if line condtion never be going true, bcz isInited set false first and check with amount with 'And' condition.
    first need to check isInited false with amount contion.
   if isInited && amount > 3 {
    isInited = true
    // some additional code
  }

  // some code
  amount += 1
   }