Design Patterns Explained

Alan Shalloway, James Trott

Mentioned 10

This book introduces the programmer to patterns: how to understand them, how to use them, and then how to implement them into their programs. This book focuses on teaching design patterns instead of giving more specialized patterns to the relatively few.

More on

Mentioned in questions and answers.

If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this. For example:

inquestion:this "Code Complete"

Applying UML and Patterns by Craig Larman.

The title of the book is slightly misleading; it does deal with UML and patterns, but it covers so much more. The subtitle of the book tells you a bit more: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

Masters of doom. As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!

Beginning C# 3.0: An Introduction to Object Oriented Programming

This is the book for those who want to understand the whys and hows of OOP using C# 3.0. You don't want to miss it.

alt text

Mastery: The Keys to Success and Long-Term Fulfillment, by George Leonard

It's about about what mindsets are required to reach mastery in any skill, and why. It's just awesome, and an easy read too.

Pro Spring is a superb introduction to the world of Inversion of Control and Dependency Injection. If you're not aware of these practices and their implications - the balance of topics and technical detail in Pro Spring is excellent. It builds a great case and consequent personal foundation.

Another book I'd suggest would be Robert Martin's Agile Software Development (ASD). Code smells, agile techniques, test driven dev, principles ... a well-written balance of many different programming facets.

More traditional classics would include the infamous GoF Design Patterns, Bertrand Meyer's Object Oriented Software Construction, Booch's Object Oriented Analysis and Design, Scott Meyer's "Effective C++'" series and a lesser known book I enjoyed by Gunderloy, Coder to Developer.

And while books are nice ... don't forget radio!

... let me add one more thing. If you haven't already discovered safari - take a look. It is more addictive than stack overflow :-) I've found that with my google type habits - I need the more expensive subscription so I can look at any book at any time - but I'd recommend the trial to anyone even remotely interested.

(ah yes, a little obj-C today, cocoa tomorrow, patterns? soa? what was that example in that cookbook? What did Steve say in the second edition? Should I buy this book? ... a subscription like this is great if you'd like some continuity and context to what you're googling ...)

Database System Concepts is one of the best books you can read on understanding good database design principles.

alt text

Algorithms in C++ was invaluable to me in learning Big O notation and the ins and outs of the various sort algorithms. This was published before Sedgewick decided he could make more money by dividing it into 5 different books.

C++ FAQs is an amazing book that really shows you what you should and shouldn't be doing in C++. The backward compatibility of C++ leaves a lot of landmines about and this book helps one carefully avoid them while at the same time being a good introduction into OO design and intent.

Here are two I haven't seen mentioned:
I wish I had read "Ruminations on C++" by Koenig and Moo much sooner. That was the book that made OO concepts really click for me.
And I recommend Michael Abrash's "Zen of Code Optimization" for anyone else planning on starting a programming career in the mid 90s.

Perfect Software: And Other Illusions about Testing


Perfect Software: And Other Illusions about Testing by Gerald M. Weinberg

ISBN-10: 0932633692

ISBN-13: 978-0932633699

Rapid Development by McConnell

The most influential programming book for me was Enough Rope to Shoot Yourself in the Foot by Allen Holub.

Cover of the book

O, well, how long ago it was.

I have a few good books that strongly influenced me that I've not seen on this list so far:

The Psychology of Everyday Things by Donald Norman. The general principles of design for other people. This may seem to be mostly good for UI but if you think about it, it has applications almost anywhere there is an interface that someone besides the original developer has to work with; e. g. an API and designing the interface in such a way that other developers form the correct mental model and get appropriate feedback from the API itself.

The Art of Software Testing by Glen Myers. A good, general introduction to testing software; good for programmers to read to help them think like a tester i. e. think of what may go wrong and prepare for it.

By the way, I realize the question was the "Single Most Influential Book" but the discussion seems to have changed to listing good books for developers to read so I hope I can be forgiven for listing two good books rather than just one.

alt text

C++ How to Program It is good for beginner.This is excellent book that full complete with 1500 pages.

Effective C++ and More Effective C++ by Scott Myers.

Inside the C++ object model by Stanley Lippman

I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time

Not a programming book, but still a very important book every programmer should read:

Orbiting the Giant Hairball by Gordon MacKenzie

The Pragmatic programmer was pretty good. However one that really made an impact when I was starting out was :

