Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use inheritance?

Me and my friend had a little debate. I had to implement a "browser process watcher" class which invokes an event whenever the browser that is being watched (let's say Internet explorer) is running.

We created a "Process watcher" class, and here starts the debate:

He said that the constructor should only accept strings (like "iexplore.exe"), and i said we should inherit "Process watcher" to create a "browser watcher" which accepts the currently used browser enum, which the constructor will "translate" it to "iexplore". he said we should use a util function which will act as the translator.

I know both ways are valid and good, but i wonder whats the pros and cons of each, and what is suitable in our case.

like image 570
Orentet Avatar asked Nov 28 '22 05:11

Orentet


1 Answers

Lately I've been taking the approach of "Keep it simple now, and refactor later if you need to extend it".

What you're doing right now seems pretty simple. You only really have one case that you're trying to handle. So I'd say take the simpler approach for now. In the end, if you never have to make another kind of watcher then you'll avoid the extra complexity. However, code it in a way that will make it easier to refactor later if you need to.

In the future, if you find you need another type of watcher, spend the effort then to refactor it into an inheritance (or composition, or whatever other pattern you want to follow). If your initial code is done right the refactoring should be fairly easy, so you're not really adding much extra work.

I've found this approach works fairly well for me. In the cases where I really didn't need inheritance the code stays simple. But when I really do need it I can add it in without any real problems.

like image 194
Herms Avatar answered Dec 26 '22 15:12

Herms