今天继续回到数据结构和OOP
为了引出inheritance的概念让我们先设置一个故事背景:
Imagine you're a software engineer at a university, and
you've been working for some time on a Person class.
场景:
But your software design team comes back to you and
says, we really can't just have one class anymore.
This needs to start behaving differently for students or faculty.
Let me propose another potential solution.
Let's just take my Person class and copy paste it into two files and
we name one to be Student and the other to be Faculty.
And then within the Student class I'm gonna change all the code
to match the behavior of a student, and within the Faculty I'm gonna change all
the code to match the behavior of a faculty member.
Problem 1:
What's gonna happen is your design team's gonna come back to you and they're gonna
say at some point, you know having a single string name isn't sufficient.
We really need you to break this out as first name and last name.
And this isn't a major change, so you go into your code,
you start changing all the instances of name to now work with first name and
last name and you fix all of the Student class.
And then you're gonna realize, wait, I had name in the Faculty class, too.
And you can't just copy-paste the code that you just changed in Student into
Faculty.
You're gonna have to rewrite all the Faculty,
do all the changes you just made in Student to the Faculty code.
It's gonna be tedious and it's unnecessary.
But more important, what if you make a mistake?
What if you miss a change in Faculty that you made in Student?
This is gonna be really hard to keep consistent.
Problem 2:
The other problem with this
is that there is probably some code that has an array of persons right now.
What's gonna happen if I now break this into two classes, only students and
only faculty.
Well I can't keep that single array of persons anymore.
I'm gonna have to keep two arrays, one for students and one for faculty.
I know there's no clean way to keep a single data structure for all persons.
And you may say, well why is that important?
Well, what if I just wanted to sort by the time that the person came on campus?
Play video starting at :5:1 and follow transcript5:01
That would be really hard to do.
I could sort the students potentially, I could sort the faculty, but
how do I merge those?
It's gonna get ugly pretty quick.
So, neither of these answers are things that we're happy with.
What do we want then?
Essentially, we figured out the goals by looking at these two examples.
The goals here are 1, to keep all of our common code in one class.
It'd be great if we could do that.
We also would like it, so if we have different behaviors,
I split that different behavior into different classes.
And lastly, I wanna be able to keep all these objects
in one single data structure.