Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

oop - "Is a" vs "Has a" : which one is better?

Portfolio A → Fund 1

Portfolio A → Fund 2

Portfolio A → Fund 3

I couldn't frame my sentence without not using is/has. But between 1 & 2,

1) has a:

class PortfolioA
{
    List<Fund> obj;
}

2) is a:

class PortfolioA : List<Fund>
{

}

which one do you think is better from the point of extensibility, usability? I can still access my funds either way, albeit with a small syntactical change.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I vote with the other folks who say HAS-A is better in this case. You ask in a comment:

when I say that a Portfolio is just a collection of funds, with a few attributes of its own like TotalPortfolio etc, does that fundamentally not become an "is-a"?

I don't think so. If you say Portfolio IS-A List<Fund>, what about other properties of the Portfolio? Of course you can add properties to this class, but is it accurate to model those properties as properties of the List? Because that's basically what you're doing.

Also what if a Portfolio is required to support more than one List<Fund>? For instance, you might have one List that shows the current balance of investments, but another List that shows how new contributions are invested. And what about when funds are discontinued, and a new set of funds is used to succeed them? Historical information is useful to track, as well as the current fund allocation.

The point is that all these properties are not correctly properties of a List, though they may be properties of the Portfolio.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...