HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Class with a sometimes unused property

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sometimeswithunusedpropertyclass

Problem

From times to times I stumble over the following situation:

I have got a class with a property that's only used if another property has a particular value, for instance:

public enum enum_ConnectionType
{
    Local,
    Server
}

public class Session
{
    private enum_ConnectionType _connectionType;
    private string _serverName; // It only makes sense if _connectionType == enum_ConnectionType.Server

    public Session(enum_ConnectionType connectionType, string serverName)
    {
        _connectionType = connectionType;
        _serverName = serverName;
    }
}


There's something that does not feel right to me.
What is your common approach on this kind of situations?

EDIT

I think both Jeff and Leonid answers are valid depending on the situation.

Solution

I would do this using an interface and polymorphism to represent this:

public interface ISession
{
    void DoSomething();

    // Add your properties / method definitions
}

public class ServerSession : ISession
{
     private readonly string _serverName;

     public ServerSession(string serverName)
     {
         _serverName = serverName;
     }

     public void DoSomething()
     {
         // Some Code
     }

     // Implement interface contracts
}

public class OtherSession : ISession
{

     public void DoSomething()
     {
         // Some Code
     }

     // Implement interface contracts
}


Then you would use it something like this:

public DoSomethingWithSession(ISession session)
{
     session.DoSomething();
}

foo.DoSomethingWithSession(new ServerSession());


If there is commonality between ISession implementations, you could base class that out, then inherit from that.

Code Snippets

public interface ISession
{
    void DoSomething();

    // Add your properties / method definitions
}

public class ServerSession : ISession
{
     private readonly string _serverName;

     public ServerSession(string serverName)
     {
         _serverName = serverName;
     }

     public void DoSomething()
     {
         // Some Code
     }

     // Implement interface contracts
}

public class OtherSession : ISession
{

     public void DoSomething()
     {
         // Some Code
     }

     // Implement interface contracts
}
public DoSomethingWithSession(ISession session)
{
     session.DoSomething();
}

foo.DoSomethingWithSession(new ServerSession());

Context

StackExchange Code Review Q#20280, answer score: 13

Revisions (0)

No revisions yet.