• 23-11-2013, 12:46:40
    #1
    #1: If + Büyük kod + küçük else

    Kötü;

    public function foo($user)
    {
        if ($user->hasAvatar()) {
            // tons of amazing code that make you scroll to the infinity
            // ...
        } else {
            // typical check
            return false;
        }
    }
    Daha iyi;

    public function foo($user)
    {
        if (!$user->hasAvatar()) {
            return false;
        } else {
            // tons of code that you should refactor :)
            // btw, check the next one for this case
        }    
    }
    #2: If + return + gereksiz else

    Kötü;

    public function foo($user)
    {
        if (!$user->hasAvatar()) {
            return false;
        } else {
            // do something...
        }
    }
    Daha iyi;

    public function foo($user)
    {
        if (!$user->hasAvatar()) {
            return false;
        }
    
        // do something...
    }
    #3: If + return true + else return false

    Kötü;

    public function foo($user)
    {
        if ($user->hasAvatar()) {
            return true;
        } else {
            return false;
        }
    }
    Daha iyi;

    public function foo($user)
    {
        return $user->hasAvatar();
    }
    #4: If + return A + else return B

    Kötü;

    public function foo($user)
    {
        if ($user->hasAvatar()) {
            return 'yeah!';
        } else {
            return 'woo!';
        }
    }
    Daha iyi;

    public function foo($user)
    {
        return $user->hasAvatar() ? 'yeah!' : 'woo!';
    }
    #5: If + else varsayılan değer

    Kötü;

    public function foo($user)
    {
        if ($user->hasAvatar()) {
            $result = 'yeah!';
        } else {
            $result = null;
        }
    
        // Do whatever with $result...
        return $result;
    }
    Daha iyi;

    public function foo($user)
    {
        $result = null;
        if ($user->hasAvatar()) {
            $result = 'yeah!';
        }
    
        // Do whatever with $result...
        return $result;
    }
    Yabancı bir blogdan aldım arkadaşlar. Faydalı bilgi olduğu için paylaşıyorum.
  • 23-11-2013, 14:26:39
    #2
    Kimlik doğrulama veya yönetimden onay bekliyor.
    public function foo($user)
    {
        $result = null;
        if ($user->hasAvatar()) {
            $result = 'yeah!';
        }
    
        // Do whatever with $result...
        return $result;
    }
    yerine

    public function foo($user)
    {
    	return ($user->hasAvatar()) ? "yeah!" : null;
    }
    olabilirdi.