Nishant
Nishant

Reputation: 437

Inheritance design concept

I have 2 unrelated classes

public class ManagedType{
    private string id;
    private string name;
    private string description;
    private string version;
    private string Properties;
   private List<string> baseTypesl
}

public class OtherClass{
    private string id;
    private string name;
    private string description;
    private string target;
    private string sources;
   private List<string> relationships;
}

So is it advised if I abstract out id, name, description into a new base class and let it extends this.

My view is that since they are unrelated we shouldn't. Also we should never extends a class only for properties(unless they are related), but only for common behaviors(which is none here). Please let me know your view on the same.

Upvotes: 0

Views: 49

Answers (2)

Barani
Barani

Reputation: 58

Your understanding is correct. Unless they are not falling under 'is-a' relationship, there is no point in bringing them under one super-class.

But, this 'is-a'relationship comes only if it is seen from functional perspective. If you are building a service-class, like Serializable, IEnumerable, etc, you may think of bringing one Interface with 3 properties (I could see ID, name and Description) are common. This is applicable only if you see this from technical service perspective. But, if you are looking from functional perspective, you shouldn't bring abstract class.

For example,

public interface Iloggable 
{   
    public string id {get; set;}   public
    string name {get; set;}   
    public string description {get; set;} 
}

public class ManagedType: Iloggable 
{   
    private string _id, _name,_description;   
    public string id   
    { 
        get 
            {return _id;} 
        set {_id = value; } 
    }   
    ..... 
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 271050

You might have heard this before: "Inheritance represents an 'is a kind of' relationship".

To decide whether to use inheritance or not, simply ask yourself this:

Is ManagedType and OtherClass the same kind of thing?

If your answer is "yes", create a common superclass.

It is as simple as that. You also have to consider whether using inheritance here will make your code "better" in any way. I can't think of any situation like this right now, but if you see that whether inheritance exists or not does not affect your other pieces of code at all, inheritance is probably unnecessary. If you used inheritance and thought "Oh, now with inheritance, I can simplify my code like this!", then it's probably good to have it there.

Also we should never extends a class only for properties(unless they are related), but only for common behaviors(which is none here).

I have never heard anything like this before. I think it depends highly on the specific situation you're in.

Upvotes: 2

Related Questions