user118190
user118190

Reputation: 2179

Generic Method - Seeking Design Advice

I have a util class (C#) where I have a static method that takes a certain type of object and brings up a web service to get further data. I would like to support other object types and to not replicate the code, i.e. add multiple similar methods, I am thinking the Generic route would be best.

For example, let's say I have:

public static void GetData(Building building)
{
    var webClient = new WebClient();
    var wrapper = new WrapperClass(building);

    if (building.Distance.HasValue)
    {
        structure = new Structure((decimal)building.Length.Value, (decimal)building.Height.Value);
    }

    ... // and so on ...

instead of creating another method(s) like so:

public static void GetDataForBridge(Bridge bridge)
{
    var webClient = new WebClient();
    var wrapper = new WrapperClass(bridge);

    if (bridge.Distance.HasValue)
    {
        structure = new Structure((decimal)bridge.Length.Value, (decimal)bridge.Height.Value);
    }

    // ...

I am not sure how to do this using Generics. Can anyone please give me some tips or advice?

Upvotes: 0

Views: 90

Answers (3)

Dylan Smith
Dylan Smith

Reputation: 22235

Sounds like you should probably be using a shared interface rather than generics in this case. Define an Interface which contains things like the Distance property and Length, Height, etc; and have your bridge and Building implement it, then define a GetData() method that takes in an instance of the shared interface.

public static viod GetData(IHasDimensions thing)
{
    var webClient = new WebClient();
    var wrapper = new WrapperClass(thing);

    if (thing.Distance.HasValue)
    {
        structure = new Structure((decimal)thing.Length.Value, (decimal)thing.Height.Value);
    }
    ...
}

Upvotes: 2

phoog
phoog

Reputation: 43046

In this case, Bridge and Building would have to implement the same interface, say, IObjectWithHeightAndWidth. You'd then specify this interface as a constraint on the type parameter of your generic method.

(Or, instead of a common interface, the classes could share a common base class.)

As other posters have pointed out, though, you might not need generics at all. You only would need generics if you subsequently need to have a strongly-typed reference to the object as a Bridge or Building -- for example if you need to call another generic method in the method we're discussing.

Upvotes: 1

Vlad
Vlad

Reputation: 35584

In your case, why not just replace Building in function declaration with a simpler IHaveDistanceLengthAndHeight interface? This way you don't need generics at all.

interface IHaveDistanceLengthAndHeight
{
    DistanceType Distance { get; }
    DistanceType Height   { get; }
    DistanceType Length   { get; }
}

class Building : IHaveDistanceLengthAndHeight
{
    ...

Upvotes: 3

Related Questions