Local variables before return statements, does it matter?

后端 未结 3 861
遇见更好的自我
遇见更好的自我 2020-12-02 19:20

Sorry if this is a newbie question but I couldn\'t find an answer for this. Is it better to do this:

int result = number/number2;
return result;
3条回答
  •  庸人自扰
    2020-12-02 19:40

    Choose the version that you think is more readable.

    There are legitimate cases where the named variable improves readability. For example

    public String encrypt(String plainString)
    {
        byte[] plainBytes      = plainString.getBytes(StandardCharsets.UTF_8);
        byte[] hashPlainBytes  = enhash( plainBytes, 4 );
        byte[] encryptedBytes  = doAes128(Cipher.ENCRYPT_MODE , hashPlainBytes );
        String encryptedBase64 = Base64.getEncoder().withoutPadding().encodeToString(encryptedBytes);
        return encryptedBase64;
    }
    
    public String decrypt(String encryptedBase64)
    {
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedBase64);
        byte[] hashPlainBytes = doAes128(Cipher.DECRYPT_MODE , encryptedBytes );
        byte[] plainBytes     = dehash( hashPlainBytes, 4 );
        String plainString = new String(plainBytes, StandardCharsets.UTF_8);
        return plainString;
    }
    

    There are also cases where we need a variable in a different type from the return type. This affects type conversion and inference, making a significant semantic difference.

    Foo foo()            vs.        Foo foo()
    {                               {
                                        Bar bar = expr;
        return expr;                    return bar;
    }                               }
    

提交回复
热议问题