Нужна помощь в рефакторинге вложенных операторов if else - PullRequest
0 голосов
/ 16 июня 2011

Пожалуйста, найдите следующий код и помогите мне написать лучший код if...else.Я чувствую, что это намного ниже среднего способа написать еще, если.

   {
        Retrieve the number in focus.
        string number= getnumber();
        string zipcode;
        int corporate;
        bool bCoverageInBet = false;
        try
        {
            //Get the address and zipcode of the number
            GetAddress(number, out address);

            if (adress!= null)
            {
                zipcode = adress.zipcode
                //if the following are null means this is first time call
                if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
                {
                    if (zipcode.Equals(_loadedZipcode))
                    {
                        if (adress.Equals(_address ))
                        {
                            if (focusChanged)
                            {
                                return result;
                            }
                        }
                        else
                        {
                            if (bCoverageInBet)
                            {
                                // case 2: Different address and different coverage which is in between, make a call anf get new valus for result                                    
                                //return the new result
                            }
                            else
                            {
                                return //current result value;
                            }
                        }
                    }   
                }             
                else 
                    {
                        _loadedZipcode = zipcode;
                        _address = adress;
                        GetResponse( out resp)
                        {
                            if ((resp != null))
                            {
                                bool isCorporate = false;
                                corporate = getValues();
                                if (corporate .Equals(100))
                                {
                                   result = true;
                                   return result;
                                }
                                else if (corporate > 0 && corporate < 100)
                                {
                                    //Make a call to get corporate 
                                    bCoverageInBet = true;
                                    LocationResponse objResults;
                                    if (GetAddressbycorporate(out objResults, out errMsg))
                                    {
                                        if (objResults != null)
                                        {
                                            isCorporate = objResults.located;
                                            if (isCorporate )
                                            {
                                                result = true;
                                            }
                                        }

                                    }
                                }
                                return result;
                            }
                            return result;
                        }
                        else
                        {
                            DisplayError("No response ");
                            return result;
                        }
                    }
                }

            else
            {
               //To do: What is address comes null
            }
        }
        catch (System.Exception ex)
        {
            //some ccode
        }
        return result;
   }

Спасибо K

Ответы [ 2 ]

4 голосов
/ 16 июня 2011

Измените метод на более мелкие единицы в зависимости от ситуации.Кроме того, вернитесь рано из метода, а не используйте предложения else.

Например, вместо

 if (adress!= null)
 {
    zipcode = adress.zipcode

    //if the following are null means this is first time call
    if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
    {
    }
    else
    {
      return false;
    }
 }
 else
 {
   return false;
 }

Do:

 if (adress == null)
 {
   return false;
 }

 if (string.IsNullOrEmpty(_loadedZipcode) || _address == null)
 {
   return false;
 }

Есть довольно много других проблем,но это должно сделать код чище для начала.

3 голосов
/ 16 июня 2011

Я не думаю, что кто-то собирается "помочь" вам переписать этот код. Тем не менее, я могу предложить несколько предложений.

Мне было легче проследить мой путь до самого внутреннего, если бы я попытался переписать и продолжить свой путь назад (вверх по цепочке). В зависимости от блока IF, иногда проще разбить их на отдельные методы, где это необходимо.

Также не забывайте об условном операторе. Иногда бывает проще использовать это, чем целый блок if else.

Например, property = (boolean expression) ? (true value) : (false value);

Вот ссылка на MSDN на нем: документация условного оператора

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...