Skip to content

Latest commit

 

History

History
54 lines (45 loc) · 1.1 KB

02-o.md

File metadata and controls

54 lines (45 loc) · 1.1 KB

O - Open-Close

Open for extension, closed for modification. You should not have to rewrite an existing class for implementing new features.

public String hashPassword(String password, HashingType hashingType)
{
    if(HashingType.BASE64.equals(hashingType))
    {
        hashedPassword="hashed with Base64";
    }
    else if(HashingType.MD5.equals(hashingType))
    {
        hashedPassword="hashed with MD5";
    }

    return hashedPassword;
}

Every time a new algorithm is implemented, we need to modify the existing class, and it looks ugly.

public class Base64Hasher implements PasswordHasher
{
    @Override
    public String hashPassword(String password)
    {
        return "hashed with 64";
    }
}
public interface PasswordHasher
{
    String hashPassword(String password);
}
public class MD5Hasher implements PasswordHasher
{
    @Override
    public String hashPassword(String password)
    {
        return "hashed with SHA256";
    }
}

In this way, we can add new algorithms without touching the existing codebase.