views:

140

answers:

3

I hope this isn't too subjective. I can't decide between these two design opportunities.

I have a Front Controller pattern. When the user surfs to a specific URL, my framework loads a specified View Controller for this URL. The View Controller then calculates some things and loads a View Template, to show the results.

Now imagine you wanted to make a site like SO. Every page looks pretty similar: Same header, same menu, same footer. Just the content area is different. You surf to the "Ask Question" page, and want the "Ask new Question" form to come up inside the layout.

So we make a RootViewController with a RootView template that sets up the layout and has a placeholder for the content. And a AskQuestionViewController with an AskQuestionView template.

Our Front Controller loads the AskQuestionViewController class. The system calls the loadView() method, and then the viewDidLoad() method.

Option A: AskQuestionViewController inherits from RootViewController.

method gets called by the system, and calls parent::loadView() first. So RootViewController gets the chance to create its RootView template. Next, loadView() loads the AskQuestionView template, and assigns it to the content placeholder of the RootView template.

Option B: AskQuestionViewController does not inherit from RootViewController.

The loadView() method of AskQuestionViewController loads RootViewController first. Then it loads its own AskQuestionView template, and assigns it to the content placeholder of the RootView template.

The only differences between these View Controllers are, that they load different View templates, and that they have different custom methods to perform certain tasks. i.e. the RootViewController is able to compose the Navigation Menu and highlight what's currently visited. There's nothing else in RootViewController that could be useful for AskQuestionViewController.

Which Option would be better design?

+5  A: 

The prefer composition over inheritance principle suggests B is preferable.

Alex Martelli
Great article. Thanks!
openfrog
@openfrog, you're most welcome!
Alex Martelli
+1  A: 

This is difficult to answer in a general, platform independant manner, but i'd go with B.

Paul Creasey
+2  A: 

The AskQuestionViewController is not really a specialisation of the RootViewController. So, I'd definitely say B. It may make sense for the two controllers to both inherit from a common parent class.

mopoke
indeed there's an abstract ViewController parent class for every View Controller :-)
openfrog