What is the best way to refactor switch statements that use variables

Viewed 58

Heyy

I have a code that definitely should be refactored. It was written for login with username and password purpose but then added other login methods as a classic development story.

It is obvious that I should use interface. However login methods do different things and all uses variables and functions from controller class in MVC architecture. That's why if I separate them, it will be really hard for me to make it work again.

It is a basic scheme that looks like my problem

public class LoginController
{
    public string username { get; set; }
    public Certificate serverCertificate { get; set; }
    public Version serverVersion { get; set; }
    public bool serverCertValid { get; set; }

    public LoginTypes loginType;

    void Login()
    {
        checkX();
        checkY();
        checkZ();
    }

    private void checkX()
    {
        switch (loginType)
        {
            case LoginTypes.DEFAULT:
                username = Console.ReadLine();
                break;
            case LoginTypes.CARD:
                username = readFromCard();
                serverCertificate = checkDeviceCertificate();
                break;
            case LoginTypes.API:
                username = getUsernameRequest();
                serverVersion = readServerVersionFromX();
                break;
            default:
                break;
        }
    }

    private void checkY()
    {
        switch (loginType)
        {
            case LoginTypes.DEFAULT:
                //
                break;
            case LoginTypes.CARD:
                serverCertValid = checkIfValidate(serverCertificate);
                break;
            case LoginTypes.API:
                //
                break;
            default:
                break;
        }
    }
}

public enum LoginTypes
{
    DEFAULT,
    CARD,
    API
}

So basically,

I have code that is not written suitable for OOP systems. And functions are too complicated. I have different login types that uses functions and variables in controller class. So even if I want to make a class that implements interface for each login type. I have to pass lots of variables with them.

0 Answers
Related