Windows 95 System Programming Secrets"

I know - it sounds and looks a bit cheesy on the outside and has probably dated a bit - but this was an awesome explanation of the internals of Win95 based on the Authors (Matt Pietrek) investigations using his own own tools - the code for which came with the book. Bear in mind this was before the whole open source thing and Microsoft was still pretty cagey about releasing documentation of internals - let alone source. There was some quote in there like "If you are working through some problem and hit some sticking point then you need to stop and really look deeply into that piece and really understand how it works". I've found this to be pretty good advice - particularly these days when you often have the source for a library and can go take a look. Its also inspired me to enjoy diving into the internals of how systems work, something that has proven invaluable over the course of my career.

Oh and I'd also throw in effective .net - great internals explanation of .Net from Don Box.

I recently read Dreaming in Code and found it to be an interesting read. Perhaps more so since the day I started reading it Chandler 1.0 was released. Reading about the growing pains and mistakes of a project team of talented people trying to "change the world" gives you a lot to learn from. Also Scott brings up a lot of programmer lore and wisdom in between that's just an entertaining read.

Beautiful Code had one or two things that made me think differently, particularly the chapter on top down operator precedence.


@Juan: I know Juan, I know - but there are some things that can only be learned by actually getting down to the task at hand. Speaking in abstract ideals all day simply makes you into an academic. It's in the application of the abstract that we truly grok the reason for their existence. :P

@Keith: Great mention of "The Inmates are Running the Asylum" by Alan Cooper - an eye opener for certain, any developer that has worked with me since I read that book has heard me mention the ideas it espouses. +1

I found the The Algorithm Design Manual to be a very beneficial read. I also highly recommend Programming Pearls.

This one isnt really a book for the beginning programmer, but if you're looking for SOA design books, then SOA in Practice: The Art of Distributed System Design is for you.

For me it was Design Patterns Explained it provided an 'Oh that's how it works' moment for me in regards to design patterns and has been very useful when teaching design patterns to others.

Code Craft by Pete Goodliffe is a good read!

Code Craft

The first book that made a real impact on me was Mastering Turbo Assembler by Tom Swan.

Other books that have had an impact was Just For Fun by Linus Torvalds and David Diamond and of course The Pragmatic Programmer by Andrew Hunt and David Thomas.

In addition to other people's suggestions, I'd recommend either acquiring a copy of SICP, or reading it online. It's one of the few books that I've read that I feel greatly increased my skill in designing software, particularly in creating good abstraction layers.

A book that is not directly related to programming, but is also a good read for programmers (IMO) is Concrete Mathematics. Most, if not all of the topics in it are useful for programmers to know about, and it does a better job of explaining things than any other math book I've read to date.

For me "Memory as a programming concept in C and C++" really opened my eyes to how memory management really works. If you're a C or C++ developer I consider it a must read. You will defiantly learn something or remember things you might have forgotten along the way.

Agile Software Development with Scrum by Ken Schwaber and Mike Beedle.

I used this book as the starting point to understanding Agile development.

Systemantics: How Systems Work and Especially How They Fail. Get it used cheap. But you might not get the humor until you've worked on a few failed projects.

The beauty of the book is the copyright year.

Probably the most profound takeaway "law" presented in the book:

The Fundamental Failure-Mode Theorem (F.F.T.): Complex systems usually operate in failure mode.

The idea being that there are failing parts in any given piece of software that are masked by failures in other parts or by validations in other parts. See a real-world example at the Therac-25 radiation machine, whose software flaws were masked by hardware failsafes. When the hardware failsafes were removed, the software race condition that had gone undetected all those years resulted in the machine killing 3 people.

It seems most people have already touched on the some very good books. One which really helped me out was Effective C#: 50 Ways to Improve your C#. I'd be remiss if I didn't mention The Tao of Pooh. Philosophy books can be good for the soul, and the code.

Discrete Mathematics For Computer Scientists

Discrete Mathematics For Computer Scientists by J.K. Truss.

While this doesn't teach you programming, it teaches you fundamental mathematics that every programmer should know. You may remember this stuff from university, but really, doing predicate logic will improve you programming skills, you need to learn Set Theory if you want to program using collections.

There really is a lot of interesting information in here that can get you thinking about problems in different ways. It's handy to have, just to pick up once in a while to learn something new.

