Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make inherited instance variables clear?

Tags:

c#

oop

I've been working with some abstract classes and something feels off but I'm not sure what to do about it. Here's a simple example to explain my question:

public abstract class Data
{
    protected Boolean _Connected = false;

    public abstract void Connect();
    public abstract void Disconnect();

    public Boolean Connected
    {
        get { return _Connected; }
    }

}

public class SqlServerData : Data
{
    public override void Connect()
    {
        // code to connect to sql server
        _Connected = true;
    }
    public override void Disconnect()
    {
        if (_Connected)
        {
            // code to disconnect from sql server
            _Connected = false;
        }
    }    
}

I have a couple problems with the design.

  1. Nothing in this design forces a new implementation of Data to do anything with the _connected instance variable. If other classes using the Data class rely on the Connected property, it may not be accurate.

  2. It can be confusing to someone new to this code. This sample is pretty simple but if there are more instance variables in the abstract class and other instance variables in the SqlServerData class it will be more difficult to know where the variables are defined.

So my question is, should this be refactored and if so, how?

like image 679
allen.mn Avatar asked Jan 18 '23 18:01

allen.mn


1 Answers

Implement the state machine (connected or not connected, and the transitions between these states) in the base class, so the derived class doesn't have to worry about this part. Provide protected methods for the actual functionality, so the derived class can easily fill in the "holes":

public abstract class Data
{
    private bool connected;

    public bool Connected
    {
        get { return connected; }
    }

    public void Connect()
    {
        OnConnect();
        connected = true;
    }

    public void Disconnect()
    {
        if (connected)
        {
            OnDisconnect();
            connected = false;
        }
    }

    protected virtual void OnConnect() { }

    protected virtual void OnDisconnect() { }
}

and

public class SqlServerData : Data
{
    protected override void OnConnect()
    {
        // code to connect to sql server
    }

    protected override void OnDisconnect()
    {
        // code to disconnect from sql server
    }    
}
like image 137
dtb Avatar answered Jan 29 '23 07:01

dtb