How to handle state of object? Expose or handle internally?

by Creepin   Last Updated September 14, 2018 20:05 PM

What is the correct way to handle states of objects from a software engineering point of view?

As introduction to my question:

I have an examplary interface:

public interface ILoginService
{
    void Login();
    void Logout();
    bool IsLoggedIn { get; } // <-- should that be exposed?
}

An examplary implementation could look like this:

public class LoginService : ILoginService
{
    private bool _loggedIn;
    public IsLoggedIn => _loggedIn;

    public void Login()
    {
        if (!IsLoggedIn) // <-- should that be done?
        {
            // Login procedure
        }
    }

    // Logout ...   
}

What of the variants would be the right one?

Variant A

Expose the IsLoggedIn property via interface but don't check IsLoggedIn before login procedure within implementation. Reason: If I expose the property, I expect the calling client to handle it correctly. A decorator or client can force the login procedure disregarding the IsLoggedIn property (because of advanced/better knowledge). Disadvantage: Can I expect from implemeters that they must not check the IsLoggedIn property internally?

Variant B

Expose the IsLoggedIn property via interface and check IsLoggedIn before login procedure within implementation. Reason: I can just return in the function and so avoid exceptions by "double login". Disadvantage: A client or decorator (with advanced knowledge) cannot force the implementation to login again, because it always checks the the state itself

Variant C

Don't expose the IsLoggedIn property via interface but check IsLoggedIn before login procedure within implementation. Reason: The client need not care about the state and can trust on the implementation to not "double login". Disadvantage: A decorator cannot decorate the IsLoggedIn property or force the implementation to login again (because the decorator might have some knowledge that the login was rejected / cancelled some time later in background)

What is the practical problem behind that question?

In some of our systems the login is discarded if a hardware reset is done. I wanted to handle this via a decorator (that is able to detect these resets) to comply with the SRP. But for this to work the decorator must be able to force the login, even if the internal state of the implementation says it is already logged in. So I would go for variant A but I am not sure if I can expect to not check the state internally from developers.



Related Questions


State Design Pattern

Updated July 05, 2016 08:02 AM