I saw a review of Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools on a blog talking also about XI-Factory, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on..

Solid Code Optimizing the Software Development Life Cycle

Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.

Managing Gigabytes is an instant classic for thinking about the heavy lifting of information.

My vote is "How to Think Like a Computer Scientist: Learning With Python" It's available both as a book and as a free e-book.

It really helped me to understand the basics of not just Python but programming in general. Although it uses Python to demonstrate concepts, they apply to most, if not all, programming languages. Also: IT'S FREE!

Object-Oriented Programming in Turbo C++. Not super popular, but it was the one that got me started, and was the first book that really helped me grok what an object was. Read this one waaaay back in high school. It sort of brings a tear to my eye...

My high school math teacher lent me a copy of Are Your Lights Figure Problem that I have re-read many times. It has been invaluable, as a developer, and in life generally.

I'm reading now Agile Software Development, Principles, Patterns and Practices. For those interested in XP and Object-Oriented Design, this is a classic reading.

alt text

Kernighan & Plauger's Elements of Programming Style. It illustrates the difference between gimmicky-clever and elegant-clever.

to get advanced in prolog i like these two books:

The Art of Prolog

The Craft of Prolog

really opens the mind for logic programming and recursion schemes.

Here's an excellent book that is not as widely applauded, but is full of deep insight: Agile Software Development: The Cooperative Game, by Alistair Cockburn.

What's so special about it? Well, clearly everyone has heard the term "Agile", and it seems most are believers these days. Whether you believe or not, though, there are some deep principles behind why the Agile movement exists. This book uncovers and articulates these principles in a precise, scientific way. Some of the principles are (btw, these are my words, not Alistair's):

  1. The hardest thing about team software development is getting everyone's brains to have the same understanding. We are building huge, elaborate, complex systems which are invisible in the tangible world. The better you are at getting more peoples' brains to share deeper understanding, the more effective your team will be at software development. This is the underlying reason that pair programming makes sense. Most people dismiss it (and I did too initially), but with this principle in mind I highly recommend that you give it another shot. You wind up with TWO people who deeply understand the subsystem you just built ... there aren't many other ways to get such a deep information transfer so quickly. It is like a Vulcan mind meld.
  2. You don't always need words to communicate deep understanding quickly. And a corollary: too many words, and you exceed the listener/reader's capacity, meaning the understanding transfer you're attempting does not happen. Consider that children learn how to speak language by being "immersed" and "absorbing". Not just language either ... he gives the example of some kids playing with trains on the floor. Along comes another kid who has never even SEEN a train before ... but by watching the other kids, he picks up the gist of the game and plays right along. This happens all the time between humans. This along with the corollary about too many words helps you see how misguided it was in the old "waterfall" days to try to write 700 page detailed requirements specifications.

There is so much more in there too. I'll shut up now, but I HIGHLY recommend this book!

alt text

The Back of the Napkin, by Dan Roam.

The Back of the Napkin

A great book about visual thinking techniques. There is also an expanded edition now. I can't speak to that version, as I do not own it; yet.

Agile Software Development by Alistair Cockburn

Do users ever touch your code? If you're not doing solely back-end work, I recommend About Face: The Essentials of User Interface Design — now in its third edition (linked). I used to think my users were stupid because they didn't "get" my interfaces. I was, of course, wrong. About Face turned me around.

"Writing Solid Code: Microsoft's Techniques for Developing Bug-Free C Programs (Microsoft Programming Series)" by Steve MacGuire.

Interesting what a large proportion the books mentioned here are C/C++ books.

While not strictly a software development book, I would highly recommend that Don't Make me Think! be considered in this list.

As so many people have listed Head First Design Patterns, which I agree is a very good book, I would like to see if so many people aware of a title called Design Patterns Explained: A New Perspective on Object-Oriented Design.

This title deals with design patterns excellently. The first half of the book is very accessible and the remaining chapters require only a firm grasp of the content already covered The reason I feel the second half of the book is less accessible is that it covers patterns that I, as a young developer admittedly lacking in experience, have not used much.

This title also introduces the concept behind design patterns, covering Christopher Alexander's initial work in architecture to the GoF first implementing documenting patterns in SmallTalk.

I think that anyone who enjoyed Head First Design Patterns but still finds the GoF very dry, should look into Design Patterns Explained as a much more readable (although not quite as comprehensive) alternative.

