Paolo
Paolo

Reputation: 19

OOP design suggestion for inheritance

abstract class db{
    // return an handle to db
}

class type extends db{
    // code that uses db
}

abstract class limits extends db{
    // code that DOES NOT use db
}

class otherclass extends limits{
    // code that use db and limits
}

As you can see, I need db in all classes except limits. But limits is parent for classes that use db. I think this is not the correct design pattern, since I extend db in limits just to have db available for children. Or is it? Thanks.

Upvotes: 1

Views: 74

Answers (2)

doctorlove
doctorlove

Reputation: 19232

You said " I need db in all classes except limits." which indicates you should compose (or contain) a db not inherit from it. See md4's answer.

You need to think about why you might have abstract classes - this is usually because you want to "program to an interface" to coin a phrase.

Perhaps db and limits are two different things - think single responsibility...

abstract class db {
    // returns db handle
}

abstract class limits {
    // does something
}

class otherclass : extends limits,  db {
}

...edit start...
Clearly for some specific OO languages like Java and C# limits and db would need to be interfaces rather than classes. The OP didn't specify a language.
...edit end...

Think about the using code - consider writing a few unit tests to see what it looks like. Think about what must change together and what should be decoupled.

Upvotes: 1

md4
md4

Reputation: 1669

Depending on unstated requirements, you would be better off with composition instead of inheritance, in this case.

class db {
    // returns db handle
}

class type {
    private db; // type can now use db
}

class limits {
    // does something
}

class otherclass {
     private limits;
     private db;      // can use limits and db
}

Upvotes: 5

Related Questions