Even though i've never programmed a game this book helped me understand a lot of things in a fun way.

How influential a book is often depends on the reader and where they were in their career when they read the book. I have to give a shout-out to Head First Design Patterns. Great book and the very creative way it's written should be used as an example for other tech book writers. I.e. it's written in order to facilitate learning and internalizing the concepts.

Head First Design Patterns

97 Things Every Programmer Should Know

alt text

This book pools together the collective experiences of some of the world's best programmers. It is a must read.

Extreme Programming Explained: Embrace Change by Kent Beck. While I don't advocate a hardcore XP-or-the-highway take on software development, I wish I had been introduced to the principles in this book much earlier in my career. Unit testing, refactoring, simplicity, continuous integration, cost/time/quality/scope - these changed the way I looked at development. Before Agile, it was all about the debugger and fear of change requests. After Agile, those demons did not loom as large.

One of my personal favorites is Hacker's Delight, because it was as much fun to read as it was educational.

I hope the second edition will be released soon!

You.Next(): Move Your Software Development Career to the Leadership Track ~ Michael C. Finley (Author), Honza Fedák (Author) link text

I've been arounda while, so most books that I have found influential don't necessarily apply today. I do believe it is universally important to understand the platform that you are developing for (both hardware and OS). I also think it's important to learn from other peoples mistakes. So two books I would recommend are:

Computing Calamities and In Search of Stupidity: Over Twenty Years of High Tech Marketing Disasters

Working Effectively with Legacy Code is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.

I am asking a quite simple question, but I am bit confused in this.

Suppose I have a class Parent:

public class Parent {

    int name;

And have another class

public class Child extends Parent{

    int salary;

And finally my class

public class Main {

    public static void main(String[] args)
        Parent parent = new Child(); "abcd";

If I make a child object like

Child child = new Child():

Then child object can access both name and salary variables.

My question is:

Parent parent = new Child();

gives the access of only name variable of Parent class. So what is the exact use of this line??

 Parent parent = new Child();

And also when it is using dynamic polymorphism then why the variable of child class is not accessible after doing this

Parent parent = new Child();

It allows you to access all subclasses through a common parent interface. This is beneficial for running common operations available on all subclasses. A better example is needed:

public class Shape
  private int x, y;
  public void draw();

public class Rectangle extends Shape
  public void draw();
  public void doRectangleAction();

Now if you have:

List<Shape> myShapes = new ArrayList<Shape>();

You can reference every item in the list as a Shape, you don't have to worry if it is a Rectangle or some other type like let's say Circle. You can treat them all the same; you can draw all of them. You can't call doRectangleAction because you don't know if the Shape is really a rectangle.

This is a trade of you make between treating objects in a generic fashion and treating the specifically.

Really I think you need to read more about OOP. A good book should help:

In my point of view, design ability is harder to get than development/coding skills.

When confronting a requirement , how to design the function modules, how to construct the program architecture properly?

By the way, are there some books related?

Trial and error is the best way to see how your own designs can improve. Always look for a better solution. What mistakes did you make? What part was less flexible than it needed to be? What caused you to have to hack around a design decision you made?

Think about the implications of the design rather than purely it's flexibility and elegance. What trade offs have you made in order to make this reusable? Are you following the seperation of concerns and the single responsibility principle? Open closed principle? Do you know what these are and their implications?

Also study the work of experts in the form of design patterns.

Read Design Patterns Explained by Shalloway, Read Head first design patterns

However remember that these aren't magic bullet solutions and take everything with a pinch of salt. Use your own creativity and STAY PRAGMATIC.

I think it all comes down to experience. Being able to read a set of requirements and translate them into a good, clean, maintainable software design is one of the hardest thing in programming (imho) and you do not learn that just by reading a book. It's about trying, making mistakes, learning from those mistakes, and learning what designs have worked for you in the past or haven't.

For me, it often helps to really take my time and create a good design in UML, for example a class diagram. It often helps me identify and components that I can reuse throughout the software application, where I can use a certain design pattern, etcetera.

A few books I can recommend: Software Architecture in Practice, which is a very good book about software architecture, and Design Patterns by the Gang of Four, which is a great reference for any design patterns you might use.

I would like to get book(s) that will really give me a complete view of modern ASP.NET development using C#, TDD, ASP.NET MVC, DDD and Design Patterns such as the Repository pattern. I'm very competent with C# and ASP.NET MVC, but want to fill in the gaps.

If you've had a good experience with a book or two that covers these topics could you please share them?

Try Applying Domain Driven Design and Patterns By Jimmy Nillson. It covers DDD and it's patterns in .NET

Guess the scope of topics you have asked is vast to be covered in a single book

Try this One Agile Principles, Patterns, and Practices in C# By Martin and Martin

Book talks mostly about Design Principles, Design Patters, UML Diagrams, Documentation, Refactoring. It doesn't cover ASP.NET and MVC though. YOu need to refer some other books for those.

I'm currently interested in how to architecture good .NET applications and I'm reading or have currently read some of the following books:

Those two Microsoft books really explain how to design .NET applications with high testability using Inversion Of Control and such.

And to be clear, yes they all use design patterns common in TDD, DDD, Dependency Injection, ans so on...

For your needs I would recommend starting with:

Like the title says; it's basically a book on how to to DDD and TDD in a .NET environment.

Here are a few that I would recommend:

NOTE: This question has been updated to provide more detail and insight than the previously.

UPDATE: I just want to say thank you to everyone who responded. I'm still pretty much in the dark on what design pattern would work best for the Widget. Perhaps one of the Factory or Builder patterns?

I am just getting started on a new project and need to use MVC, OO and design patterns.

Here's the idea: Imagine a page that displays a set of widgets. These widgets are (usually) charts that are based off of data contained in several separate tables in the database. I use a running example of page that reports on a student's performance.

High Level Requirements

  • a page that displays a set of (HTML only) widgets.
  • widget's data will be based off a database query.
  • the page can be used to view separate datasets containing similarly laid out data. For example, a single page will display widgets that report on various aspects of a single student's performance.
  • want to see another student's performance, pull up another page. Displaying different widgets for different students is not needed (though it may be nice to have later).
  • There may be many students, but data contained in the database is similarly laid out for all students.
  • the way a widget is displayed may be changed easily (say changing a widget from displaying as a pie chart to display as a bar chart).
  • widgets should be able to be created quickly.

Low Level Requirements

  • Currently data does not change so widgets will not need to automatically update themselves.
  • Widgets may represent a ratio of two things (eg. a ratio of failed tests to successful tests as a pie chart), a series of points, or sometimes a single numeric value.
  • Development of new widgets should be a breeze, existing code need not be modified.
  • Framework to be used: Zend Framework, based on MVC.

There are (minimally) three things to define a widget: the dataset to report on (in the example above, the student ID), the query that describes the metric being reported, and a render mode (barchart, timeseries etc).

Here is a pass at breaking down the responsibilities of each layer of the MVC:

View: Zend views are HTML templates with PHP injected. They will contain one of several types of widgets. Widgets are of various forms including: static JPEG images (loaded from a remote site ie: <img src=""/>, JSON based javascript widgets, or charts of various kinds (piechart, bar chart etc.)

Controller: Creates the widgets, assigns them to the view afterwards. The set of widgets that is to be displayed on a page needs to be maintained somewhere. Since I can't think of a good way to do this in the view, I'll add this to the controllers responsibilities for now. If there's a better place for this please shout. The controller will also have to handle any other input parameters and passing them to the widget. For example, the data_set id which may be passed at the url line as http:/.../report/?student_id=42

Model: The model, in the Zend Framework, is responsible for pulling the data and as such will most likely contain a class for each widget for accessing the database.

Some points:

  1. The model here, represents the data for a particular widget. So necessarily, it will need to know what the query is going to be, in order to pull together the tables necessary to fetch that data.

  2. There's an additional processing step that will most likely be necessary before the widget can present the data. This is dependant upon which renderer will be used. Sometimes it may require forming a url out of the data returned. Other times, a JSON array. Other times perhaps creating some markup. This can go either in the model or the controller or the view. Unless anyone can think of a good reason to move it to the controller or view, it is probably best to let this live in the model and keep the view and controller thin.

  3. Likewise, a widget will be made up of 3 things, its parameters, its data, and its renderer.

    One big part of the question is: What's a good way to represent the widget in an Object Oriented design? I already asked this once, couldn't get an answer. Is there a design pattern that can be applied to the Widgets that makes the most sense for this project?

    Here's a first pass at a rather simple class for the Widget:

    class Widget{ 
      //method called by the view 
      render() {//output the markup based on the widget Type and interleaved the processed data} 
      //methods called by the controller: 
      public function __construct() {//recieve arguments for widget type (query and renderer), call create()}  
      public function create() {//tell the widget to build the query, execute it, and filter the data} 
      public function process_data() {//transform into JSON, an html entity etc} 
      //methods called by the model: 
      public function build_query() {...}; 
      public function execute_query() {...}; 
      public function filter_data() {...}; 

    Looking at it, I can already see some problems.

  4. For example, it is straightforward to pass the widget that was created in the controller to the View to render.

    But when it comes to implementing the model it seems not so straight forward. Table Gateway Pattern is simpler to implement than ORM. But since table gateway pattern has one class for each model/table it doesn't seem to fit the bill. I could create a model for a particular table, and then within that, instantiate any other models needed. But that doesn't seem so to fit the Table Gateway Pattern, but rather ORM pattern. Can Table Gateway Pattern be implemented with multiple tables? What alternatives are there? Does it make sense that the controller creates the widget and the widget creates the Model?

  5. Another issue that arises is that this design does not enable ease of widget creation. ie. Say I wanted to create a PiechartWidget, how much code can be reused? Would it not make more sense to use some OO ideas such as an interface or abstract classes/methods and inheritance?

    Let's say I abstract the Widget class so only the shared methods are defined concretely, and the rest are declared as abstract methods. Revising the Widget class to make it abstract (second pass):

    abstract class Widget{
      private $_type;
      private $_renderer;
      //methods called by the controller:
      //receive arguments for widget type (query and renderer), 
      protected function __construct($type, $renderer) {
        $this->_type = $type;
        $this->_render = $renderer;
      //tell the widget to build the query, execute it, and filter the data
      private function create() {
      //methods called by the model:
      abstract protected function build_query();
      protected function execute_query() {
        //common method
      abstract protected function filter_data();
      //method called by controller to tranform data for view
      //transform into JSON, an html entity etc
      abstract protected function process_data();
      //method called by the view
      //output the markup based on the widget Type and interleave the processed data
      abstract protected function render(); 

    Is this a good design? How could it be improved?

  6. I assume writing a new widget will require at least some new code to build the query, and maybe filter the data, but it should be able to use preexisting code for almost all of the rest of its functionality, including the renderers that already exist.

I am hoping anyone could provide at least some feedback on this design. Validate it? Tear it apart. Call me an idiot. That's fine too. I could use any forward traction.

A few specific questions:

Q1. What's the best way to implement the renderers, as part of the Widget class or as a separate class? 1a. If separate, how would it interact with the widget class(es)?

Q2. How could I improve this design to simplify creation of new kinds of widgets?

Q3. And lastly, I feel like I am missing something here with regards to data encapsulation. How does data encapsulation relate to the requirements and play out in this scenario?

The purpose behind all of these ideas -- MVC, patterns, etc. -- is essentially the same: every class should do one thing, and every distinct responsibility in your application should be separated into distinct layers. Your views (page and widgets) should be thin and make few if any decisions other than to present data gathered from the models. The models should operate on a data layer agnostically, which is to say they should not know whether the source of their data is a specific kind of data source. The controllers should be thin as well, acting basically as a routing layer between the views and models. Controllers take input from the users and perform the relevant actions on the models. The application of this concept varies depending on your target environment -- web, rich client, etc.

The architecture of the model alone is no trivial problem. You have many patterns to choose from and many frameworks, and choosing the right one -- pattern or framework -- will depend entirely on the particulars of your domain, which we have far too few of here to give you more specific advice. Suffice it to say it is recommended you spend some time getting to know a few Object-Relational Mapping frameworks for your particular technology stack (be it Java, .NET, etc.) and the respective patterns they were built on.

Also make yourself familiar with the difference between MVP and MVC -- Martin Fowler's work is essential here.

As for design patterns, the application of most of the standard GOF patterns could easily come into play in some form or another, and it is recommended you spend time in Design Patterns or one of the many introductory texts on the subject. No one here can give specific answers as to how MVC applies to your domain -- that can only be answered by experienced engineers in cooperation with a Product Owner who has the authority to make workflow and UI decisions that will greatly affect such decisions in their particulars.

In short, the very nature of your question suggests you are in need of an experienced OOP architect or senior developer who has done this before. Alternatively give yourself a good deal of time in intensive study before moving forward. The scope of your project encompasses a vast amount of learning that many coders take years to fully grasp. This is not to say your project is doomed -- in fact you may be able to accomplish quite a lot if you choose the right technology stack, framework, etc., and assuming you are reasonably bright and focused on the task at hand. But getting concepts as broad as "MVC" or "OO" right is not something I think can be done on a first try and under time constraints.

EDIT: I just caught your edit re: Zend. Having a framework in place is good, that takes care of a lot of architectural decisions. I'm not familiar with Zend, but I would stick to its defaults. Much more depends here on your ultimate UI delivery -- are you in a RIA environment like Flash or Silverlight, or are you in a strict HTML/JavaScript environment? In either case the controllers should still be thin and operate as routers taking user requests from HTTP gets and posts, and immediately handing off to the models. The views should remain thin as well and make as few decisions as possible. The concept of MVC applied in a web environment has been pretty well established by Rails and the frameworks that followed, and I'm assuming Zend is similar to something like CakePHP in this regard: the application server has a routing system that maps HTTP calls to controller actions that respond with specific views. The request/response cycle is basically this:

  1. User request posted through a URL
  2. Router hands control to a controller class
  3. Controller makes a call to a model with the given params
  4. The model operates on the data, posts back to the controller
  5. The framework maps the finished data into a view, with some kind of code-behind that puts the results of the request in the view's scope.
  6. The framework creates html (or xml or whatever) and posts back to the caller.

I am just posting this question so some of you might be able to point me in the right way. I am slowly warming up to OOP, starting to understand the concept. I want to make a good solid core or foundation to be used as a CMS backend. It will also use MVC. I have been using as the MVC- base.

The thing I cant figure out is the following:

Say, on the projectpage in the backend I have 2 sections: htmltext and projects and I should be able to edit them both. The uri would be something like: //domain/backend/projects (the method would be the index and show the 2 sections)

When i click on projects how should it be handled? //domain/backend/projects/projects/ or //domain/backend/projects/list/

One step further, a project will hold some images or a gallery: //domain/backend/projects/edit/5/gallery/2

My question here is, first: would this be a good way to go and even more important how would this be implemented in OOP

the main projects controller:

class projects {

    function index(){
        // view index

    function edit{
        $project = new Project();
        $projectdata = $project->load(5);

A single project controller

class project {

    function __construct(){
        $this->projectmodel = $this->loadModel('project_model'); // prepare the model to be used

    function load($id){

project model

class project_model extends model { //extends for DB  access and such

    function __construct(){
        // do stuff

    function loadproject($id){
        return $this->db->query("SELECT * FROM projects where id=" . $id . " LIMIT 1");

Now my question. If this project has images, where should I load the image class to handle those? Should I load it in the project_model like $this->images = new Images(); and have a function inside the model

function loadimages($id){

and then images would be something like:

class image extends model { //extends for DB  access and such 

    function __construct(){

    function load($id){
        return $this->db->query("SELECT * FROM project_images where id=" . $id . " LIMIT 1");

It seems controllers and models gets mixed up this way. Yet in a logical way a project is a container that holds projectinfo, which could be text, images and maybe video's. How would I go about to set that up logically as well.

The original question

The first part, about the URLs is something called: Routing or Dispatching. There is quite good article about it in relationship with Symfony 2.x, but the the idea behind it is what matters. Also, you might looks at ways how other frameworks implement it.

As for your original URL examples, galleries will be stored in DB. Won't they? And they will have a unique ID. Which makes this, /backend/projects/edit/5/gallery/2 quite pointless. Instead your URL should look more like:

/backend/gallery/5/edit         // edit gallery with ID 5
/backend/project/3              // view project with ID 3
/backend/galleries/project/4    // list galleries filtered by project with ID 4

The URL should contain only the information you really need.

This also would indicate 3 controllers:

  1. single gallery management
  2. single project management
  3. dealing with lists of galleries

And the example URLs would have pattern similar to this:


Where the /backend part is mandatory, but the controller is optional. If controller is found , then id ( or page, when you deal with lists ) and action is optional. If action is found, additional parameter is optional. This structure would let you deal with majority of your routes, if written as a regular expression.

OOP beyond classes

Before you start in on using or writing some sort of PHP framework, you should learn how to write proper object oriented code. And that does not mean "know how to write a class". It means, that you have to actually understand, what is object oriented programming, what principles it is based on, what common mistakes people make and what are the most prevalent misconceptions. Here are few lecture that might help you with it:

This should give you some overview of the subject .. yeah, its a lot. But is suspect that you will prefer videos over books. Otherwise, some reading materials:

You will notice that a lot of materials are language-agnostic. That's because the theory, for class-based object oriented languages, is the same.


Be careful with extends keyword in your code. It means "is a". It is OK, if class Oak extends Tree, because all oaks are trees. But if you have class User extends Database, someone might get offended. There is actually an OOP principle which talks about it: Liskov substitution principle .. also there is a very short explanation

So, coming upon the subject of Factories, I'm wondering how they are set up.

From where I stand, I can see 3 types of Factories:

All In One

A factory that basically contains all of the classes used in an application. It feels like it is just having a factory for the sake of having a factory, and doesn't really feel structured.

Example (Where ClassA, Class B, and ClassC have nothing in common except being in the same App):

class Factory
 public static function buildClassA()
 public static function buildClassB()
 public static function buildClassC()

Code samples provided are in PHP. However, this question is language-agnostic.

Built-In Factory

The next one is mixing in static functions with the regular functions in order to make special creation patterns (see this question)


class ClassA
 public static function buildClass()
 public function __construct()

Factory On-the-Side

The last one I can think of is having a factory for individual classes, or individual sets of classes. This just seems to variable to be used in an uniform manner.

Example (Where ClassA, B, and C are related, and 1, 2, and 3 are related):

class FactoryAlpha
 public static function buildClassA()
 public static function buildClassB()
 public static function buildClassC()

class FactoryNumeric
 public static function buildClass1()
 public static function buildClass2()
 public static function buildClass3()

My question is: Are all of these bad ideas, are any of them bad ideas? Are there other ways of creating factories? Are any of these actually good ideas? What is a good/best way to create Factories.

There's really just two standard sorts of factories, at least according to GOF and the slew of patterns books that followed: The basic Factory, and the Abstract Factory.

A Factory generally returns a concrete instance that the caller refers to through an interface, like so:

// createWidget() here instantiates a BigWidget or SmallWidget or whatever the context calls for
IWidget widget = WidgetFactory.createWidget(someContextValue);

Using a factory with an interface in this way keeps the caller from being coupled into a specific type of the returned object. Following the venerable Single Responsibility Principle, a factory should do one thing, that is, return a concrete instance of the interface that was called for, and nothing more. A basic factory should only have the job of creating one type of object.

An Abstract Factory, on the other hand, can be thought of as a factory of factories, and might be closer to what you were thinking of as an "all in one" factory. An Abstract Factory is usually configured at start-up to return a group of related factories, for instance factories that might create a particular family of GUIs depending on a given context. This is an example of Dependency Inversion that has largely been replaced by using IOC containers like Spring.

Currently I am working on a bit of code which (I believe) requires quite a few embedded if statements. Is there some standard to how many if statements to embed? Most of my googling has turned up things dealing with excel..don't know why.

If there is a standard, why? Is it for readability or is it to keep code running more smoothly? In my mind, it makes sense that it would be mainly for readability.

An example of my if-structure:

if (!all_fields_are_empty):
    if (id_search() && validId()):
        // do stuff
    else if (name_search):
        if (name_exists):
            if (match < 1):
                // do stuff
            // do stuff
    else if (name_search_type_2):
        if (exists):
            if (match < 1):
                // do stuff
            // do stuff
    // you're stupid

I have heard that there's a limit to 2-3 nested for/while loops, but is there some standard for if-statements?

I don't think there is a limit but i wouldn't recommend embeddeding more the two - it's too hard to read, difficult to debug and hard to unit test. Consider taking a look at a couple great books like Refactoring, Design Patterns, and maybe Clean Code

Is there a good book which I can follow to learn modelling/doing architecture? Good samples?

What would you do if you have to learn modelling from very basics?


I think by learning and understanding UML you will gain the knowledge needed to model anything. So I recommend UML Distilled book by fowler UML Diagrams to master:

  • Use Case
  • Class
  • Sequence
  • Component
  • State
  • Activity

As for architecture GOF is the best book out there Designed Patterns Explained.