Design Patterns

Ralph Johnson, Erich Gamma, John Vlissides, Richard Helm

Mentioned 277

Capturing a wealth of experience about the design of object-oriented software, four top-notch designers present a catalog of simple and succinct solutions to commonly occurring design problems. Previously undocumented, these 23 patterns allow designers to create more flexible, elegant, and ultimately reusable designs without having to rediscover the design solutions themselves. The authors begin by describing what patterns are and how they can help you design object-oriented software. They then go on to systematically name, explain, evaluate, and catalog recurring designs in object-oriented systems. With Design Patterns as your guide, you will learn how these important patterns fit into the software development process, and how you can leverage them to solve your own design problems most efficiently. Each pattern describes the circumstances in which it is applicable, when it can be applied in view of other design constraints, and the consequences and trade-offs of using the pattern within a larger design. All patterns are compiled from real systems and are based on real-world examples. Each pattern also includes code that demonstrates how it may be implemented in object-oriented programming languages like C++ or Smalltalk. 0201633612B07092001

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.

The singleton pattern is a fully paid up member of the GoF's patterns book, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory classes, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.

Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?

Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

Preferred languages: C/C++, Java, and Ruby.

I am looking for some helpful books/tutorials on how to write your own compiler simply for educational purposes. I am most familiar with C/C++, Java, and Ruby, so I prefer resources that involve one of those three, but any good resource is acceptable.

The Dragon Book is definitely the "building compilers" book, but if your language isn't quite as complicated as the current generation of languages, you may want to look at the Interpreter pattern from Design Patterns.

The example in the book designs a regular expression-like language and is well thought through, but as they say in the book, it's good for thinking through the process but is effective really only on small languages. However, it is much faster to write an Interpreter for a small language with this pattern than having to learn about all the different types of parsers, yacc and lex, et cetera...

I think Modern Compiler Implementation in ML is the best introductory compiler writing text. There's a Java version and a C version too, either of which might be more accessible given your languages background. The book packs a lot of useful basic material (scanning and parsing, semantic analysis, activation records, instruction selection, RISC and x86 native code generation) and various "advanced" topics (compiling OO and functional languages, polymorphism, garbage collection, optimization and single static assignment form) into relatively little space (~500 pages).

I prefer Modern Compiler Implementation to the Dragon book because Modern Compiler implementation surveys less of the field--instead it has really solid coverage of all the topics you would need to write a serious, decent compiler. After you work through this book you'll be ready to tackle research papers directly for more depth if you need it.

I must confess I have a serious soft spot for Niklaus Wirth's Compiler Construction. It is available online as a PDF. I find Wirth's programming aesthetic simply beautiful, however some people find his style too minimal (for example Wirth favors recursive descent parsers, but most CS courses focus on parser generator tools; Wirth's language designs are fairly conservative.) Compiler Construction is a very succinct distillation of Wirth's basic ideas, so whether you like his style or not or not, I highly recommend reading this book.

I concur with the Dragon Book reference; IMO, it is the definitive guide to compiler construction. Get ready for some hardcore theory, though.

If you want a book that is lighter on theory, Game Scripting Mastery might be a better book for you. If you are a total newbie at compiler theory, it provides a gentler introduction. It doesn't cover more practical parsing methods (opting for non-predictive recursive descent without discussing LL or LR parsing), and as I recall, it doesn't even discuss any sort of optimization theory. Plus, instead of compiling to machine code, it compiles to a bytecode that is supposed to run on a VM that you also write.

It's still a decent read, particularly if you can pick it up for cheap on Amazon. If you only want an easy introduction into compilers, Game Scripting Mastery is not a bad way to go. If you want to go hardcore up front, then you should settle for nothing less than the Dragon Book.

Big List of Resources:


  • ¶ Link to a PDF file
  • $ Link to a printed book

This is a pretty vague question, I think; just because of the depth of the topic involved. A compiler can be decomposed into two separate parts, however; a top-half and a bottom-one. The top-half generally takes the source language and converts it into an intermediate representation, and the bottom half takes care of the platform specific code generation.

Nonetheless, one idea for an easy way to approach this topic (the one we used in my compilers class, at least) is to build the compiler in the two pieces described above. Specifically, you'll get a good idea of the entire process by just building the top-half.

Just doing the top half lets you get the experience of writing the lexical analyzer and the parser and go to generating some "code" (that intermediate representation I mentioned). So it will take your source program and convert it to another representation and do some optimization (if you want), which is the heart of a compiler. The bottom half will then take that intermediate representation and generate the bytes needed to run the program on a specific architecture. For example, the the bottom half will take your intermediate representation and generate a PE executable.

Some books on this topic that I found particularly helpful was Compilers Principles and Techniques (or the Dragon Book, due to the cute dragon on the cover). It's got some great theory and definitely covers Context-Free Grammars in a really accessible manner. Also, for building the lexical analyzer and parser, you'll probably use the *nix tools lex and yacc. And uninterestingly enough, the book called "lex and yacc" picked up where the Dragon Book left off for this part.

The quickest approach is through two books:

1990 version of An Introduction to Compiling Techniques, a First Course using ANSI C, LeX, and YaCC by JP Bennett - a perfect balance of example code, parsing theory and design- it contains a complete compiler written in C, lex and yacc for a simple grammar

Dragon Book (older version) - mostly a detailed reference for the features not covered in the former book

A long time ago I have read an article (I believe a blog entry) which put me on the "right" track on naming objects: Be very very scrupulous about naming things in your program.

For example if my application was (as a typical business app) handling users, companies and addresses I'd have a User, a Company and an Address domain class - and probably somewhere a UserManager, a CompanyManager and an AddressManager would pop up that handles those things.

So can you tell what those UserManager, CompanyManager and AddressManager do? No, because Manager is a very very generic term that fits to anything you can do with your domain objects.

The article I read recommended using very specific names. If it was a C++ application and the UserManager's job was allocating and freeing users from the heap it would not manage the users but guard their birth and death. Hmm, maybe we could call this a UserShepherd.

Or maybe the UserManager's job is to examine each User object's data and sign the data cryptographically. Then we'd have a UserRecordsClerk.

Now that this idea stuck with me I try to apply it. And find this simple idea amazingly hard.

I can describe what the classes do and (as long as I don't slip into quick & dirty coding) the classes I write do exactly one thing. What I miss to go from that description to the names is a kind of catalogue of names, a vocabulary that maps the concepts to names.

Ultimately I'd like to have something like a pattern catalogue in my mind (frequently design patterns easily provide the object names, e.g. a factory)

  • Factory - Creates other objects (naming taken from the design pattern)
  • Shepherd - A shepherd handles the lifetime of objects, their creation and shutdown
  • Synchronizer - Copies data between two or more objects (or object hierarchies)
  • Nanny - Helps objects reach "usable" state after creation - for example by wiring to other objects

  • etc etc.

So, how do you handle that issue? Do you have a fixed vocabulary, do you invent new names on the fly or do you consider naming things not-so-important or wrong?

P.S.: I'm also interested in links to articles and blogs discussing the issue. As a start, here is the original article that got me thinking about it: Naming Java Classes without a 'Manager'

Update: Summary of answers

Here's a little summary of what I learned from this question in the meantime.

  • Try not to create new metaphors (Nanny)
  • Have a look at what other frameworks do

Further articles/books on this topic:

And a current list of name prefixes/suffixes I collected (subjectively!) from the answers:

  • Coordinator
  • Builder
  • Writer
  • Reader
  • Handler
  • Container
  • Protocol
  • Target
  • Converter
  • Controller
  • View
  • Factory
  • Entity
  • Bucket

And a good tip for the road:

Don't get naming paralysis. Yes, names are very important but they're not important enough to waste huge amounts of time on. If you can't think up a good name in 10 minutes, move on.

I asked a similar question but where possible I try to copy the names already in the .NET framework, look for ideas in the Java and Android frameworks.

Seems Helper, Manager, Util is the unavoidable noun you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator.

You could get particularly purple prosey with the names and go for things like Minder, Overseer,Supervisor,Administrator,Master but as I said I prefer keeping it like the framework names you're use to.

Some other common suffixes (if that is the correct term) you also find in the .NET framework are

  • Builder
  • Writer
  • Reader
  • Handler
  • Container

Specific to C#, I found "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" to have lots of good information on the logic of naming.

As far as finding those more specific words though, I often use a thesaurus and jump through related words to try and find a good one. I try not to spend to much time with it though, as I progress through development I come up with better names, or sometimes realize that SuchAndSuchManager should really be broken up into multiple classes, and then the name of that deprecated class becomes a non-issue.

It wasn't that long ago that I was a beginning coder, trying to find good books/tutorials on languages I wanted to learn. Even still, there are times I need to pick up a language relatively quickly for a new project I am working on. The point of this post is to document some of the best tutorials and books for these languages. I will start the list with the best I can find, but hope you guys out there can help with better suggestions/new languages. Here is what I found:

Since this is now wiki editable, I am giving control up to the community. If you have a suggestion, please put it in this section. I decided to also add a section for general be a better programmer books and online references as well. Once again, all recommendations are welcome.

General Programming

Online Tutorials
Foundations of Programming By Karl Seguin - From Codebetter, its C# based but the ideas ring true across the board, can't believe no-one's posted this yet actually.
How to Write Unmaintainable Code - An anti manual that teaches you how to write code in the most unmaintable way possible. It would be funny if a lot of these suggestions didn't ring so true.
The Programming Section of Wiki Books - suggested by Jim Robert as having a large amount of books/tutorials on multiple languages in various stages of completion
Just the Basics To get a feel for a language.

Code Complete - This book goes without saying, it is truely brilliant in too many ways to mention.
The Pragmatic Programmer - The next best thing to working with a master coder, teaching you everything they know.
Mastering Regular Expressions - Regular Expressions are an essential tool in every programmer's toolbox. This book, recommended by Patrick Lozzi is a great way to learn what they are capable of.
Algorithms in C, C++, and Java - A great way to learn all the classic algorithms if you find Knuth's books a bit too in depth.


Online Tutorials
This tutorial seems to pretty consise and thourough, looked over the material and seems to be pretty good. Not sure how friendly it would be to new programmers though.
K&R C - a classic for sure. It might be argued that all programmers should read it.
C Primer Plus - Suggested by Imran as being the ultimate C book for beginning programmers.
C: A Reference Manual - A great reference recommended by Patrick Lozzi.


Online Tutorials
The tutorial on seems to be the most complete. I found another tutorial here but it doesn't include topics like polymorphism, which I believe is essential. If you are coming from C, this tutorial might be the best for you.

Another useful tutorial, C++ Annotation. In Ubuntu family you can get the ebook on multiple format(pdf, txt, Postscript, and LaTex) by installing c++-annotation package from Synaptic(installed package can be found in /usr/share/doc/c++-annotation/.

The C++ Programming Language - crucial for any C++ programmer.
C++ Primer Plus - Orginally added as a typo, but the amazon reviews are so good, I am going to keep it here until someone says it is a dud.
Effective C++ - Ways to improve your C++ programs.
More Effective C++ - Continuation of Effective C++.
Effective STL - Ways to improve your use of the STL.
Thinking in C++ - Great book, both volumes. Written by Bruce Eckel and Chuck Ellison.
Programming: Principles and Practice Using C++ - Stroustrup's introduction to C++.
Accelerated C++ - Andy Koenig and Barbara Moo - An excellent introduction to C++ that doesn't treat C++ as "C with extra bits bolted on", in fact you dive straight in and start using STL early on.


FORTH, a text and reference. Mahlon G. Kelly and Nicholas Spies. ISBN 0-13-326349-5 / ISBN 0-13-326331-2. 1986 Prentice-Hall. Leo Brodie's books are good but this book is even better. For instance it covers defining words and the interpreter in depth.


Online Tutorials
Sun's Java Tutorials - An official tutorial that seems thourough, but I am not a java expert. You guys know of any better ones?
Head First Java - Recommended as a great introductory text by Patrick Lozzi.
Effective Java - Recommended by pek as a great intermediate text.
Core Java Volume 1 and Core Java Volume 2 - Suggested by FreeMemory as some of the best java references available.
Java Concurrency in Practice - Recommended by MDC as great resource for concurrent programming in Java.

The Java Programing Language


Online Tutorials - The online documentation for this language is pretty good. If you know of any better let me know.
Dive Into Python - Suggested by Nickola. Seems to be a python book online.


Online Tutorials
perldoc perl - This is how I personally got started with the language, and I don't think you will be able to beat it.
Learning Perl - a great way to introduce yourself to the language.
Programming Perl - greatly referred to as the Perl Bible. Essential reference for any serious perl programmer.
Perl Cookbook - A great book that has solutions to many common problems.
Modern Perl Programming - newly released, contains the latest wisdom on modern techniques and tools, including Moose and DBIx::Class.


Online Tutorials
Adam Mika suggested Why's (Poignant) Guide to Ruby but after taking a look at it, I don't know if it is for everyone. Found this site which seems to offer several tutorials for Ruby on Rails.
Programming Ruby - suggested as a great reference for all things ruby.

Visual Basic

Online Tutorials
Found this site which seems to devote itself to visual basic tutorials. Not sure how good they are though.


Online Tutorials
The main PHP site - A simple tutorial that allows user comments for each page, which I really like. PHPFreaks Tutorials - Various tutorials of different difficulty lengths.
Quakenet/PHP tutorials - PHP tutorial that will guide you from ground up.


Online Tutorials
Found a decent tutorial here geared toward non-programmers. Found another more advanced one here. Nickolay suggested A reintroduction to javascript as a good read here.

Head first JavaScript
JavaScript: The Good Parts (with a Google Tech Talk video by the author)


Online Tutorials
C# Station Tutorial - Seems to be a decent tutorial that I dug up, but I am not a C# guy.
C# Language Specification - Suggested by tamberg. Not really a tutorial, but a great reference on all the elements of C#
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth


nlucaroni suggested the following:
OCaml for Scientists Introduction to ocaml
Using Understand and unraveling ocaml: practice to theory and vice versa
Developing Applications using Ocaml - O'Reilly
The Objective Caml System - Official Manua


Online Tutorials
nlucaroni suggested the following:
Explore functional programming with Haskell
Real World Haskell
Total Functional Programming


wfarr suggested the following:
The Little Schemer - Introduction to Scheme and functional programming in general
The Seasoned Schemer - Followup to Little Schemer.
Structure and Interpretation of Computer Programs - The definitive book on Lisp (also available online).
Practical Common Lisp - A good introduction to Lisp with several examples of practical use.
On Lisp - Advanced Topics in Lisp
How to Design Programs - An Introduction to Computing and Programming
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp - an approach to high quality Lisp programming

What about you guys? Am I totally off on some of there? Did I leave out your favorite language? I will take the best comments and modify the question with the suggestions.

Java: SCJP for Java 6. I still use it as a reference.


O'Reilly Book:

  1. Real World Haskell, a great tutorial-oriented book on Haskell, available online and in print.

My favorite general, less academic online tutorials:

  1. The Haskell wikibook which contains all of the excellent Yet Another Haskell Tutorial. (This tutorial helps with specifics of setting up a Haskell distro and running example programs, for example.)
  2. Learn you a Haskell for Great Good, in the spirit of Why's Poignant Guide to Ruby but more to the point.
  3. Write yourself a Scheme in 48 hours. Get your hands dirty learning Haskell with a real project.

Books on Functional Programming with Haskell:

  1. Lambda calculus, combinators, more theoretical, but in a very down to earth manner: Davie's Introduction to Functional Programming Systems Using Haskell
  2. Laziness and program correctness, thinking functionally: Bird's Introduction to Functional Programming Using Haskell

Some books on Java I'd recommend:

For Beginners: Head First Java is an excellent introduction to the language. And I must also mention Head First Design Patterns which is a great resource for learners to grasp what can be quite challenging concepts. The easy-going fun style of these books are ideal for ppl new to programming.

A really thorough, comprehensive book on Java SE is Bruce Eckel's Thinking In Java v4. (At just under 1500 pages it's good for weight-training as well!) For those of us not on fat bank-bonuses there are older versions available for free download.

Of course, as many ppl have already mentioned, Josh Bloch's Effective Java v2 is an essential part of any Java developer's library.

Let's not forget Head First Java, which could be considered the essential first step in this language or maybe the step after the online tutorials by Sun. It's great for the purpose of grasping the language concisely, while adding a bit of fun, serving as a stepping stone for the more in-depth books already mentioned.

Sedgewick offers great series on Algorithms which are a must-have if you find Knuth's books to be too in-depth. Knuth aside, Sedgewick brings a solid approach to the field and he offers his books in C, C++ and Java. The C++ books could be used backwardly on C since he doesn't make a very large distinction between the two languages in his presentation.

Whenever I'm working on C, C:A Reference Manual, by Harbison and Steele, goes with me everywhere. It's concise and efficient while being extremely thorough making it priceless(to me anyways).

Languages aside, and if this thread is to become a go-to for references in which I think it's heading that way due to the number of solid contributions, please include Mastering Regular Expressions, for reasons I think most of us are aware of... some would also say that regex can be considered a language in its own right. Further, its usefulness in a wide array of languages makes it invaluable.

C: “Programming in C”, Stephen G. Kochan, Developer's Library.

Organized, clear, elaborate, beautiful.


The first one is good for beginners and the second one requires more advanced level in C++.

I know this is a cross post from here... but, I think one of the best Java books is Java Concurrency in Practice by Brian Goetz. A rather advanced book - but, it will wear well on your concurrent code and Java development in general.


C# to the Point by Hanspeter Mössenböck. On a mere 200 pages he explains C# in astonishing depth, focusing on underlying concepts and concise examples rather than hand waving and Visual Studio screenshots.

For additional information on specific language features, check the C# language specification ECMA-334.

Framework Design Guidelines, a book by Krzysztof Cwalina and Brad Abrams from Microsoft, provides further insight into the main design decisions behind the .NET library.

For Lisp and Scheme (hell, functional programming in general), there are few things that provide a more solid foundation than The Little Schemer and The Seasoned Schemer. Both provide a very simple and intuitive introduction to both Scheme and functional programming that proves far simpler for new students or hobbyists than any of the typical volumes that rub off like a nonfiction rendition of War & Peace.

Once they've moved beyond the Schemer series, SICP and On Lisp are both fantastic choices.

For C++ I am a big fan of C++ Common Knowledge: Essential Intermediate Programming, I like that it is organized into small sections (usually less than 5 pages per topic) So it is easy for me to grab it and read up on concepts that I need to review.

It is a must read for me the night before and on the plane to a job interview.

C Primer Plus, 5th Edition - The C book to get if you're learning C without any prior programming experience. It's a personal favorite of mine as I learned to program from this book. It has all the qualities a beginner friendly book should have:

  • Doesn't assume any prior exposure to programming
  • Enjoyable to read (without becoming annoying like For Dummies /
  • Doesn't oversimplify

For Javascript:

For PHP:

For OO design & programming, patterns:

For Refactoring:


  • C - The C Programming Language - Obviously I had to reference K&R, one of the best programming books out there full stop.
  • C++ - Accelerated C++ - This clear, well written introduction to C++ goes straight to using the STL and gives nice, clear, practical examples. Lives up to its name.
  • C# - Pro C# 2008 and the .NET 3.5 Platform - Bit of a mouthful but wonderfully written and huge depth.
  • F# - Expert F# - Designed to take experienced programmers from zero to expert in F#. Very well written, one of the author's invented F# so you can't go far wrong!
  • Scheme - The Little Schemer - Really unique approach to teaching a programming language done really well.
  • Ruby - Programming Ruby - Affectionately known as the 'pick axe' book, this is THE defacto introduction to Ruby. Very well written, clear and detailed.

I have read around 4-5 books on design patterns, but still I dont feel I have come closer to intermediate level in design patterns?

How should I go studying design patterns?

Is there any best book for design pattern?

I know this will come only with experience but there must be some way to master these?

I'm pondering the design of a C# library, that will have several different high level functions. Of course, those high-level functions will be implemented using the SOLID class design principles as much as possible. As such, there will probably be classes intended for consumers to use directly on a regular basis, and "support classes" that are dependencies of those more common "end user" classes.

The question is, what is the best way to design the library so it is:

  • DI Agnostic - Although adding basic "support" for one or two of the common DI libraries (StructureMap, Ninject, etc) seems reasonable, I want consumers to be able to use the library with any DI framework.
  • Non-DI usable - If a consumer of the library is using no DI, the library should still be as easy to use as possible, reducing the amount of work a user has to do to create all these "unimportant" dependencies just to get to the "real" classes they want to use.

My current thinking is to provide a few "DI registration modules" for the common DI libraries (e.g a StructureMap registry, a Ninject module), and a set or Factory classes that are non-DI and contain the coupling to those few factories.


This is actually simple to do once you understand that DI is about patterns and principles, not technology.

To design the API in a DI Container-agnostic way, follow these general principles:

Program to an interface, not an implementation

This principle is actually a quote (from memory though) from Design Patterns, but it should always be your real goal. DI is just a means to achieve that end.

Apply the Hollywood Principle

The Hollywood Principle in DI terms says: Don't call the DI Container, it'll call you.

Never directly ask for a dependency by calling a container from within your code. Ask for it implicitly by using Constructor Injection.

Use Constructor Injection

When you need a dependency, ask for it statically through the constructor:

public class Service : IService
    private readonly ISomeDependency dep;

    public Service(ISomeDependency dep)
        if (dep == null)
            throw new ArgumentNullException("dep");

        this.dep = dep;

    public ISomeDependency Dependency
        get { return this.dep; }

Notice how the Service class guarantees its invariants. Once an instance is created, the dependency is guaranteed to be available because of the combination of the Guard Clause and the readonly keyword.

Use Abstract Factory if you need a short-lived object

Dependencies injected with Constructor Injection tend to be long-lived, but sometimes you need a short-lived object, or to construct the dependency based on a value known only at run-time.

See this for more information.

Compose only at the Last Responsible Moment

Keep objects decoupled until the very end. Normally, you can wait and wire everything up in the application's entry point. This is called the Composition Root.

More details here:

Simplify using a Facade

If you feel that the resulting API becomes too complex for novice users, you can always provide a few Facade classes that encapsulate common dependency combinations.

To provide a flexible Facade with a high degree of discoverability, you could consider providing Fluent Builders. Something like this:

public class MyFacade
    private IMyDependency dep;

    public MyFacade()
        this.dep = new DefaultDependency();

    public MyFacade WithDependency(IMyDependency dependency)
        this.dep = dependency;
        return this;

    public Foo CreateFoo()
        return new Foo(this.dep);

This would allow a user to create a default Foo by writing

var foo = new MyFacade().CreateFoo();

It would, however, be very discoverable that it's possible to supply a custom dependency, and you could write

var foo = new MyFacade().WithDependency(new CustomDependency()).CreateFoo();

If you imagine that the MyFacade class encapsulates a lot of different dependencies, I hope it's clear how it would provide proper defaults while still making extensibility discoverable.

FWIW, long after writing this answer, I expanded upon the concepts herein and wrote a longer blog post about DI-Friendly Libraries, and a companion post about DI-Friendly Frameworks.

The C++ friend keyword allows a class A to designate class B as its friend. This allows Class B to access the private/protected members of class A.

I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this earlier StackOverflow question seem to be saying it is a useful part of C++ and there are good reasons to use it. In my experience I'd have to agree.

Another question seems to me to be really asking how to do something similar to friend in a C# application. While the answers generally revolve around nested classes, it doesn't seem quite as elegant as using the friend keyword.

The original Design Patterns book uses it regularly throughout its examples.

So in summary, why is friend missing from C#, and what is the "best practice" way (or ways) of simulating it in C#?

(By the way, the internal keyword is not the same thing, it allows all classes within the entire assembly to access internal members, while friend allows you to give a certain class complete access to exactly one other class)

Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language.

That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I bet because of C#'s "pure" OOness (compared to C++'s pseudo OOness) MS decided that because Java has no friend keyword C# shouldn't either (just kidding ;))

On a serious note: internal is not as good as friend but it does get the job done. Remember that it is rare that you will be distributing your code to 3rd party developers not though a DLL; so as long as you and your team know about the internal classes and their use you should be fine.

EDIT Let me clarify how the friend keyword undermines OOP.

Private and protected variables and methods are perhaps one of the most important part of OOP. The idea that objects can hold data or logic that only they can use allows you to write your implementation of functionality independent of your environment - and that your environment cannot alter state information that it is not suited to handle. By using friend you are coupling two classes' implementations together - which is much worse then if you just coupled their interface.

Is it a good concept to use multiple inheritance or can I do other things instead?

See w:Multiple Inheritance.

Multiple inheritance has received criticism and as such, is not implemented in many languages. Criticisms includes:

  • Increased complexity
  • Semantic ambiguity often summarized as the diamond problem.
  • Not being able to explicitly inherit multiple times from a single class
  • Order of inheritance changing class semantics.

Multiple inheritance in languages with C++/Java style constructors exacerbates the inheritance problem of constructors and constructor chaining, thereby creating maintenance and extensibility problems in these languages. Objects in inheritance relationships with greatly varying construction methods are hard to implement under the constructor chaining paradigm.

Modern way of resolving this to use interface (pure abstract class) like COM and Java interface.

I can do other things in place of this?

Yes, you can. I am going to steal from GoF.

  • Program to an Interface, not an Implementation
  • Prefer composition over inheritance

What are the differences between Strategy design pattern and State design pattern?

I was going through quite a few articles on the web but could not make out the difference clearly.

Can someone please explain in layman's terms?

Both patterns delegate to a base class that has several derivative, but it's only in the State pattern that these derivative classes hold a reference back to context class.

Another way to look at it is that the Strategy pattern is a simpler version of the State pattern; a sub-pattern, if you like. It really depends if you want the derived states to hold references back to the context or not (i.e: do you want them to call methods on the context).

For more info: Robert C Martin (& Micah Martin) answer this in their book, "Agile Principles, Patterns and Practices in C#". (

Can somebody please explain in layman's terms?

Design patterns are not really "layman" concepts, but I'll try to make it as clear as possible. Any design pattern can be considered in three dimensions:

  1. The problem the pattern solves;
  2. The static structure of the pattern (class diagram);
  3. The dynamics of the pattern (sequence diagrams).

Let's compare State and Strategy.

Problem the pattern solves

State is used in one of two cases [GoF book p. 306]:

  • An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
  • Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.

If you want to make sure you indeed have the problem the State pattern solves, you should be able to model the states of the object using a finite state machine. You can find an applied example here.

Each state transition is a method in the State interface. This implies that for a design, you have to be pretty certain about state transitions before you apply this pattern. Otherwise, if you add or remove transitions, it will require changing the interface and all the classes that implement it.

I personally haven't found this pattern that useful. You can always implement finite state machines using a lookup table (it's not an OO way, but it works pretty well).

Strategy is used for the following [GoF book p. 316]:

  • many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.
  • you need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms [HO87].
  • an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
  • a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

The last case of where to apply Strategy is related to a refactoring known as Replace conditional with polymorphism.

Summary: State and Strategy solve very different problems. If your problem can't be modeled with a finite state machine, then likely State pattern isn't appropriate. If your problem isn't about encapsulating variants of a complex algorithm, then Strategy doesn't apply.

Static structure of the pattern

State has the following UML class structure:

PlantUML class diagram of State Pattern

Strategy has the following UML class structure:

PlantUML class diagram of Strategy Pattern

Summary: in terms of the static structure, these two patterns are mostly identical. In fact, pattern-detecting tools such as this one consider that "the structure of the [...] patterns is identical, prohibiting their distinction by an automatic process (e.g., without referring to conceptual information)."

There can be a major difference, however, if ConcreteStates decide themselves the state transitions (see the "might determine" associations in the diagram above). This results in coupling between concrete states. For example (see the next section), state A determines the transition to state B. If the Context class decides the transition to the next concrete state, these dependencies go away.

Dynamics of the pattern

As mentioned in the Problem section above, State implies that behavior changes at run-time depending on some state of an object. Therefore, the notion of state transitioning applies, as discussed with the relation of the finite state machine. [GoF] mentions that transitions can either be defined in the ConcreteState subclasses, or in a centralized location (such as a table-based location).

Let's assume a simple finite state machine:

PlantUML state transition diagram with two states and one transition

Assuming the subclasses decide the state transition (by returning the next state object), the dynamic looks something like this:

PlantUML sequence diagram for state transitions

To show the dynamics of Strategy, it's useful to borrow a real example.

PlantUML sequence diagram for strategy transitions

Summary: Each pattern uses a polymorphic call to do something depending on the context. In the State pattern, the polymorphic call (transition) often causes a change in the next state. In the Strategy pattern, the polymorphic call does not typically change the context (e.g., paying by credit card once doesn't imply you'll pay by PayPal the next time). Again, the State pattern's dynamics are determined by its corresponding fininte state machine, which (to me) is essential to correct application of this pattern.

There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:

  1. Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.

  2. Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.

What are the benefits, costs, and consequences of each? Are there other alternatives?

I see this debate come up on a regular basis, but I don't think it's been asked on Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it.

At the beginning of GOF they state

Favor object composition over class inheritance.

This is further discussed here

When modelling classes, what is the preferred way of initializing:

  1. Constructors, or
  2. Factory Methods

And what would be the considerations for using either of them?

In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)

Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.

In contrast to this I can have a static factory method on those classes which will return null if the record is not found.

Which approach is better in this case, constructor or factory method?

From page 108 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.

Use the Factory Method pattern when

  • a class can't anticipate the class of objects it must create
  • a class wants its subclasses to specify the objects it creates
  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate

You need to read (if you have access to) Effective Java 2 Item 1: Consider static factory methods instead of constructors.

Static factory methods advantages:

  1. They have names.
  2. They are not required to create a new object each time they are invoked.
  3. They can return an object of any subtype of their return type.
  4. They reduce verbosity of creating parameterized type instances.

Static factory methods disadvantages:

  1. When providing only static factory methods, classes without public or protected constructors cannot be subclassed.
  2. They are not readily distinguishable from other static methods

Ask yourself what they are and why do we have them. They both are there to create instance of an object.

ElementarySchool school = new ElementarySchool();
ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside

No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:

HighSchool school = new HighSchool();
HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside

In case of an interface we would have:

ISchool school = new HighSchool();
ISchool school = SchoolFactory.Construct(); // new HighSchool() inside

Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).

And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school.

ISchool school = SchoolFactory.ConstructForStudent(myStudent);

Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.

So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way.

This way you follow the first design principle from the gang of four book "Program to an interface, not an implementation".

I'm a confused newbie and hobbyist programmer trying to get a grip on this, so forgive me if my question is a little off or doesn't make much sense.

I see a lot of questions on SO revolving around the use of design patterns, and I'm wondering if anyone has a good resources for learning about, and implementing design patterns? I understand the general idea, and know how/when to use a couple of them(Singletons, Factory methods) but I know I'm missing out.

(Just in case it matters, my language of preference is C# but I could learn from examples in other languages)

Applying UML and Patterns by Craig Larman. Start from the basic of analysis, design and uses a simple Case scenario. Introduces most of the basic patterns in a simple way.

An introductory book that I found useful and well written is Design Patterns Explained by Alan Shalloway and James Trott (Addison Wesley).

alt text

Do not start from the Gang of Four book, for it is not an introductory book by any means.

The original Design Patterns book is a must-read for all programmers.

It is an excellent book on every level: layout, clarity, insight, depth. It's one of those great books that you first read cover-to-cover, and then use as a reference until you literally know it inside out.

You could start by the Wikipedia page, but treat yourself with the great book too.

Design patterns are great for various reasons:

  1. gives you a starting for solving common problems.
  2. gives developers a vocabulary to talk about certain ways of solving problems in a very compact manner.
  3. when working with developers who know design patterns and you use design patterns in your solutions they will understand the solutions a lot faster.

But when your goal is just to learn design patterns I think you are missing the fundamentals. All design patterns are based on more common principles. High Cohesion, Low Coupling Open Closed Principle, DRY, Liskov Substitution Principle etc. For these fundamentals I would read the following books in this order:

  1. Head First Object-Oriented Analysis and Design (Head First) [ILLUSTRATED] (Paperback)
  2. Applying UML and Patterns (Hardcover)
  3. Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series) (Hardcover)

After that you are ready for the basic gang of four design patterns

  1. Head First Design Patterns (Head First) [ILLUSTRATED] (Paperback)
  2. The BIBLE
  3. A nice website (don't buy anything, it is not worth it) (some implementations of this site are worth a discussion

The next step:

  1. Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series) (Hardcover)
  2. The POSA books

And always remember : the pattern is not the goal !

Before spending money on books I would recommend Wikipedia's excellent design patterns page. Also for something different Google for "design pattern screencasts" or search for "design patterns" on YouTube. Getting the same information presented differently often helps the penny drop.

The Gang of Four book is the definitive text on the most well known patterns but is not that easy to read and with C++ examples not everyone's favourite.

The Head First Design Patterns text is far more accessible but only contains a subset of the Gang of Four patterns.

The most important thing is to understand where and why a particular pattern is useful. Afterwards search the web for implementation examples in the language of your choice and experiment until you "get it". Understand one pattern before moving on to the next. Everyone understands some patterns better than others (and there are hundreds of lesser known ones).

Just keep plugging away.

Head First Design Patterns

alt text

and the Design Pattern Wikipedia page are the best resources for beginners. FluffyCat is another good, free online resource for design patterns in both Java and PHP.

The Gang of Four book is where to go afterward, but it's fairly advanced, so I'd wait until you have a pretty firm grasp from the other resources.

I'd add that Design Patterns book from the "Gang of four" is a bible for anyone who is seriously interested in design patterns.

My questions is simple!

  1. Would you start learning Smalltalk if you had the time? Why? Why not?
  2. Do you already know Smalltalk? Why would you recommend Smalltalk? Why not?

Personally I'm a Ruby on Rails programmer and I really like it. However, I'm thinking about Smalltalk because I read various blogs and some people are calling Ruby something like "Smalltalk Light". The second reason why I'm interested in Smalltalk is Seaside.

Maybe someone has made the same transition before?

EDIT: Actually, what got me most excited about Smalltalk/Seaside is the following Episode of WebDevRadio: Episode 52: Randal Schwartz on Seaside (among other things)

If you like Ruby you'll probably like Smalltalk. IIRC Seaside has been ported to the Gemstone VM, which is part of their Gemstone/S OODBMS. This has much better thread support than Ruby, so it is a better back-end for a high-volume system. This might be a good reason to take a close look at it.

Reasons to learn Smalltalk:

  • It's a really, really nice programming environment. Once you've got your head around it (it tends to be a bit of a culture shock for people used to C++ or Java) you'll find it to be a really good environment to work in. Even a really crappy smalltalk like the Old Digitalk ones I used is a remarkably pleasant system to use. Many of the old XP and O-O guru types like Kent Beck and Martin Fowler cut their teeth on Smalltalk back in the day and can occasionally be heard yearning for the good old days in public (Thanks to Frank Shearer for the citation, +1) - Agile development originated on this platform.

  • It's one of the most productive development platforms in history.

  • Several mature implementations exist and there's a surprisingly large code base out there. At one point it got quite trendy in financial market circles where developer productivity and time-to-market is quite a big deal. Up until the mid 1990s it was more or less the only game in town (With the possible exception of LISP) if you wanted a commercially supported high-level language that was suitable for application development.

  • Deployment is easy - just drop the image file in the appropriate directory.

  • Not really a reason, but the Gang of Four Book uses Smalltalk for quite a few of their examples.

Reasons not to learn Smalltalk:

  • It's something of a niche market. You may have trouble finding work. However if you are producing some sort of .com application where you own the servers this might not be an issue.

  • It's viewed as a legacy system by many. There is relatively little new development on the platform (although Seaside seems to be driving a bit of a renaissance).

  • It tends not to play nicely with traditional source control systems (at least as of the early-mid 90's when I used it). This may or may not still be the case.

  • It is somewhat insular and likes to play by itself. Python or Ruby are built for integration from the ground up and tend to be more promiscuous and thus easier to integrate with 3rd party software. However, various other more mainstream systems suffer from this type of insularity to a greater or lesser degree and that doesn't seem to impede their usage much.

  • When should implement or extend be used?
  • What are some real-world examples?

Is this correct?

Implementing appears to be a way to enforce that certain methods exists in a class, and that these methods function calls are properly formatted. Implementing is not a way of passing variables or "settings" to the class though?

Expected real-life scenario: I have an e-commerce platform featuring multiple payment classes that all follow the same design. When a new payment class should be added, it's really easy to follow the defined design of the interface to ensure that all bits and pieces are there, from the beginning.

Extending classes makes the extended (child?) class inherit everything from its parent class except methods & variables declared as private?

Expected real-life scenario: I have one class called sessions with two child classes named sessioncookies and databasesessions. sessioncookies and databasesessions, together inherit a number of mutual config options from their parent sessions, making it easy to change a config option to affect all sorts of eventual visitor data storage.

Inheritance is useful to reduce the amount of code you rewrite. If you have several classes with a few common methods or fields, instead of defining these methods and fields over and over you can factor them into a base class and have each of the child classes extend that base class.

Interfaces (and implements) are useful when you'd like to define a common protocol for how a group of objects should behave. For example, you might want to mandate that objects that are comparable can be compared for equality and hashed, etc.

Using inheritance is ultimately a design choice. Be on the lookout for cases where you define the same methods across several classes; those are excellent cases where you can factor those methods out into a base class. The same goes for classes that observe some of the same characteristics: you can guarantee consistency by putting those characteristics in an interface to be implemented by those related classes.

Inheritance is a big concept in OOP that goes way beyond just PHP. I recommend you read the wikipedia article on inheritance and perhaps Design Patterns by the Gang of Four.

I believe your understanding of inheritance is mainly correct. The next step would be to use it in production.

What is a good challenge to improve your skills in object oriented programming?

The idea behind this poll is to provide an idea of which exercises are useful for learning OOP.

The challenge should be as language agnostic as possible, requiring either little or no use of specific libraries, or only the most common of libraries. Try to include only one challenge per answer, so that a vote will correspond to the merits of that challenge alone. Would also be nice if a level of skill required was indicated, and also the rationale behind why it is a useful exercise.

Solutions to the challenges could then be posted as answers to a "How to..." question and linked to from here.

For example:

  • Challenge - implement a last-in-first-out stack
  • Skill level - beginner
  • Rationale - gives experience of how to reference objects

After you have learned the basics, study the "Gang of four" design patterns book.

This is a classic, and a must read for any coder who wants to understand how to use OO to design elegant solutions to common coding problems.

Currently, I'm reading a lot about Software Engineering, Software Design, Design Patterns etc. Coming from a totally different background, that's all new fascinating stuff to me, so please bear with me in case I'm not using the correct technical terminology to describe certain aspects ;-)

I ended up using Reference Classes (a way of OOP in R) most of the time because object orientation seems to be the right choice for a lot of the stuff that I'm doing.

Now, I was wondering if anyone has some good advice or some experience with respect to implementing the MVC (Model View Controller; also known as MVP: Model View Presenter) pattern in R, preferably using Reference Classes.

I'd also be very interested in info regarding other "standard" design patterns such as observer, blackboard etc., but I don't want to make this too broad of a question. I guess the coolest thing would be to see some minimal example code, but any pointer, "schema", diagram or any other idea will also be greatly appreciated!

For those interested in similar stuff, I can really recommend the following books:

  1. The Pragmatic Programmer
  2. Design Patterns

UPDATE 2012-03-12

I did eventually come up with a small example of my interpretation of MVC (which might not be totally correct ;-)).

Package Dependencies


Class Definition Observer

        notify=function(uid, ...) {
            message(paste("Notifying subscribers of model uid: ", uid, sep=""))
            temp <- get(uid, .self$.X)
            if (length(temp$subscribers)) {
                # Call method updateView() for each subscriber reference
                sapply(temp$subscribers, function(x) {

Class Definition Model

        initialize=function(...) {
            # Make sure all inputs are used ('...')
            .self <- callSuper(...)
            # Ensure uid
            .self$uid <- digest(c(.self, Sys.time()))
            # Ensure hash key of initial state
            .self$state <- digest(.self$.X)
            # Register uid in observer
            assign(.self$uid, list(state=.self$state), .self$observer$.X)
        multiply=function(x, ...) {
            .self$.X <- .X * x 
            # Handle state change
        publish=function(...) {
            message(paste("Publishing state change for model uid: ", 
                .self$uid, sep=""))
            # Publish current state to observer
            if (!exists(.self$uid, .self$observer$.X)) {
                assign(.self$uid, list(state=.self$state), .self$observer$.X)
            } else {
                temp <- get(.self$uid, envir=.self$observer$.X)
                temp$state <- .self$state
                assign(.self$uid, temp, .self$observer$.X)    
            # Make observer notify all subscribers
        statechangeDetect=function(...) {
            out <- TRUE
            # Hash key of current state
            state <- digest(.self$.X)
            if (length(.self$state)) {
                out <- .self$state != state
                if (out) {
                # Update state if it has changed
                    .self$state <- state
            if (out) {
                message(paste("State change detected for model uid: ", 
                   .self$uid, sep=""))
                # Publish state change to observer

Class Definition Controller and Views

        multiply=function(x, ...) {
            # Call respective method of model
        subscribe=function(...) {
            uid     <- .self$model$uid
            envir   <- .self$model$observer$.X 
            temp <- get(uid, envir)
            # Add itself to subscribers of underlying model
            temp$subscribers <- c(temp$subscribers, .self)
            assign(uid, temp, envir)    
        updateView=function(...) {
            # Call display method of each registered view
            sapply(.self$views, function(x) {
        display=function(model, x=1, y=2, ...) {
            plot(x=model$.X[,x], y=model$.X[,y])
        display=function(model, ...) {

Class Definition For Representing Dummy Data

            new("Model", .X=.self$.X)

Create Instances

x <- new("MyData", .X=data.frame(a=1:3, b=10:12))

Investigate model characteristics and observer state

mod <- x$modelMake()

> mod$uid
[1] "fdf47649f4c25d99efe5d061b1655193"
# Field value automatically set when initializing object.
# See 'initialize()' method of class 'Model'.

> mod$state
[1] "6d95a520d4e3416bac93fbae88dfe02f"
# Field value automatically set when initializing object.
# See 'initialize()' method of class 'Model'.

> ls(mod$observer$.X)
[1] "fdf47649f4c25d99efe5d061b1655193"

> get(mod$uid, mod$observer$.X)
[1] "6d95a520d4e3416bac93fbae88dfe02f"

Note that the object's uid has automatically been registered in the observer upon initialization. That way, controllers/views can subscribe to notifications and we have a 1:n relationship.

Instantiate views and controller

view1 <- new("View1")
view2 <- new("View2")
cont  <- new("Controller", model=mod, views=list(view1, view2))


Controller subscribes to notifications of underlying model


Note that the subscription has been logged in the observer

get(mod$uid, mod$observer$.X)

Display Registered Views

> cont$updateView()
  a  b
1 1 10
2 2 11
3 3 12
[1] TRUE

There's also a plot window that is opened.

Modify Model

> cont$model$multiply(x=10)
State change detected for model uid: fdf47649f4c25d99efe5d061b1655193
Publishing state change for model uid: fdf47649f4c25d99efe5d061b1655193
Notifying subscribers of model uid: fdf47649f4c25d99efe5d061b1655193
   a   b
1 10 100
2 20 110
3 30 120
[1] TRUE

Note that both registered views are automatically updated as the underlying model published its state change to the observer, which in turn notified all subscribers (i.e., the controller).

Open Questions

Here's what I feel like I'm not fully understanding yet:

  1. Is this a somewhat correct implementation of the MVC pattern? If not, what did I do wrong?
  2. Should "processing" methods (e.g. aggregate data, take subsets etc.) for the model "belong" to the model or the controller class . So far, I always defined everything a specific object can "do" as methods of this very object.
  3. Should the controller be sort of a "proxy" controlling every interaction between model and views (sort of "both ways"), or is it only responsible for propagating user input to the model (sort of "one way"?
  1. It looks quite good, but I'm not so sure why you have an Observer additional to your other classes (maybe you can tell me) Usually the Controller IS an Observer. It's a really good idea to do this in R because when I learned it in Java it was not so easy to understand (Java hides some of the good parts)

  2. Yes and No. There are many different interpretations of this pattern. I like to have the methods in the Object, I'd say it belongs to the model. A simple example would be a sudoku solver that shows the solving steps in a GUI. Let's split it into some parts that can be separated into M, V and C: the raw data (2D array maybe), the sudoku functions (calc next step, ...), the GUI, someone who tells the GUI that a new step was calculated I'd put it like this: M: raw data + sudoku functions, C: who tells the GUI about changes / the model about GUI inputs, V: GUI without any logic others put the sudoku function into the Controller, is also right and might work better for some problems

  3. It's possible to have a "one way" controller like you call it and the View is an Observer of the model It's also possible to let the Controller do everything and Model and View don't know each other (have a look at Model View Presenter, that's about that)

Anyone can read the GoF book to learn what design patterns are and how to use them, but what is the process for figuring out when a design pattern solves a problem? Does the knowledge of the pattern drive the design, or is there a way to figure out how a pattern can be used to change a design?

In other words, are there patterns for Patterns?

Design Patterns? You're soaking in them!

There's nothing special about design patterns, they are merely patterns of design. All development uses design patterns. There are a certain set of design patterns in object oriented programming which are considered generally desirable and have become the canonical Design Patterns. But there are also many undesirable or otherwise indifferent design patterns (such as design anti-patterns) as well as undiscovered and/or undocumented patterns.

You can't avoid using patterns when programming. But you can become more aware of the patterns you are using and of when certain patterns are useful and when they are not. Studying the canonical Design Patterns from the GoF book will help, as will learning about code smells and refactoring. There's no one right answer for when a particular design or design pattern should be used, you need to build up experience in using and implementing them in order to know when and where to use which pattern.

Coming from a OO background (C#/java) I'm looking for resources to learn how to design pure C programs well.

Whilst i'm familiar with the syntax of C, and i can write small programs, i'm unsure of the approach to take for larger applications, and what techniques to employ. Anything you guys can recommend.

EDIT: I'm happy to completly abandon OO for the purposes of programming in C, my interest is in learning how to structure a program without OO, I want to learn about good ways of designing programs in procedural languages such as C.

This posting has a list of unix books which includes most of the classic C/Unix works. For C programming on Windows, Petzold's Programming Windows is probably the best start.

For C program design, some of the unix programming books will tell you snippets but I'm not aware of a 'C program architecture' book.

If you're used to java, some tips for C programing are:

  1. Make use of stack. Often when you call a procedure you will want to have variables allocated in the caller's stack frame and pass pointers to them into the procedure you want to call. This will be substantially faster than dynamically allocating memory with malloc() and much less error prone. Do this wherever appropriate.

  2. C doesn't do garbage collection, so dynamically allocating data items is more fiddly and you have to keep track of them to make sure they get freed. Variables allocated on the stack (see 1) are more 'idiomatic' where they are applicable. Plus, you don't have to free them - this is a bonus for local variables.

  3. Apropos of (2), consider an architecture where your functions return a status or error code and pass data in and out using the stack as per (1).

  4. Get to know what setjmp() and longjmp() do. They can be quite useful for generic error handler mechanisms in lieu of structured exception handling functionality.

  5. C does not support exceptions. See (3).

  6. Lint is your friend. Splint is even friendlier.

  7. Learn what the preprocessor does and what you shouldn't do with it even if you can.

  8. Learn the ins and outs of endian-ness, word alignment, pointer arithmetic and other low-level architectural arcana. Contrary to popular opinion these are not rocket science. If you're feeling keen, try dabbling in assembly language and get a working knowledge of that. It will do much for your understanding of what's going on in your C program.

  9. C has no concept of module scope, so plan your use of includes, prototype declarations, and use of extern and static to make private scopes and import identifiers.

  10. GUI programming in C is tedious on all platforms.

  11. Apropos of (10) learn the C API of at least one scripting language such as Tcl, Lua or Python. In many cases the best use of C is as a core high-performance engine on an application that is substantially written in something else.

  12. The equivalent of a constructor is an initialising function where you pass in a pointer to the item you want set up. Often you can see this in the form of a call to the function that looks like setup_foo(&my_foo). It's better to separate allocation from initialising, as you can use this function to initialise an item you have allocated on the stack. A similar principle applies to destructors.

  13. Most people find Hungarian notation about as readable as written Hungarian. The exception to this is native Hungarian speakers, who typically find Hungarian notation about as legible as Cuneiform.. Unfortunately Hungarian notation is widely encounterd in Windows software and the entire Win32 API uses it, with the expected effects on the legibility of software written on this platform.

  14. C/Unix books, even really good ones like the ones written by the late W Richard Stevens tend to be available secondhand quite cheaply through Amazon marketplace. In no particular order, get a copy of K&R, Stevens APUE and UNP 1 & 2, the Dragon book, Rochkind, Programming Pearls, Petzold and Richter (if working on Windows) and any of the other classic C/Unix works. Read, scribble on them with a pencil and generally interact with the books.

  15. There are many, many good C/Unix programming resources on the web.

  16. Read and understand the Ten Commandments of C Programming and some of the meta discussion as to the why's and wherefores behind the commandments. This is showing its age to a certain extent, although most of it is still relevant and obscure compilers are still quite common in the embedded systems world.

  17. Lex and Yacc are your friend if you want to write parsers.

  18. As Navicore points out below (+1), Hanson's 'C Interfaces and Implementations' is a run-down on interface/implementation design for modular architecture with a bunch of examples. I have actually heard of this book and heard good things about it, although I can't claim to have read it. Aside from the C idioms that I've described above, this concept is arguably the core of good procedural design. In fact, other procedural languages such as Modula-2 actually make this concept explicit in their design. This might be the closest thing to a 'C Program Architecture' book in print.

  19. Read the C FAQ.

Here's some interesting responses from a different question regarding OO programming in C. I made a post about some C code I worked with which basically impelmented object orientation stopping just short by not including virtual methods.

If I were doing C coding, I would use this technique to define 'objects'.

I find keeping Design Patterns in mind is always helpful, and can be implemented in most languages.

Here's a nice PDF discussing object oriented C programming.

What is your opinion of this design decision? What advantages does it have and what disadvantages?


The Gang of 4's crucial principle is "prefer composition to inheritance"; Go makes you follow it;-).

Possible Duplicate:
What is so bad about Singletons?

It's understandable that many design patterns can in some cases be abused, and like mom always said: "Too much of a good thing isn't always good!"

I'm noticing that these days, I'm using Singletons a lot, and I'm worried that I might be abusing the design pattern myself, and running deeper and deeper into a bad-practice kind of habit.

We're developing a Flex application that has a quite a large hierarchical data structure kept in memory while the user works on it. The user can load, save, change and refresh the data on demand.

This data is centralized by means of a Singleton class, which aggregates a couple of ArrayCollections, Arrays, value objects and some other native member variables exposed via getters and setters.

To get a reference to our data from anywhere in the application, we do the whole Model.getInstance() method type of thing, that I'm sure everyone is familiar with. This ensures that we always get our hands on the same copy of data, since when we designed, we said that only once instance is allowed to exist during the application lifetime.

From this central data repository, it's then easy for us to for example, dispatch property changed events, and can have multiple UI components that reference the central data, update their displays to reflect the data changes that have occurred.

So far, this approach has been effective and proven very practical to our circumstances.

I'm finding however, that I'm a little overeager when creating new classes. Questions like should a class be a Singleton, or should it rather be managed some other way, like maybe using a factory for example, tend to sometimes become a bit difficult, with a bit of uncertainty.

Where do I draw the line with singletons? Is there a good guideline for deciding when to use Singletons and when to stay away from them.

Also, can anyone recommend a good book on design patterns?

No, they're not necessarily bad.

As for a book, you need to start with the classics.

The key thing to remember is that design patterns are just a tool to help you understand the abstract concepts. Once you have that understanding, restricting yourself specifically to a "recipe" from a book is pointless and hurts your ability to write the code most appropriate for your purpose.

That said, reading books like GoF will present you with more ways to think about problems so that when the time comes to implement something on your own, you'll have a wider set of perspectives to approach the problem from.

In your case, if using singleton makes sense in every case, then go right ahead. If it "sort of" fits and you have to implement it in some clunky way, then you need to come up with a new solution. Forcing a pattern that isn't perfect is somewhat like hammering a square peg in a round hole.

Given that you say "this approach has been effective and proven very practical to our circumstances," I think you're doing fine.

Here are some good books:

Gang of Four Book - the classic book for design patterns

Head First Design Patterns - I've heard this recommended by a few people as an alternative

Singletons are not "that bad". If you have a lot of related Singletons and you can replace/consolidate a number of them using a Factory, without losing anything you care about, then that's when you should so do.

As to books, well, there's kind of a canon.

I know that design patterns is generally something that's connected to OO programming, but do you have some pattern you often use when you program C?

I'm not interested in simple translations of the classical OO patterns and please don't mention Duff's device. ;-)

Design Patterns could be viewed as missing language features. The Introduction of Design Patterns: Elements of Reusable Object-Oriented Software states:

The choice of programming language is important because it influences one's point of view. Our patterns assume Smalltalk/C++-level language features, and that choice determines what can and cannot be implemented easily. If we assumed procedural languages, we might have included design patterns called "Inheritance," "Encapsulation," and "Polymorphism." Similarly, some of our patterns are supported directly by the less common object-oriented languages. CLOS has multi-methods, for example, which lessen the need for a pattern such as Visitor. (italics mine)

The sentence in italics is the answer to your question.

I have a problem. My mind isn't working as I wish it would.

I'm currently working on a small 2D game-engine in C++, but I am now facing a deamon - I suck at designing a 'system of classes' that actually works. There are a blockade in my mind that disables me from seeing where I should use a class and where I should not. I was reading an article about engine-design and it purposed to use a 'State' class to manage the state of different game entries (I was using an int). It also suggested that all objects for the game (not io/video/sound etc) derive from either Renderable or NonRenderable classes. That's smart. I already know that that was a smart way of doing it - I mean, every object in Java is of baseclass Object right? Smart, I know that! How come I didn't do it that way? What do I have to read to really get into this mindset?

Another example. I'm taking this summer-course in Ruby (really simple) and we're supposed to design a camping site. Simple! So, a camping is a collection of 'plots' that each have a electrical-gauge to measure how much power the guest has consumed. My design was three classes, one for a Camping - that in turn used arrays of Guest and Plot classes. My teacher suggested that I use more classes. WTF(!) was my first thought, where, what classes?? Everything was a class in my opinion - until I realized, maybe the gauge should be a class to? Right now the gauge was an Integer in the Plot class.

I want to learn how to come up with a object oriented solutions to my problems - not just how to make the most obvious stuff into classes!


Keep in mind, I'm not new to programing. I'm two years into a collage degree in CS and have been programming as a hobby for many years! I'm 'just' stuck - and it's preventing me from creating any larger piece of software!

Sorry for the wall of text. Thanks, much appreciated Andreas

Head First Object-Oriented Analysis and Design

I love Head First Books because they are fun to read. They have exercises and puzzles to scratch your head. I've read this book and found it very good.

The book covers:

  • Use OO principles (encapsulation and delegation)
  • Open-Closed Principle (OCP)
  • The Single Responsibility Principle (SRP)
  • Design patterns, UML, Use cases etc.

I probably learned most about object oriented software development from Craig Larman´s Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

In his approach, classes are derived in a systematic way from use cases:

  • Nouns in the use cases are mapped to classes,
  • verbs to methods and
  • adjectives to member variables.

This, of course, works better for notions in the problem domain than, say, GUI widgets. Nevertheless, starting with a description/use case of the program to be written helped me to find better abstractions than when I omitted that step.

For me OO didn't 'click' until I read a book about design patterns. If you're already comfortable with concepts like abstract classes, interfaces, etc that's only half the battle.

The next step is figuring out why you should prefer composition over inheritance, how to code to an interface and how to write your classes so that they are decoupled and well-encapsulated. Design patterns show you solutions to common OO problems and help you structure your code adhering to the above guidelines.

I can't recommend any particular books about C++ but the GOF book is the standard on Design Patterns (Java). I prefer books that talk about design patterns in a particular language so that you can get concrete code examples. Design Patterns In Ruby is pretty good, as is PHP: Objects, Patterns and Practice.

I get the feeling that your instructor doesn't particularly know what he's talking about. 'More classes' is pretty useless advice by itself.

In my opinion, one of the the best books I've read for learning object oriented concepts is:

The Object-Oriented Thought Process

For me, this book really gets you thinking in an object oriented way (well, the clue's in the title! :) It's fairly language agnostic, containing some small code samples throughout the text in VB.NET, C# and Java and frequently references many "greats" in the world of OO analysis and design, like Grady Booch, Martin Fowler and others.

Since the book helps you to think in an object oriented way, it'll often take a specific example and show the differences between the OO way of approaching a problem and the procedural way. This can be a big help if you're coming from more or a procedural background. It also touches on things like UML to help explain and understand the design behind complete libraries of classes (e.g. frameworks) and the interaction between classes and also the design of rich class hierarchies using concepts such as aggregation and composition.

Peter Coad and Ed Yourdon wrote a book about it couple years ago. While not filled with new overhyped methdologies, this book provides good foundation for thinking in object style.

What would be a good/recommended way of tying up the Google+ api client life cycle with the flow of a multi-activity app? Make the activities depend on the onConnected api client method to trigger its functionality, use it as a one-time only "activation" thing, or maybe something else entirely?

I am currently struggling to understand how to correctly use the Google+ sign in in my Android app, which has more than one activity.

The idea is, in a first phase, to use the G+ sign in just to authenticate the user and be able to get her email, to send notifications and stuff like that. Eventually I plan to roll out other Google functionality like maybe Maps or other Google Play services, so I think it's useful to implement it already.

However, my app is not behaving as expected, and I have narrowed down the issue to the fact that I have not yet understood the G+ sign in app cycle when more than one activity is present.

What is the correct or recommended way to implement this auth method? is there maybe a pattern of sorts that could guide me in the right direction?

For example, I have found a very simple diagram of the life cycle of the api client, but how does this relate to the app flow?

Initially I have a Login Activity, where I put the sign in button. Following Google's guide I am able to sign in, and when the onConnected method is called, I start the Home Activity (kinda like the dashboard or main screen of the app).

This works somewhat. For example, what would be a good way of handling the onStart and onStop for each activity? should I re-connect and re-authenticate the api client every time for every activity? So maybe its a good idea to have a BaseActivity to implement all this.

Another issue is, should I use the same api client object and pass it around somehow, or maybe store it in the Base Activity class? or should I be creating and initializing a new api client object every time?

How about just using the Login Activity to authenticate with G+ and then just get the email and store it in a local database, and flag the user as "authenticated" or "active" or something. That would prevent me from having to re-authenticate every time the app is closed or connection is suspended, even allowing for some battery savings.

The app is not really using G+ posting or any other functionality like that. Ideally it should work well offline, and only need connection for stuff like initial authentication or other one-time only things.

Any suggestions or pointers in the right direction are very much appreciated.

Edit: I have read every guide and tutorial I could find, that uses Google+, and every one of them addresses this from a single activity perspective. I would think this is a common enough problem that it would benefit from a pattern or at least a general guideline.

0. TL;DR

For the impatient coder, a working version of the following implementation can be found on GitHub.

After rewriting the login activity code several times in many different apps, the easy (and not so elegant) solution was create the Google API client as a Application class object. But, since the connection state affect the UX flow, I never was happy about with this approach.

Reducing our problem only to the connection concept, we may consider that:

  1. It hides the Google API client.
  2. It has finite states.
  3. It is a (rather) unique.
  4. The current state affect the behavior of the app.

1. Proxy Pattern

Since the Connection encapsulates the GoogleApiClient, it will implement the ConnectionCallbacks and OnConnectionFailedListener:

public void onConnected(Bundle hint) {

public void onConnectionSuspended(int cause) {

public void onConnectionFailed(ConnectionResult result) {
    if (currentState.equals(State.CLOSED) && result.hasResolution()) {
        connectionResult = result;
    } else {

Activities can communicate to the Connection class through the methods connect, disconnect, and revoke, but their behaviors are decided by the current state. The following methods are required by the state machine:

protected void onSignIn() {
    if (!googleApiClient.isConnected() && !googleApiClient.isConnecting()) {

protected void onSignOut() {
    if (googleApiClient.isConnected()) {

protected void onSignUp() {
    Activity activity = activityWeakReference.get();
    try {
        connectionResult.startResolutionForResult(activity, REQUEST_CODE);
    } catch (IntentSender.SendIntentException e) {

protected void onRevoke() {
    googleApiClient =;

2. State Pattern

This is a behavioral pattern the allow an object to alter its behavior when its internal state changes. The GoF Design Patterns book describes how a TCP connection can be represent by this pattern (which is also our case).

A state from a state machine should be a singleton, and the easiest away of doing it in Java was to create Enum named State as follows:

public enum State {
        void connect(Connection connection) {
        void disconnect(Connection connection) {
    OPENING {},
    OPENED {
        void disconnect(Connection connection) {
        void revoke(Connection connection) {
    CLOSED {
        void connect(Connection connection) {

void connect(Connection connection) {}
void disconnect(Connection connection) {}
void revoke(Connection connection) {}

The Connection class holds the context, i.e. the current state, which defines how the Connection methods connect, disconnect, and revoke will behave:

public void connect() {

public void disconnect() {

public void revoke() {

private void changeState(State state) {
    currentState = state;

3. Singleton Pattern

Since there is not need to recreate this class repeatedly, we provide it as a singleton:

public static Connection getInstance(Activity activity) {
    if (null == sConnection) {
        sConnection = new Connection(activity);

    return sConnection;

public void onActivityResult(int result) {
    if (result == Activity.RESULT_OK) {
    } else {

private Connection(Activity activity) {
    activityWeakReference = new WeakReference<>(activity);

    googleApiClientBuilder = new GoogleApiClient
           .addApi(Plus.API, Plus.PlusOptions.builder().build())
           .addScope(new Scope("email"));

    googleApiClient =;
    currentState = State.CLOSED;

4. Observable Pattern

The Connection class extends Java Observable, so 1 or more activities can observe the state changes:

protected void onCreate(Bundle bundle) {
    connection = Connection.getInstance(this);

protected void onStart() {

protected void onDestroy() {

protected void onActivityResult(int request, int result, Intent data) {
    if (Connection.REQUEST_CODE == request) {

public void update(Observable observable, Object data) {
    if (observable != connection) {
    // Your presentation logic goes here...

I don't understand when I should use composite design pattern. What kinds of benefits will I get from this design pattern? I visited this website but it only tells me about the structure of the design pattern and not the scenarios in which it is used. I hope that it will be beneficial to the programmers like me who are starting to learn design pattern.

Quoting from Design Patterns,

Use the Composite pattern when

  • you want to represent part-whole hierarchies of objects.
  • you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

A common usage is the one used as a motivating example in the book, a display system of graphic windows which can contain other windows and graphic elements such as images, text. The composite can be composed at run-time, and the client code can manipulate all the elements without concern for which type it is for common operations such as drawing.

I've always been a largely independent learner gleaning what I can from Wikipedia and various books. However, I fear that I may have biased my self-education by inadvertent omission of topics and concepts. My goal is to teach myself the equivalent of an undergraduate degree in Computer Science from a top university (doesn't matter which one).

To that end, I've purchased and started reading a few academic textbooks:

As well as a few textbooks I have left over from classes I've taken at a mediocre-at-best state university:

My questions are:

  • What topics aren't covered by this collection?
  • Are there any books that are more rigorous or thorough (or even easier to read) than a book listed here?
  • Are there any books that are a waste of my time?
  • In what order should I read the books?
  • What does an MIT or Stanford (or UCB or CMU ...) undergrad learn that I might miss?

Software engineering books are welcome, but in the context of academic study only please. I'm aware of Code Complete and the Pragmatic Programmer, but I'm looking for a more theoretical approach. Thanks!

I think you can use most of the other books for reference and just absorb Programming Pearls in its entirety. Doing so would make you better than 90% of the programmers I've ever met.

The "Gang of Four" Design Patterns book. The Design Patterns course I took in college was probably the most beneficial class I've ever taken.

First, I wouldn't worry about it. But if you'd like a book to learn some of the abstract CS ideas, I'd recommend The Turing Omnibus or Theoretical Introduction to Programming.

If I were deciding between hiring two programmers and neither had much experience, but one had a CS degree and the other didn't, I'd hire the one with the CS degree. But when you get to comparing two programmers with a dozen years of experience, the degree hardly matters.

Even i'm in the same plane: studying computer science in my free time after work; These are some of the books i have in my shelf right now

  1. Applying UML and patterns - Larman
  2. Introduction to algorithms - Cormen
  3. Discrete mathematics and its applications - Rosen
  4. Software Engineering
  5. Advanced Programming in the UNIX Environment

Will udpate this list further as soon as i finish them... :-)

File Structures: An object oriented approach with C++

A lot of good info about block devices and file structuring which you won't find in any of the books you listed. It got a few critical reviews on Amazon because people didn't like his code examples, but the point of the book is to teach the concepts, not give cut and paste code examples.

Also make sure to get a book on compilers

Biggest two omissions I see:

For operating systems I prefer the Tanenbaum instead of the Silberschatz but both are good:

And about the order, that would depend on your interests. There aren't many prerequisites, automata for compilers is the most obvious one. First read the automata book and then the dragon one.

I don't know all the books you have, but the ones I know are good enough so that may mean the others are decent as well.

You are missing some logic and discrete math books as well.

And let's not forget some database theory books!

Related to this SO question (C state-machine design), could you SO folks share with me (and the community!) your Python state-machine design techniques?

Update3: At the moment, I am going for an engine based on the following:

class TrackInfoHandler(object):
    def __init__(self):

    ## ================================== Event callbacks

    def startElement(self, name, attrs):
        self._dispatch(("startElement", name, attrs))

    def characters(self, ch):

    def endElement(self, name):
        self._dispatch(("endElement", self._acc))

    ## ===================================
    def _missingState(self, _event):
        raise HandlerException("missing state(%s)" % self._state)

    def _dispatch(self, event):
        getattr(self, methodName, self._missingState)(event)

    ## =================================== State related callbacks

But I am sure there are tons of ways of going at it whilst leveraging Python's dynamic nature (e.g. dynamic dispatching).

Update2: I am after design techniques for the "engine" that receives the "events" and "dispatches" against those based on the "state" of the machine.

I don't really get the question. The State Design pattern is pretty clear. See the Design Patterns book.

class SuperState( object ):
    def someStatefulMethod( self ):
        raise NotImplementedError()
    def transitionRule( self, input ):
        raise NotImplementedError()

class SomeState( SuperState ):
    def someStatefulMethod( self ):
        actually do something()
    def transitionRule( self, input ):
        return NextState()

That's pretty common boilerplate, used in Java, C++, Python (and I'm sure other languages, also).

If your state transition rules happen to be trivial, there are some optimizations to push the transition rule itself into the superclass.

Note that we need to have forward references, so we refer to classes by name, and use eval to translate a class name to an actual class. The alternative is to make the transition rules instance variables instead of class variables and then create the instances after all the classes are defined.

class State( object ):
    def transitionRule( self, input ):
        return eval([input])()

class S1( State ): 
    map = { "input": "S2", "other": "S3" }
    pass # Overrides to state-specific methods

class S2( State ):
    map = { "foo": "S1", "bar": "S2" }

class S3( State ):
    map = { "quux": "S1" }

In some cases, your event isn't as simple as testing objects for equality, so a more general transition rule is to use a proper list of function-object pairs.

class State( object ):
    def transitionRule( self, input ):
        next_states = [ s for f,s in if f(input)  ]
        assert len(next_states) >= 1, "faulty transition rule"
        return eval(next_states[0])()

class S1( State ):
    map = [ (lambda x: x == "input", "S2"), (lambda x: x == "other", "S3" ) ]

class S2( State ):
    map = [ (lambda x: "bar" <= x <= "foo", "S3"), (lambda x: True, "S1") ]

Since the rules are evaluated sequentially, this allows a "default" rule.

Where did the idea of design patterns come from, who decided what is and isn't a pattern and gave them their names? Is there an official organisation that defines them, or do they exist through some community consensus?

There is no definitive list - for there to be one would most likely require some authority to declare whether a pattern is a pattern or just a ... something else.

Some patterns make sense only in a subset of languages - the canonical GOF book concentrates on Java (or is it C++? The book's on my desk at the office) and some of the patterns described aren't very relevant in, for example, Ruby or VB6. And vice versa of course.

There are a lot of books and online resources about Design Patterns. Although they are good to learn the main notion, without extensive experience it is really hard to remember tiny details of patterns. This makes harder to utilize patterns when faced with a problem. Having a design patterns cheat sheet may help developer to see big picture and to choose the patterns to delve into details.

UML represations and basic implementations of design patterns in different programmimg languages would be very beneficial.

Here some resources I have found on SO:

Do you know other useful resources?

The dofactory design patterns page is a pretty good free resource.

On a different note, the book Head First Design Patterns has a pretty good poster that we had hanging on the wall at a former workplace of mine.

The GoF Design Patterns Book have nice cheat sheets inside the front cover and back cover.

This is somewhat related to a similar post, but that post was Visual Studio 6 in general and a lot of the suggestions didn't apply to Visual Basic 6.0.

Suggest or vote for tools/tips. Please one tool/tip per post so that everyone can vote on them individually. Include a brief description of what the tools do.

Design Patterns by the GoF. While it doesn't seem specific for VB6 the fact that most of the patterns are based interface implementation and aggregating objects (as opposed to inheritance) makes it well suited for use with VB6. They talk about this on pages 16 to 18 and sum it up in one statement. Program to an interface, not an implmentation If there is one thing that VB6 and COM does well is handle interfaces.

The VB6 Credits Easter Egg that lists the development team :)

To show the VB6 Program Credits create an 'About' button to the standard toolbar and rename its caption to 'Show VB Credits'. Here's a bit more detail:

  1. Right-Click on a toolbar and select 'Customize'
  2. Within the 'Commands' tab select the 'Help' category
  3. Drag the 'About Microsoft Visual Basic' command (right windows of dialog box) up to the end of the standard toolbar.
  4. Without closing the 'Customize' dialog box, Right-Click on the button you just created and change its Name to 'Show VB Credits'
  5. Close 'Customize' and click the new button.

Bonus points for spotting famous names.

It may seem as if this is question is a dupe, but please bear with me - I promise I've read the related posts (and the GOF book).

After everything I've read, I still don't have it clear when to use an Abstract Factory, a Factory Method, or a Builder. I believe it will finally sink in after I see a simple example of a problem which is best approached by, say, a builder and it would be clearly silly to use, say, an abstract factory.

Can you provide a simple example where you would clearly use one pattern and not the others?

I understand it may boil down to a matter of opinion if the example is too simple, but I'm hopeful that if anybody can, that person is in SO.


A builder helps you construct a complex object. An example is the StringBuilder class (Java, C#), which builds the final string piece by piece. A better example is the UriComponentsBuilder in Spring, which helps you build a URI.

A factory method gives you a complete object in one shot (as opposed to the builder). A base class defines a single abstract method that returns an interface (or super class) reference, and defers the concrete creation of the object to subclasses.

An abstract factory is an interface (or abstract class) to create many different related objects. A good example (in .NET) is the DbProviderFactory class, that serves to create related objects (connections, commands, ...) to a given database provider (oracle, sql server, ...), depending on its concrete implementation.

I'm reading "Design Patterns: Elements of Reusable OOSW". In chapter two, the authors provide a case study of an editor they refer to as Lexi, which seems to be written in C++. I've looked around everywhere, but the only useful link I could find said this:

The Gof tell us in a note that Lexi is based on "Doc, a text editing application developed by Calder". But this paper only outlines an editor, without any source. And I even believe today that Lexi never truly existed as a program.

The link provides Delphi source. I'm after C++, cause that's what I'm comfortable with, and that's what's used in the book.

Does anybody know where I can find C++ source for Lexi? If the original never existed, it would be good to find something that I can use as a base. I really don't feel like writing my own text editor from scratch just so I can work through the case study in this book.

While designing my objects I find composition to be a better choice from the perspective of testability. The reason being, I can mock parts of the composition structure if I need to, while running unit tests. This is not possible if I have an inheritance hierarchy.

I would like to know if others have also found this to be a reason to prefer composition. Also what other testability pitfalls did you get into because inheritance was used?

The Gang of Four Design Patterns book is basically all about why to prefer composition over inheritance and offers many ways to do that. Some reasons:

  1. of classes increases the complexity of the code base

  2. In many newer languages, inheritance is limited to one class, while you can compose as much as you want
  3. Base classes cannot be changed at runtime (essentially the issue behind what you are running into).

I want to ask you to provide me with some articles (maybe books), which you possibly have found very convincing criticising the OOP methodology.

I have read some in the WWW on this topic and I didn't really find a 'definitive demotivator'.

It's not much about my personal attitude to the OOP, but I really would like to have something constructive, rigorous foundation for any kind of discussion and just abstract thinking.

You can post some original research too, but please be very constructive (as my personal request).

The Gideon Bible of object-oriented design patterns, aptly named Design Patterns. One of the best software design books I've ever read. has a great page on Object Oriented Programming.

Most of the page consists of humorous but not terribly informative quotes. However, at the bottom of the page are a number of links to articles challenging OOP. They are:

If you are interested in alternatives to Object-Oriented Programming:

  • From their 'about' page: hosts a series of sites dedicated to diverse subjects that share an idiosyncratic intellectual perspective, questioning orthodoxy and fomenting elitism and high standards in topics from software design to politics, passing by art and journalism and anything else interesting.

  • Structure and Interpretation of Computer Programs. Specifically teaches functional programming. Available free online here, for sale here. I cannot recommend this highly enough. It is absolutely revolutionary. It will change the way you think.

  • Any and all writings/videos/lectures by Rob Pike and Steve Yegge. Of particular interest is Yegge's Whirlwind Languages Tour.

I am mainly looking for good development practices specially when working in conjunction with mysql. I searched through the questions but could not find any related questions. I would appreciate if some one share their practices and wisdom gained through experience.

Apart from some coding standards, I am also looking for design standards and common architectural practices.

Background: I started my career with Java, and over the years I moved to C#/.NET space. I have been practicing architect for over 3 years now. Just added this to give some idea to people.

I would suggest that you familiarize yourself with the history of PHP, I know that doing so has given me a much greater appreciation of what PHP is today and where it has come from.

In short, PHP was written by Rasmus Lerdorf to provide simple wrapper functions for the C code that was actually doing the heavy-lifting so that he could have a simpler language / syntax for writing templates that needed to behave dynamically. The growth of PHP and the community which surrounds it is best described as organic. And much like other things that grow organically, its more than a little messy, asymmetrical, and downright non-congruent.

Once you understand PHP and its community, you need to embrace PHP for everything that it is and everything that it is not. This idea was best presented by Terry Chay in his article PHP without PHP. He's specifically talking about the concept of funky caching, but he captures the concept of coding for PHP as if it were PHP and not (insert favorite language here) better than anyone I've ever seen. In other words, don't try to make PHP into Java, C#, Ruby, etc because if you do you'll fail and you'll hate your life.

Take a look at How is PHP Done the Right Way?.

I must say that you must first, last, and always avoid the tendency of most beginning PHP developers to use the spaghetti-code anti-pattern. In other words, if you find that you're writing code that contains sql queries, manipulation of data, validation of data, and html output all in a single php script, then you're doing it wrong.

In order to avoid this, it will be helpful to learn something about the nature of web-oriented design patterns. This of course precludes a familiarity with object-oriented programming. But once you've learned the basics of object-oriented programming in PHP, study the MVC design pattern. You don't have to implement this exactly but using the basic ideas of Model-View-Controller will allow you to avoid the blob script problem that most newbies tend to create.

On this point, I would strongly recommend that you take any code snippets you find on the web with a grain of salt. And even if you find it in a book you'll have to consider how old the book is. PHP as a language has advanced quite a long ways and you can't just take code samples at face value because, depending on their age, they may be using workarounds that were valid in 3.x or 4.x but simply are no longer necessary with newer features.

One great thing to do is to study the various frameworks out there. Evaluate what you like and what you don't. Maybe even work up each of the quickstarts that are provided with the framework documentation so that you can start to get an idea of what you like and don't like. And I would strongly recommend that you review the code from the frameworks as well as several other open-source projects so that you can get a feel for how others do things in PHP. Again, take it all with a grain of salt because every PHP developer has their own pet peeves and nuances and none of us is right all the time. In fact, most of the time with PHP there are going to be several pretty good ways to do something.

If you want to get a better understanding of the patterns that are being implemented by the frameworks and are commonly thrown around in the common vernacular on SO, I would suggest that you read Fowler and GoF. They'll teach all about the basic design patterns you'll use in your development efforts.

Specifically watch for the following:

  • Function files that contain LOTS of functions. This is most likely representative of a need to either put functions directly in the scripts that need them or it may also indicate an opportunity to create some more generic functions that can be made to fulfill the roles of a couple of highly specific functions. Of course, if you're building cohesive, well-encapsulated classes you shouldn't run into this problem.
  • The do everything class. This is a blob anti-pattern and is really nasty. In this case you need to identify where cohesion and encapsulation are breaking down and use those points as opportunities to break up the class into several smaller, more maintainable classes.
  • SQL queries that don't use parameterized queries or at least escaped parameters. Very, very, very bad.
  • Any instance where validation is not being performed or is only performed client-side. When developing for the web, the only way to keep your site and your users safe is to assume that everyone else is a black hat.
  • A sudden obsessive desire to use a template engine. PHP is a templating language. Make certain that you have clear reasons for adding another layer onto your website before using a template engine.

For further reading please look at the following:

PHP Application Design Patterns
Defend PHP -- useful to give you an idea of the most common criticisms.
Security of strip_tags and mysqlirealescapestring
What should Every PHP Programmer Know
How to Structure an ORM
Best Way to Organize Class Hierarchy
Main Components / Layers of PHP App
Why use Framework for PHP
Recommended Security Training for PHP

I see the word thrown around often, and I may have used it myself in code and libraries over time, but I never really got it. In most write-ups I came across, they just went on expecting you to figure it out.

What is a Class Factory? Can someone explain the concept?

Heres's a little additional information that may help better understand some of the other technically correct, but shorter answers.

In the strictest sense a Class Factory is a function or method that creates or selects a class and returns it, based on some condition determined from input parameters or global context. This is required when the type of object needed can't be determined until runtime. Implementation can be done directly when classes are themselves objects in the language being used, such as Python.

Since the primary use of any class is to create instances of itself, in languages such as C++ where classes are not objects that can be passed around and manipulated, a similar result can often be achieved by simulating "virtual constructors", where you call a base-class constructor but get back an instance of some derived class. This must be simulated because constructors can't really be virtual in C++, which is why such object—not class—factories are usually implemented as standalone functions or static methods.

Virtual functions are normally resolved "late" by the actual type of object referenced, but in the case of constructors, the object doesn't exist yet, so the type must be determined by some other means.

The best implementations are those that handle new candidate classes automatically when they are added rather than having only a certain finite set currently hardcoded into the factory (although the trade-off is often acceptable if the factory is the only place requiring modification).

James Coplien's 1991 book Advanced C++: Programming Styles and Idioms has details on one way to implement such virtual generic constructors in C++. There are even better ways to do this using C++ templates, but that was not covered in the book which predates their being added to the standard language definition. In fact, C++ templates themselves are class factories since they instantiate a new class whenever they're used with different actual type argument(s). Update: I located a 1998 paper he wrote for EuroPLoP '98 titled C++ Idioms where, among other things, he revises and regroups the idioms in his book into design-pattern form à la the 1994 Design Patterns: Elements of Re-Usable Object-Oriented Software book.

See also the related answers here for the question Class factory in Python. Also see Abstract Factory, Template Style which is a 2001 Dr. Dobb's article also about implementing them with C++ Templates.

I've almost finished my Data Mapper, but now I'm at the point where it comes to relationships.

I will try to illustrate my ideas here. I wasn't able to find good articles / informations on this topic, so maybe I'm re-inventing the wheel (for sure I am, I could just use a big framework - but I want to learn by doing it).

1:1 Relationships

First, lets look at 1:1 relationships. In general, when we've got an domain class called "Company" and one called "Address", our Company class will have something like address_id. Lets say in most cases we just display a list of Companies, and the address is only needed when someone looks at the details. In that case, my Data Mapper (CompanyDataMapper) simply loads lazily, meaning it will just fetch that address_id from the database, but will not do a join to get the address data as well.

In general, I have an getter method for every Relationship. So in this case, there's an getAddress(Company companyObject) method. It takes an company object, looks for it's address property and - if it's NULL - fetches the corresponding Address object from the database, using the Mapper class for that Address object (AddressDataMapper), and assigns that address object to the address property of the specified company object.

Important: Is a Data Mapper allowed to use another Data Mapper?

Lets say in most cases you need both the company object AND the address object, because you always display it in a list all together. In this case, the CompanyDataMapper not only fetches company objects, but does an SQL query with JOIN to also get all the fields of the address object. Finally, it iterates over the record set and feeds new objects with their corresponding values, assigning the address object to the company object.

Sounds simple, so far.

1:n Relationships

How about these? The only difference to 1:1 is, that an Company may have multiple Address objects. Lets have a look: When we're most of the time only interested in the Company, the Data Mapper would just set the addresses property of the company object to NULL. The addresses property is an array which may reference none, one or multiple addresses. But we don't know yet, since we load lazily, so it's just NULL. But what, if we would need all the addresses in most cases as well? If we would display a big list with all companys together with all their addresses? In this case, things start to get really ugly. First, we can't join the address table fifty times for every address object (I strongly believe that's impossible, and if it is, performance would be below zero). So, when we think this further down the road, it's impossible to NOT load lazily in this case.

Important: Is this true? Must I send out 100 queries to get 100 address objects, if I have 10 companies with each 10 addresses?

m:n Relationships

Lets say an address object only contains the country, state, city, road and house number. But one house could be a big business tower with lots of companies in them. Like one of those modern office buildings where anyone can rent a small rom to show off that tower on its website. So: Many companies can share the same address.

I have no plans yet to deal with that kind of problem.

Important: Probably it's not a bigger problem than the 1:n Relationships?

If anyone knows a good ressource that goes into details about solving / implementing this, I would be happy about a link!

I am looking forward to any answers you'll get on this topic, but in the meantime why not just hop over to Amazon (or your local books dealer) and finally buy

These book contain the original patterns you have been pointed at in various of your questions and are considered reference works in Design Patterns and Software Architecture.

I will choose Java as an example, most people know it, though every other OO language was working as well.

Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.

However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.

Now there was this article, saying it's better to inherit interfaces than implementations, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the fragile base class problem. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.

What bugs me about this, is that implementation inheritance means code reuse, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?

E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.

How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?

Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.

Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like

public void move() {


Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?

You should read Design Patterns. You will find that Interfaces are critical to many types of useful Design Patterns. For example abstracting different types of network protocols will have the same interface (to the software calling it) but little code reuse because of different behaviors of each type of protocol.

For some algorithms are eye opening in showing how to put together the myriad elements of a programming to do some useful task. Design Patterns do the same for objects.Shows you how to combine objects in a way to perform a useful task.

Design Patterns by the Gang of Four

Possible Duplicate:
What C++ idioms should C++ programmers use?

After reading books like C++ Primer, Effective C++ and TC++PL I want to learn some important design patterns.

So, what are the famous design patterns that every C++ programmer should know?

I can solve the problem of adding functionality by adding sub classing then why should I use decorator pattern what's the real advantage of decorator pattern ?

The GoF Design Patterns book identifies two major advantages of using Decorators over subclassing:

  1. More flexibility than static inheritance. The Decorator pattern provides a more flexible way to add responsibilities to objects than can be had with static (multiple) inheritance. With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them. In contrast, inheritance requires creating a new class for each additional responsibility (e.g., BorderedScrollableTextView, BorderedTextView). This gives rise to many classes and increases the complexity of a system. Furthermore, providing different Decorator classes for a specific Component class lets you mix and match responsibilities.

    Decorators also make it easy to add a property twice. For example, to give a TextView a double border, simply attach two BorderDecorators. Inheriting from a Border class twice is error-prone at best.

  2. Avoids feature-laden classes high up in the hierarchy. Decorator offers a pay-as-you-go approach to adding responsibilities. Instead of trying to support all foreseeable features in a complex, customizable class, you can define a simple class and add functionality incrementally with Decorator objects. Functionality can be composed from simple pieces. As a result, an application needn't pay for features it doesn't use. It's also easy to define new kinds of Decorators independently from the classes of objects they extend, even for unforeseen extensions. Extending a complex class tends to expose details unrelated to the responsibilities you're adding.

From my point of view, preventing subclass explosion alone is quite compelling.

If you have a TextWindow to which you want to add horizontal scrolling, vertical scrolling, and borders all independently and optionally, using subclasses, you'd have to define subclasses for HorizontalScrollingTextWindow, VerticalScrollingTextWindow, HorizontalAndVerticalScrollingTextWindow, BorderedTextWindow, HorizontalScrollingBorderedTextWindow, VerticalScrollingBorderedTextWindow, HorizontalAndVerticaScrollingBorderedTextWindow, and more if you care about the order of scrolling and bordering.

With Decorators, you only need to define two scrolling decorators and one border decorator.

I'm developing an application in which i have integrated google plus. So far Its working fine, I am able to retrieve the user profile.

But now i want to do the following:

1)I have two activity signInActivity and shareActivity.

2)If user is already signin using signInActivity then it should not ask for signin again in shareActivity and should directly share the content.

3)If user is not signedin in the signInActivity and try to share data using shareActivitythen app should signin the user and then only share the data. In this case if user goes back to the signInActivity then app should show that "you have already signedin"

In short i want user signin to be Central within application so that if it is alrady signedin it should be accessible from any activity.

I have heard about the access token but i dont know how to use it and document says that it expires in an hour which is not what i want.

How can i make central google plus signin? is it possible? or i need to authenticate user in each activity?

0. TL;DR

For the impatient coder, a working version of the following implementation can be found on GitHub. This is the same answer written on another Stack Overflow post.

After rewriting the login activity code several times in many different apps, the easy (and not so elegant) solution was create the Google API client as a Application class object. But, since the connection state affect the UX flow, I never was happy about with this approach.

Reducing our problem only to the connection concept, we may consider that:

  1. It hides the Google API client.
  2. It has finite states.
  3. It is a (rather) unique.
  4. The current state affect the behavior of the app.

1. Proxy Pattern

Since the Connection encapsulates the GoogleApiClient, it will implement the ConnectionCallbacks and OnConnectionFailedListener:

public void onConnected(Bundle hint) {

public void onConnectionSuspended(int cause) {

public void onConnectionFailed(ConnectionResult result) {
    if (currentState.equals(State.CLOSED) && result.hasResolution()) {
        connectionResult = result;
    } else {

Activities can communicate to the Connection class through the methods connect, disconnect, and revoke, but their behaviors are decided by the current state. The following methods are required by the state machine:

protected void onSignIn() {
    if (!googleApiClient.isConnected() && !googleApiClient.isConnecting()) {

protected void onSignOut() {
    if (googleApiClient.isConnected()) {

protected void onSignUp() {
    Activity activity = activityWeakReference.get();
    try {
        connectionResult.startResolutionForResult(activity, REQUEST_CODE);
    } catch (IntentSender.SendIntentException e) {

protected void onRevoke() {
    googleApiClient =;

2. State Pattern

This is a behavioral pattern the allow an object to alter its behavior when its internal state changes. The GoF Design Patterns book describes how a TCP connection can be represent by this pattern (which is also our case).

A state from a state machine should be a singleton, and the easiest away of doing it in Java was to create Enum named State as follows:

public enum State {
        void connect(Connection connection) {
        void disconnect(Connection connection) {
    OPENING {},
    OPENED {
        void disconnect(Connection connection) {
        void revoke(Connection connection) {
    CLOSED {
        void connect(Connection connection) {

void connect(Connection connection) {}
void disconnect(Connection connection) {}
void revoke(Connection connection) {}

The Connection class holds the context, i.e. the current state, which defines how the Connection methods connect, disconnect, and revoke will behave:

public void connect() {

public void disconnect() {

public void revoke() {

private void changeState(State state) {
    currentState = state;

3. Singleton Pattern

Since there is not need to recreate this class repeatedly, we provide it as a singleton:

public static Connection getInstance(Activity activity) {
    if (null == sConnection) {
        sConnection = new Connection(activity);

    return sConnection;

public void onActivityResult(int result) {
    if (result == Activity.RESULT_OK) {
    } else {

private Connection(Activity activity) {
    activityWeakReference = new WeakReference<>(activity);

    googleApiClientBuilder = new GoogleApiClient
           .addApi(Plus.API, Plus.PlusOptions.builder().build())
           .addScope(new Scope("email"));

    googleApiClient =;
    currentState = State.CLOSED;

4. Observable Pattern

The Connection class extends Java Observable, so 1 or more activities can observe the state changes:

protected void onCreate(Bundle bundle) {
    connection = Connection.getInstance(this);

protected void onStart() {

protected void onDestroy() {

protected void onActivityResult(int request, int result, Intent data) {
    if (Connection.REQUEST_CODE == request) {

public void update(Observable observable, Object data) {
    if (observable != connection) {
    // Your presentation logic goes here...

I've been confused by what I've been reading during my research on the repository pattern. I'm wondering if folks are (incorrectly?) using that word when they simply mean a data access layer.

Since "repository" is not found in the index of Design Patterns (GoF), I've turned to Patterns of Enterprise Application Architecture (Fowler). Fowler seems pretty clear (page 323) when he states that clients create a criteria object and pass it to the repository to get the results. It looks something like this:

public class Person
    public List<Person> Dependents()
        Repository repository = Registry.personRepository();
        Criteria criteria = new Criteria();
        criteria.equal(Person.BENEFACTOR, this);
        return repository.matching(criteria);

Is the criteria object what makes the repository a repository? If not, what does? If abstracting the persistence mechanism (and therefore constructing queries) is the goal, in what way does the repository differ from a simpe DAL/ORM call like this:

public class PersonLogic
    public List<Person> GetDependents()
        IPersonData personData = DependencyContainer.Resolve<IPersonData>();
        return personData.GetDependents();

To me, the difference looks like this:
* With the repository pattern, the client constructs different criteria objects and calls the Matching() method on it.
* With the simple DAL, clients just call different methods based on what they want.

Is there more to it than this? Are programmers mistakenly using the term "repository" when they really mean DAL?


David Osborne sent this link to Persistence Patterns. It states:

Basically, the Repository pattern just means putting a façade over your persistence system so that you can shield the rest of your application code from having to know how persistence works.

That's really what a data access layer is. It really appears to me that a repository and a DAL are the same thing, and maybe a "true" repository uses the criteria object.

Take a look at the "Using the IQueryable interface" section and beyond at Extending and Enhancing the Orders and Registrations Bounded Context. It provides an insightful and balanced discussion of DAO/Repository implementations.

As subsequently highlighted by Bob Horn, the Persistence Patterns articles summarises that:

Basically, the Repository pattern just means putting a façade over your persistence system so that you can shield the rest of your application code from having to know how persistence works.

What do you see as the pros and cons of using callbacks for domain logic? (I'm talking in the context of Rails and/or Ruby projects.)

To start the discussion, I wanted to mention this quote from the Mongoid page on callbacks:

Using callbacks for domain logic is a bad design practice, and can lead to unexpected errors that are hard to debug when callbacks in the chain halt execution. It is our recommendation to only use them for cross-cutting concerns, like queueing up background jobs.

I would be interested to hear the argument or defense behind this claim. Is it intended to apply only to Mongo-backed applications? Or it is intended to apply across database technologies?

It would seem that The Ruby on Rails Guide to ActiveRecord Validations and Callbacks might disagree, at least when it comes to relational databases. Take this example:

class Order < ActiveRecord::Base
  before_save :normalize_card_number, :if => :paid_with_card?

In my opinion, this is a perfect example of a simple callback that implements domain logic. It seems quick and effective. If I was to take the Mongoid advice, where would this logic go instead?

I don't think the answer is all too complicated.

If you're intending to build a system with deterministic behavior, callbacks that deal with data-related things such as normalization are OK, callbacks that deal with business logic such as sending confirmation emails are not OK.

OOP was popularized with emergent behavior as a best practice1, and in my experience Rails seems to agree. Many people, including the guy who introduced MVC, think this causes unnecessary pain for applications where runtime behavior is deterministic and well known ahead of time.

If you agree with the practice of OO emergent behavior, then the active record pattern of coupling behavior to your data object graph isn't such a big deal. If (like me) you see/have felt the pain of understanding, debugging and modifying such emergent systems, you will want to do everything you can to make the behavior more deterministic.

Now, how does one design OO systems with the right balance of loose coupling and deterministic behavior? If you know the answer, write a book, I'll buy it! DCI, Domain-driven design, and more generally the GoF patterns are a start :-)

  1., "Where did we go wrong?". Not a primary source, but consistent with my general understanding and subjective experience of in-the-wild assumptions.

From a bookish perspective, you might say that x design pattern is applicable in y scenario, but I want to dig a little deeper here. So here are my queries:

  1. When do you first decide that you'll use design patterns? Do all of you decide upon design patterns before coding?
  2. Are there any DPs that you apply after you're done coding (small refactorings)? Do you apply DP while maintaining code?
  3. What are the design patterns that are predominantly applied during design?
  4. What are the DPs that you apply while tweaking/refactoring code?
  5. Are there any hints in code (technical not functional stuff) that suggest that you should apply a DP (like too many ifs, double dispatch, multithreading)? If so, could you name the DPs and their catchpoints?
  6. Do you use any Micro-DPs that makes you feel good about the code you've written (even though others hate you for it :p)?

I'd like to add that I read DPs through "Head First Design Patterns" and although it's one of the best books to understand the pattern. I don't think I've been able to transition the Pizza examples to real world scenarios.

I think this is one of the most influential books on DP but we can still have a book that may enumerate the various popular business scenarios that demand a particular pattern alongside that pattern. This knowledge is still implicit to a large extent I think. Such a book would be a very nice quick reference don't you think :))

Don't forget the book Design Patters, it may cover C++ but it doesn't matter, it's all patterns. Besides the book is very good.

And you don't learn patterns to implement them, that's the wrong way, you learn then so you can talk about code with other programmers. It's more a extension to your normal language then anything else. Use it in your code when needed, but not before :-)

Two good books which deal with the how and when (not) to use Design Patterns are:

I recently read an interesting comment on an OOP related question in which one user objected to creating a "Manager" class:

Please remove the word manager from your vocabulary when talking about class names. The name of the class should be descriptive of its' purpose. Manager is just another word for dumping ground. Any functionality will fit there. The word has been the cause of many extremely bad designs

This comment embodies my struggle to become a good object-oriented developer. I have been doing procedural code for a long time at an organization with only procedural coders. It seems like the main strategy behind the relatively little OO code we produce is to break the problem down into classes that are easily identifiable as discrete units and then put the left over/generalized bits in a "Manager" class.

How can I break my procedural habits (like the Manager class)? Most OO articles/books, etc. use examples of problems that are inherently easy to transform into object groups (e.g., Vehicle -> Car) and thus do not provide much guidance for breaking down more complex systems.

Becoming good at OO takes years of practice and study of good OO code, ideally with a mentor. Remember that OO is just one means to an end. That being said, here are some general guidelines that work for me:

  • Favor composition over inheritance. Read and re-read the first chapter of the GoF book.
  • Obey the Law of Demeter ("tell, don't ask")
  • Try to use inheritance only to achieve polymorphism. When you extend one class from another, do so with the idea that you'll be invoking the behavior of that class through a reference to the base class. ALL the public methods of the base class should make sense for the subclass.
  • Don't get hung up on modeling. Build a working prototype to inform your design.
  • Embrace refactoring. Read the first few chapters of Fowler's book.

Reading and then practicing OO principles is what works for me. Head First Object-Oriented Analysis & Design works you through examples to make a solution that is OO and then ways to make the solution better.

My eureka moment for understanding object-oriented design was when I read Eric Evans' book "Domain-Driven Design: Tackling Complexity in the Heart of Software". Or the "Domain Driven Design Quickly" mini-book (which is available online as a free PDF) if you are cheap or impatient. :)

Any time you have a "Manager" class or any static singleton instances, you are probably building a procedural design.

Is there a design pattern that deals with callback mechanism?

The Observer Pattern comes to mind.

One object (suscriber) can suscribe to another object (publisher). When the publisher changes or is updated, he can notify all his suscribers.

Depending on what language you are using, you can specify a function that should be called on notifies.

It is well described in Design Patterns: Elements of Reusable Object-Oriented Software [Gang of Four]

You often see that a new game will be released on Xbox 360, PS3 and Windows PC.

How do gaming companies do this? Is it a common source code compiled using different compilers? Are actual different source codes required?

example news article announcing this:

Not necessarily video game related, but the best walk through I've seen for doing multi-platform software was in GOF ( Read the case study on the windowing system.

I am planning to learn C# on the job - a moderately complex (2000 lines of code) project. I am interested in picking up "design patterns" along the way.

Can anyone suggest a book that doesn't assume too much of c# expertise and teaches design patterns? It's ok if the book is not devoted to design patterns (it could be one of the chapters).

An excellent book is Head First Design Patterns. Easy to understand and follow and a fun read.

The GoF book is where it all started, but I found it very dry and difficult to grasp. Not what I would recommend for learning.

Examples are in Java, but the concepts translate well.

You can even get C# examples.

Design patterns are actually language agnostic. They are not tied to a particular language. So for instance any design pattern that works with Java, will work for C# too.

Of course there are patterns which works with a particular language/technology such as MVVM, but I don't think you are writing in WPF or Silverlight, do you? For web you can choose to go with MVC instead of WebForms.

And about the books, you can take a look at

Because C# is a full OO language, you will have to adapt to OO design principles and patterns.

I agree with the other responses that design patterns are language agnostic. However, coming from a C# background, I have found the book Design Patterns in C# by Steven John Metsker to be a great read and would be relevant for you.

The obvious choice would be Design Patterns in C#, but I've not read it, so I can't comment on its quality.

Edit: As mentioned by Popo, the Design Patterns book itself is a great way to learn design patterns, but the code is not in C#: Design Patterns: Elements of Reusable Object-Oriented Software

There are several good books (some already mentioned) on design patterns. I actually have around four or so. When learning a pattern I like to read about it in more than one book. Usually the scenarios and examples will be a little different, which helps get the idea better. is a pretty good resource too.

That said, I like to spend some time reading code related to the patterns. Code that shows strengths of a platform is nice for obvious reasons. Check out while you are at it. If you want to see the GoF and other enterprise patterns applied to some real coding problems, then that site is excellent. You have to pay for the reference app and design patterns solutions, but there are examples related to the Head First book, the GoF work, and what they call optimized variations that leverage .NET.

Some books I found useful:

  • Head First Design Patterns: Great book for getting the ideas.
  • C# 3.0 Design Patterns (Judith Bishop) : Not my favorite for the code examples, but there are usually some nice points around comparing a pattern to other related patterns and why you might pick one over another.
  • Design Patterns (Christopher G. Lasater): A pretty good book that is straight to the point.

I code for a while now and learned several programming languages. I programmed a lot of little tools and such. I think I master the act of coding itself pretty good so I have e.g. no problems with syntax, I got a pretty good understanding of what is going on under the hood (reasonable assembler knowledge) and so on.

My big problem though is: I just can't design bigger/more complex applications. I learned the principles of OOP, design patterns, learned some basic lisp programming and all stuff I could find and thought it would help me with my issue.

But no matter what I try, how long I try: I just can't get it right. My designs always seem wrong to me somehow. Cause of that I never drawn through a bigger project, i'm kinda never satisfied with the structure of my program.

Have you had a similiar problem? How did you manage to solve it? Got you any hints for me on how to go on?

Design itself is an iterative activity. You first start with a certain design and then in phases you make it better.

Design is not about achiveing perfection, which can't even be achieved in larger application. Design is all about making good balances and tradeoffs that in the end provide a good, robust and maintainable application, that conforms to the requirements.

You will never get it 100% right on all sides.

Reading a few good books on design/architecture will not make you directly a rock star on the matter but it will certainly give you the tools that you can use to improve and perfect your skills.

Here are some examples of books:

Of course practical experience also counts.

I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable.

If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware.

Thanks Everyone!

Edit: How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.

I think they're comparable at this point. As a simple test, I doubt there's any pattern in Design Patterns or Patterns of Enterprise Application Architecture, arguably the two most influential books in OOP, that is impossible to implement in either language.

Both languages have come along by leaps and bounds since their infancies.

As far as multiple inheritance, it often creates more problems than it solves, and is, these days, commonly left out of languages as an intentional design decision.

I'm relatively new to .NET programming (and OOP in general) and I want to make sure I'm not developing bad beginner habits when designing my applications.

If you were hiring a new .NET developer and had to get him up to speed relatively quickly, but also wanted to make sure he adopts best practices (e.g., single responsibility principle, unit testing, separation of concerns), what would be your recommended learning path?

I've been listening to the Polymorphic Podcast lately and, while listening to discussion of best practices is helpful, I'm finding a lack of screencasts and code examples aimed at providing an introduction to these best practices.

I am helping a friend that is exactly in the situation you mention. He is a HW guy that used to work with C in the past.

I think the best approach is mentoring and coding. I explain him a few concepts and then ask him to program some code. We just built a simple calculator in multiple platforms (WCF, Silverlight, XNA,..) and using some well known patterns (state, MVP...).

I force him to use good programming practices and refactor the code by asking him new features based on his mistakes. For example if he coupled a couple components like the View and the Controller I would ask him for a new view... this obviously makes him to rewrite a bunch of code and he realizes there are better ways...

In this way he is the one coming up with the natural decoupling and what is more important the "why is good". I am very pleased with the results so far; he is very happy with unit testing and how it allows him to easily change the code for good.

IMHO separation of concerns and unit testing are better explained and understood by coding and having to implement new features; specially for new programmers. Once he buys in I would recommend him to read "Design Patterns" by the GOF or some of its simpler varians.

There are two separate, though related, goals:

  • To be a good OO developer


  • To be a good .NET Developer

Being excellent at the latter will require being at least good at the former, but both will require hard work. Don't get locked into the Microsoft mindset, or even a .NET one - you need to develop familiarity across a wide range of the field.

If you have the flexibility to do so, find yourself a job or a team where someone experienced is willing to do some mentoring.

Next, recognise that you'll need to do a lot of reading, both online and off. If your reading speed is average or lower (around 250 words per minute or less), then you should consider attending a training course on reading techniques. I've done a course with Write Group (New Zealand) and trebled my reading speed.

In terms of books, Object Thinking from the Microsoft Press would be a good starting point; I'd follow that with Programming .NET Components (Juval Lowy) and Smalltalk Best Practice patterns (Kent Beck), then The Pragmatic Programmer (Hunt and Thomas).

After that, trawl around (on StackOverflow or elsewhere) and find lists of recommended books and blogs. Keep reading - try to read a new book on a new topic at least every two months, if not monthly.

Just the other day I have seen code that uses the so called singleton pattern. Meaning something along the lines of

class MySingleton{
    void foo() { ... }
    static MySingleton&get_instance(){
        static MySingleton singleton;
        return singleton
    MySingleton(){ ... }
    ~MySingleton(){ ... }
    int bar;

I do see why one would want to do that:

  • Make the instance globally accessible.
  • Make sure that there is never more than one instance of that class.

However I do not see why this way of doing things is superior to a couple of free functions. The way I'd implement it is to put

namespace some_name{
    void foo();

in the header and

namespace some_name{
    void foo(){

in the implementation file. If I need initialization and/or cleanup I either add a couple of functions that must be explicitly called or I add

    class Dummy{
        Dummy(){ ... }
        ~Dummy(){ ... }

into the implementation file.

I know that this is from a semantic point of view a singleton, however I see the first variant used far more often in C++ Code than the second. Why? I consider the second version to be slightly superior, so I asking myself if I'm missing something obvious.

  • The second version is simpler to implement and less error prone. In the first variant the private copy constructor is missing on purpose to demonstrate this. In the second variant there is no way to do this error.
  • Implementation and interface are better separated in the second version. In the first all private members must be declared in the header. This has the advantage that you can rewrite the implementation from scratch and don't even need to recompile anything that uses the singleton. When using the first variant it is very likely that you have to recompile all user code even when only changing slight implementation details.
  • Implementation details are hidden in both cases. In the first variant using private and in the second variant using unnamed namespaces.

Can you please explain me why everybody uses the first variant? I don't see a single advantage over the good old way of doing things in C.

According to the party line (E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, Reading, MA, 1995, p. 128), the singleton offers the following advantages over the solution you propose.

  • You can refine the operations and the representation e.g. through subclassing.
  • You can change your mind at a later point and have multiple instances.
  • You can override the singleton's methods polymorphically.
  • You can configure your application at runtime by initializing the singleton instance with the class you need.

Having said that, in most cases I consider the additional complexity excessive and rarely use the pattern in the code I write. But I can see its value when you design an API that others will use.

Can someone illustrate what really is the difference between the two?

Here is GOF's answer:

Because patterns and frameworks have some similarities, people often wonder how or even if they differ. They are different in three major ways:

  • Design patterns are more abstract than frameworks. Frameworks can be embodied in code, but only examples of patterns can be embodied in code. A strength of frameworks is that they can be written down in programming languages and not only studied but executed and reused directly. In contrast, the design patterns in this book have to be implemented each time they're used. Design patterns also explain the intent, trade-offs, and consequences of a design.

  • Design patterns are smaller architectural elements than frameworks. A typical framework contains several design patterns, but the reverse is never true.

  • Design patterns are less specialized than frameworks. Frameworks always have a particular application domain. A graphical editor framework might be used in a factory simulation, but it won't be mistaken for a simulation framework. In contrast, the design patterns in this catalog can be used in nearly any kind of application. While more specialized design patterns than ours are certainly possible (say, design patterns for distributed systems or concurrent programming), even these wouldn't dictate an application architecture like a framework would.

I am going to be giving developers at my company a crash course on design patterns (after coming across some scary code recently).

One of the most important things I want to put across is that they save time in both the long and short term (which they really do!) - as developers here are put under quite a bit of time strain. All in all I need to demonstrate the every day benefits - things that will let them go home early.

Telling them that it might mean less bugs probably isn't going to hit home. I need stuff that is going to sink in.

I will probably do three to four sessions of an hour each. Do you guys have any suggestions on what to touch on/to do?

Head First Design Patterns would be a great place to start. It covers the mainstream design patterns.

Refactoring to Patterns might also be of interest.

If you can't buy a book for every developer, buy a few and spread them around.

You are in a unique position for a course-giver: you know the developers and you know the code that they are working with.

A possible approach would be to look at some of the scary code, and go along the lines of "How could we go about improving this? As it happens, there's a design pattern called Observer...."

This might end up being a mix of design patterns and refactoring. But that might be appropriate, given that you're trying to reach developers working on an existing code base.

Good opening slides for any education course in my opinion are:
1) Why are we here? (Where has the need for this course been identified?)
2) What do I expect to learn?
3) Who should take this course? (What are the intended students, prerequisites, etc?)
4) When can I apply what I’ve learned?
5) Expectations of you (Participation, homework, tests, minimum classes to attend, etc)

For design patterns I could expect several visual tools or "job aids".

I would follow a structure similar to the Elements of Reusable Object-Oriented Software book:

1) UML – Class Diagram Overview
2) OOP – Abstraction, Encapsulation, Polymorphism, Inheritance
3) Cohesion and Coupling
4) What is a design Pattern? – Pattern Name, The Problem, The solution, The consequences
5) Why are design patterns so hard to learn?
6) Why use design Patterns?
7) How to Select a Design Pattern
8) How to Use a Design Pattern
9) Cover various GoF design patterns with examples – Show examples of code before applying a design pattern, and how it looks after like Vince Huston does in his examples.
10) Conclusion

As already mentioned, design patterns are really ideas, so when teaching you must convey the idea. If they understand the problem, solution and consequences of the design pattern, then they will be far better off than trying to force patterns into the code (and that will become a nightmare). Recognition of where and what patterns (if any) can be applied is the real goal. The Huston examples are really good for putting out an example of code to the class and seeing if they can identify a pattern to improve it. Hope this helps.

I am still having trouble understanding what interfaces are good for. I read a few tutorials and I still don't know what they really are for other then "they make your classes keep promises" and "they help with multiple inheritance".

Thats about it. I still don't know when I would even use an interface in a real work example or even when to identify when to use it.

From my limited knowledge of interfaces they can help because if something implements it then you can just pass the interface in allowing to pass in like different classes without worrying about it not being the right parameter.

But I never know what the real point of this since they usually stop short at this point from showing what the code would do after it passes the interface and if they sort of do it it seems like they don't do anything useful that I could look at and go "wow they would help in a real world example".

So what I guess I am saying is I am trying to find a real world example where I can see interfaces in action.

I also don't understand that you can do like a reference to an object like this:

ICalculator myInterface = new JustSomeClass();

So now if I would go myInterface dot and intellisense would pull up I would only see the interface methods and not the other methods in JustSomeClass. So I don't see a point to this yet.

Also I started to do unit testing where they seem to love to use interfaces but I still don't understand why.

Like for instance this example:

public AuthenticationController(IFormsAuthentication formsAuth)
    FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

public class FormsAuthenticationWrapper : IFormsAuthentication
    public void SetAuthCookie(string userName, bool createPersistentCookie)
        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    public void SignOut()


public IFormsAuthentication FormsAuth

Like why bother making this interface? Why not just make FormsAuthenticationWrapper with the methods in it and call it a day? Why First make an interface then have the Wrapper implement the interface and then finally write the methods?

Then I don't get what the statement is really saying.

Like I know know that the statement is saying this

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

if formsAuth is null then make a new FormsAuthenticationWrapper and then assign it to the property that is an Interface.

I guess it goes back to the whole point of why the reference thing. Especially in this case since all the methods are exactly the same. The Wrapper does not have any new methods that the interface does not have and I am not sure but when you do this the methods are filled right(ie they have a body) they don't get converted to stubs because that would really seem pointless to me(it it would be converted back to an interface).

Then in the testing file they have:

var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>();

So they just pass in the FormsAuthentication what I am guessing makes all the fake stubs. I am guessing the wrapper class is used when the program is actually running since it has real methods that do something(like sign a person out).

But looking at new Mock(from moq) it accepts a class or an interface. Why not just again made the wrapper class put those methods in and then in the new Mock call that?

Would that not just make the stubs for you?


We use interfaces (or abstract base classes) to allow polymorphism, which is a very central concept in object-oriented programming. It allows us to compose behavior in very flexible ways. If you haven't already, you should read Design Patterns - it contains numerous examples of using interfaces.

In relation to Test Doubles (such as Mock objects), we use interfaces to be able to remove functionality that we currently don't want to test, or that can't work from within a unit testing framework.

Particularly when working with web development, a lot of the services that we rely on (such as the HTTP Context) isn't available when the code executes outside of the web context, but if we hide that functionality behind an interface, we can replace it with something else during testing.

I've been programming for around a year now, and all the stuff that I've written works - it's just extremely poorly written from my point of view. I'd like to know if there are any (free) good books on Software Design out there that can offer a little guidance to the beginning programmer? I don't think I'd have as many problems if I knew a little about the thought processes that go into software design.

Check out this book: Head First Design Patterns ...literally. Check it out. From the library.

Head First Design Patterns would be a good place to start for a beginner. It's probably easier to get into than the Gang of four book.

I would definitely add another book. I think that Clean Code by Bob Martin is a very good book to tell you how to write code that is maintainable. It introduces several easy rules that leads to code that is very well structured and readable.

Sounds like you want a book on design patterns.

Take a look at: Design Patterns - Elements of Reusable Object-Oriented Software. Warning it is not Python specific though.

You could also take at this online resource for Python design patterns.

Stackoverflow user @S.Lott also has a lot of really good Python resources that he wrote. You can see them on his Stackoverflow page.

Last week I interviewed for a position at a TripleA MMORPG game company here in NE. I didn't get the job but one of the areas that came up during the interview was the about the scalability of the code that you write and how it should be considered early on in the design of your architecture and classes.

Sadly to say I've never thought very much about the scalability of the .NET code that I've written (I work with single user desktop and mobile applications and our major concerns are usually with device memory and rates of data transmission). I'm interested in learning more about writing code that scales up well so it can handle a wide range of remote users in a client server environment, specifically MMORPGs.

Are there any books, web sites, best practices, etc. that could get me started researching this topic?

If you are looking for physical validation, what I usually find that helps is doing some prototyping. This gives you a good idea usually of any unforeseen problems that might be in your design and just how easy it is to add onto it. I would try to apply any design patterns possible to allow future scalability. Elements of Reusable Object-Oriented Software is a great reference for that. Here are some good examples that show before and after code using design patterns. This can help you visualize how design patterns could make your code more scalable as well. Here is an SO post about specific design patterns for software scalability.

I didn't find any question that would be this general.

Please post whatever you find to be a useful rule for oject-oriented design.

The best of OOP nothing, any approach that's fit for your project is best. But it is important what are OOP practices before choosing any/many from them for your project.

1: APIE: Abstraction, Polymorphism, Inheritance, Encapsulation.

2: SOLID Principle.

3: OO analysis and design.

4: Design patterns.

5: Code refactoring.

6: Effective Java.

I have recommended the Head First Design Patterns book many times.

It gives you a good intro to the GoF Design Patterns (a more advanced book that you also should read), but also a good intro to sound OOP design principles.

enter image description here

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.

This is what I understand about IDisposable and finalizers from "CLR via C#", "Effective C#" and other resources:

  • IDisposable is for cleaning up managed and unmanaged resources deterministically.
  • Classes that are responsible for unmanaged resources (e.g. file handles) should implement IDisposable and provide a finalizer to guarantee that they are cleaned up even if the client code does not call Dispose() on the instance.
  • Classes that are responsible for managed resources only should never implement a finalizer.
  • If you have a finalizer then you must implement IDisposable (this allows client code to do the right thing and call Dispose(), while the finalizer prevents leaking resources if they forget).

While I understand the reasoning for and agree with all of the above, there is one scenario where I think it makes sense to break these rules: a singleton class that is responsible for unmanaged resources (such as providing a single point of access to particular files).

I believe it is always wrong to have a Dispose() method on a singleton because the singleton instance should live for the life of the application and if any client code calls Dispose() then you are stuffed. However, you want a finalizer so that when the application is unloaded the finalizer can clean up the unmanaged resources.

So having a singleton class with a finalizer that does not implement IDisposable seems to me to be a reasonable thing to do, yet this type of design is counter to what I understand are best practices.

Is this a reasonable approach? If not, why not and what are the superior alternatives?

I'd first mention that Object Oriented design patterns and their consequences do not always influence every language decision, even in Object Oriented languages. You can certainly find classic design patterns that are easier to implement in one language (Smalltalk) as opposed to another (C++).

That being said, I'm not sure I agree with the premise that a singleton instance should only be disposed at the end of an application. Nothing in the design pattern descriptions that I've read for Singleton (or Design Patterns: Elements of reusable Object-Oriented Software) mention this as a property of this pattern. A singleton should ensure that only one instance of the class exists at any one moment in time; that does not imply that it must exist for as long as the application exists.

I have a feeling that in practice, many singletons do exist for most of the life of an application. However, consider an application that uses a TCP connection to communicate with a server, but can also exist in a disconnected mode. When connected, you would want a singleton to maintain the connection information and state of the connection. Once disconnected, you may want to keep that same singleton - or you may dispose of the singleton. While some may argue that it makes more sense to keep the singleton (and I may even be among them), there is nothing in the design pattern itself that precludes you from disposing of it - if a connection is remade, the singleton can be instantiated again, as no instance of it exists at that moment in time.

In other words, you can create scenarios where it is logical for singletons to have IDisposable.

If I have limited time, but I want to start learning a few design patterns, which ones should I learn first?

Your question is like asking, "I want to learn C# but only have time to learn a few keywords. Which ones should I learn?"

Any one design pattern doesn't live in a vacuum. They all define different aspects of how an application goes together. It's unlikely that any one app needs all of the known design patterns, but every app is different and you'll need a different combination of them for each app. Knowing what not to use is as important as knowing what to use. You need at least a conversational knowledge of all of the primary design patterns.

Start with this list and the Head First Design Patterns book previously mentioned here. Learn a little about all of them. And don't bellyache about not having the time--make the time! Stay outta FaceBook a couple of extra nights or skip a Star Trek rerun or two.

Also, avoid at first the GoF patterns book unless you are truly an OO guru. It is quite dense and immediately asssumes you understand the value and need for patterns. It's a great book, just not a great first book.

Design Patterns are not the sort of topic you quickly start reading and learning about. You will have to do many exercises and then apply what you've learned in real scenarios. If your time is really that limited then you might be wasting your time. I suggest the book Head First Design Patterns, which is excellent.

But your knowledge of OO should be at a fairly high standard to start with.

I have been working on some of the projects of my own and dont have any indrustial exposure. Currently i use simple approach for developing small applications with negligible OO approach like creating a common class for database functions using polymorphism of functions little bit use of constructors but i dont really able to think of how to implement whole project logic using OOP.

I know what are interface, abstract class, sealed classes and other oops concepts and very much clear picture in mind. But problem is that when and how should i implement OOP heavily where I should.

Do i need to study real time applications and their case studies, if so please refer me some sites or books/e-books from where i can read them and can be able to implement them.

Currently i feel myself incomplete while programming. I implement database and most of its components effeciently, but a kid while trying to use OOP.

I have read many examples that tries to make one understand OOP like shape eg, car eg. all these kind of. They r gud to clear concepts but not enough to implement in some live project

At first I would recommend this classic book on design patterns.

But in the end, all that really matters is working experience on big real-life projects! When you start working, and after a few years, everything will become much clearer.

In a C++ application, let's say I have a window class, which has several instances of a control class. If my window wanted to notify a control that it had been clicked, I might use:


Now let's say that the control needs to know the size of it's parent window, or some other information. For this I was considering giving the control a pointer to itself (this) as a parameter to it's constructor. I would then make a call like this from the controls onClick() method:

Size windowsize = parent->getSize();

Would this be considered bad practice, or in any other way contradict the values of object orientated programming? If so, what would he the 'proper' way of doing this?

As a side question, would it be better to have a vector of Class or Class*? Is it worth the added complexity for the speed gain? (Changes to the vector would be infrequent).

In fact the GOF Composite design pattern is based on Explicit Parent References.

Explicit parent references. Maintaining references from child components to their parent can simplify the traversal and management of a composite structure. The parent reference simplifies moving up the structure and deleting a component. Parent references also help support the Chain of Responsibility (223) pattern. The usual place to define the parent reference is in the Component class. Leaf and Composite classes can inherit the reference and the operations that manage it.

With parent references, it's essential to maintain the invariant that all children of a composite have as their parent the composite that in turn has them as children. The easiest way to ensure this is to change a component's parent only when it's being added or removed from a composite. If this can be implemented once in the Add and Remove operations of the Composite class, then it can be inherited by all the subclasses, and the invariant will be maintained automatically.

Therefore, I guess, there is a clear place for such a design, depending on the actual requirement and context.

I've been studying OOP for quite a while now and I have a good grasp of the theory. I read the Head First book on OOP and, while it reinforced a lot of the theory, I found the case studies to be somewhat trivial.

I find that I'm applying OOP principles to my code each day, but I'm not sure if I'm applying them correctly. I need to get to the point where I am able to look at my code and know whether I'm using inheritance appropriately, whether my object is cohesive enough, etc.

Does anyone have any good recommendations (books, online guides, blogs, walk-throughs, etc.) for taking the next step in developing solid OOP skills?

I am working primarily in .NET (visual basic), but I welcome suggestions that incorporate various platforms.

Consider looking into Design Patterns. Although it seems like they aren't commonly used in enterprise applications (I've seen them more commonly used in API's and Frameworks than embedded into enterprise code), they could be applied to make software simpler or more robust in a lot of situations if only developers knew how to apply them.

The key is to understand the design patterns first, then with experience you'll learn how to apply them.

There is a Head First book on design patterns that teaches the concept pretty simply, although if you want a book that really covers design patterns in detail, check out the Gang of Four design patterns book, which is basically what made design patterns mainstream and is referred to almost every time the topic is brought up.

Design patterns can be applied in pretty much any object-oriented language to some degree or another, although some patterns can be overkill or over engineering in some cases.

I also want to add, you should check out the book Code Complete 2. It's a very influential book in the world of software development. It covers a lot of different concepts and theories. I learn something new every time I read it. It's such a good book that if I read it every 6 months to a year, I look at it from a different perspective that makes me a better programmer just by re-reading it. No matter how much you might think you know, this book will make you realize just how little you really know. It's really a great book. I can't stress how much you should own this book.

Read Refactoring by Martin Fowler, and apply it to your own work.

It will take you through a litany of malodorous characteristics of software code that describe how to detect improperly constructed classes, and even more importantly, how to fix them.

I am currently half-way through the following book:

I cannot recommend this book strongly enough in terms of learning a real-life, professional-grade, practical approach to drafting and applying a well-formed and iterative design strategy before diving into code.

I, too, read the "Head First" book and felt that I was much better off for having read it.

After having a few years of working-world experience, I now view the Craig Larman book that I am recommending to be a perfect "next step" for me.

About the Presence of "UML" in this Book Title:

Whether you have positive feelings or negative feelings about UML notation, please do not let that influence your decision to buy the book (ISBN 0131489062) in either direction.

The prominence of "UML" in the title is misleading. While the author does use and explain UML notation, these explanations are extremely well-woven into relevant design discussions, and at no time does this book read like a boring UML spec.

In fact, here is a quote taken directly from the book:

What's important is knowing how to think and design in objects, which is a very different and much more valuable skill than knowing UML notation. While drawing a diagram, we need to answer key questions: What are the responsibilities of the object? Who does it collaborate with? What design patterns should be applied? Far more important than knowing the difference between UML 1.4 and 2.0 !

This book at times seems like it is "speaking to" a lead architect or a project manager. What I mean to say by that is that it assumes that the reader has significant control over the planning and direction of a software project.

Nonetheless, even if you are only responsible for some very small piece of your company's projects and products, I would still recommend this book and encourage you to apply some "scaled down" modifications of the book's advice to your piece of the project.

Tortoise HG is extrodanarily well designed piece of OO open source software (written in Python).

If you already understand the basics, building something from scratch in a fully object oriented language will be a good step in fully understanding OOP software architecture. If you don't know Python, Python Essential Reference will take you through the language in full in a few days to a week.

After you understand the language take a look through the software above and you'll have all sorts of epiphanies.

This is entirely a best practices type question, so the language is irrelevant. I understand the basic principles of MVC, and that there are different, subtle flavors of it (i.e. views having a direct reference to models vs. a data delegate off the controller).

My question is around cross MVC communication, when those MVCs are nested. An example of this would be a drawing program (like Paint or something). The Canvas itself could be an MVC, but so could each drawn entity (e.g. Shapes, Text). From a model perspective, it makes sense for the CanvasModel to have a collection of entities, but should the CanvasView and CanvasController have corresponding collections of entity views and controllers respectively?

Also, what's the best/cleanest way to add a new drawn entity? Say the user has the CircleTool active, they click in the Canvas view and start drawing the shape. The CanvasView could fire relevant mouse down/move/up events that the CanvasController could listen to. The controller could then basically proxy those events to the CircleTool (state pattern). On mouse down, the CircleTool would want to create a new Circle. Should the Tool create a new CircleEntityController outright and call something like canvasController.addEntity(circleController)? Where should the responsibility of creating the Circle's model and view then lie?

Sorry if these questions are somewhat nebulous :)


Here's a pseudo-codish example of what I'm talking about:

CircleTool {
    onCanvasMouseDown: function(x, y) {
        // should this tool/service create the new entity's model, view, and controller?
        var model = new CircleModel(x, y);
        var view = new CircleView(model);
        var controller = new CircleController(model, view);

        // should the canvasController's add method take in all 3 components
        // and then add them to their respective endpoints?
        this.canvasController.addEntity(model, view, controller);

CanvasController {
    addEntity: function(model, view, controller) {
        // this doesn't really feel right...

If I were you I would opt for Composite pattern when working with shapes. Regardless of whether you have circles, squares, rectangles, triangles, letters, etc, I would treat everything as a shape. Some shapes can be simple shapes like lines, other shapes can be more complex composite shapes like graphs, pie charts, etc. A good idea would be to define a base class that has a reference to basic shapes and to advanced (complex) shapes. Both basic shapes and advanced shapes are the same type of object, its just that advanced shapes can have children that help define this complex object.

By following this logic, you can use the logic where each shape draws itself and each shape knows its location, and based on that you would apply certain logic and algorithm to ask which shape was clicked and each shape could respond to your event.

According to the GoF book:


Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.


Graphics applications like drawing editors and schematic capture systems let users build complex diagrams out of simple components. The user can group components to form larger components. [...]

The key to composite pattern is an abstract class that represents both primitives and their containers. For the graphics system, this class is Graphics. Graphic declares operations like Draw that are specific to graphical objects. It also declares operations that all composite objects share, such as operations for accessing and managing its children.

Now, back to your problem. One of the base functions, as previously mentioned, is a Draw method. This method could be implemented as an abstract method in the base class with a following signature:

public virtual void Draw(YourDrawingCanvas canvas);

Each shape would implement it's own version of Draw. The argument that you pass them is a reference to the drawing canvas where each shape will draw itself. Each shape could store a reference of itself in its internal structure and it can be used to compare mouse click location with these coordinates to inform you which shape was clicked.

Wow, well I have perhaps a surprising answer to this question: I have a long-standing rant about how MVC is considered this beatific symbol of perfection in programming that no one sees any issues with. A favorite interview question is 'what are some problems, or challenges that you might encounter in MVC?' It's amazing how often the question is greeted with a puzzled, queasy look.

The answer is really quite simple: MVC relies on the notion of multiple consumers having their needs met from a single shared model object. Things really start to go to hell when the various views make different demands. There was an article a few years ago where the authors advanced the notion of Hierarchical MVC. Someone else came on in the comments and told them that what they thought they were inventing already existed: a pattern called Presentation-Abstraction-Controller (PAC). Probably the only place you see this in the pattern literature is in the Buschmann book, sometimes referred to as the Gang of Five, or POSA (Pattern-Oriented Software Architecture). Interestingly, whenever I explain PAC, I use a paint program as the perfect example.

The main difference is that in PAC, the presentation elements tend to have their own models, that's the A of the PAC: for each component, you don't have to, but can have an abstraction. Per some of the other responses here, then what happens is you have a coordinating controller, in this case, that would rule over the canvas. Let's say we want to add a small view to the side of the canvas that shows the count of various shapes (e.g. Squares 3, Circles 5, etc.). That controller would register with the coordinating controller to listen on a two events: elementAdded and elementRemoved. As it received each notification, it would simply update a map it had in its own Abstraction. Imagine how absurd it would be to alter a shared model that a bunch of components are using to add support for such a thing. Furthermore, the person who did the ShapesSummary component didn't have to learn about anything, but the event protocols, and of course all its interactions with collaborators are immutable.

The hierarchical part is that there can be layers of controllers in PAC: for instance, the coordinating one at the Canvas level would not know about any of the various components with specialized behaviors. We might make a shape that can contain other things, which would need logic for accepting drags, etc. That component would have its own Abstraction and Controller, and that Controller would coordinate its activities with the CanvasController, etc. It might even become necessary at some point for it to communicate with its contained components.

Here's the POSA Book.

I am very familiar with the Command pattern, but I don't yet understand the difference in theory between a Functor and a command. In particular, I am thinking of Java implementations. Both are basically programming "verbs" represented as objects. However, in the case of functors, as I have seen from some examples anonymous inner class implementations seem common. Can anyone out there clear this up for me nicely?

Here comes the answer from the GOF:

Coplien describes how to implement functors, objects that are functions, in C++ [Cop92]. He achieves a degree of transparency in their use by overloading the function call operator (operator()). The Command pattern is different; its focus is on maintaining a binding between a receiver and a function (i.e., action), not just maintaining a function.

I came across this problem via a colleague today. He had a design for a front end system which goes like this:

class LWindow
   //Interface for common methods to Windows

class LListBox : public LWindow
   //Do not override methods in LWindow.
   //Interface for List specific stuff

class LComboBox : public LWindow{} //So on

The Window system should work on multiple platforms. Suppose for the moment we target Windows and Linux. For Windows we have an implementation for the interface in LWindow. And we have multiple implementations for all the LListBoxes, LComboBoxes, etc. My reaction was to pass an LWindow*(Implementation object) to the base LWindow class so it can do this:

void LWindow::Move(int x, int y)
   p_Impl->Move(x, y);   //Impl is an LWindow*

And, do the same thing for implementation of LListBox and so on

The solution originally given was much different. It boiled down to this:

#define WindowsCommonImpl {//Set of overrides for LWindow methods}

class WinListBox : public LListBox
    WindowsCommonImpl     //The overrides for methods in LWindow will get pasted here.
    //LListBox overrides

//So on

Now, having read all about macros being evil and good design practices, I immediately was against this scheme. After all, it is code duplication in disguise. But I couldn't convince my colleague of that. And I was surprised that that was the case. So, I pose this question to you. What are the possible problems of the latter method? I'd like practical answers please. I need to convince someone who is very practical (and used to doing this sort of stuff. He mentioned that there's lots of macros in MFC!) that this is bad (and myself). Not teach him aesthetics. Further, is there anything wrong with what I proposed? If so, how do I improve it? Thanks.

EDIT: Please give me some reasons so I can feel good about myself supporting oop :(

Going for bounty. Please ask if you need any clarifications. I want to know arguments for and vs OOP against the macro :)

Does'nt answer your question directly may be, but can't help from telling you to Read up on the Bridge Design pattern in GOF. It's meant exactly for that.

Decouple an abstraction from its implementation so that the two can vary independently.

From what I can understand, you are already on the right path, other than the MACRO stuff.

My reaction was to pass an LWindow*(Implementation object) to the base LWindow class so it can do this:

I’ve almost 6 years of experience in application development using .net technologies. Over the years I have improved as a better OO programmer but when I see code written by other guys (especially the likes of Jeffrey Richter, Peter Golde, Ayende Rahien, Jeremy Miller etc), I feel there is a generation gap between mine and their designs. I usually design my classes on the fly with some help from tools like ReSharper for refactoring and code organization.

So, my question is “what does it takes to be a better OO programmer”. Is it

a) Experience

b) Books (reference please)

c) Process (tdd or uml)

d) patterns

e) anything else?

And how should one validate that the design is good, easy to understand and maintainable. As there are so many buzzwords in industry like dependency injection, IoC, MVC, MVP, etc where should one concentrate more in design. I feel abstraction is the key. What else?

To have your design reviewed by someone is quite important. To review and maintain legacy code helps you to realize what makes the software rotten. Thinking is also very important; One one hand don't rush into implementing the first idea. On the other hand, don't think everything at once. Do it iteratively.

Regular reading of books/articles, like Eric Evan's Model Driven Design, or learning new languages (Smalltalk, Self, Scala) that take different approach to OO, helps you to really understand.

Software, and OO, is all about abstractions, responsibilities, dependencies and duplication (or lack of it). Keep them on your mind on your journey, and your learning will be steady.

It takes being a better programmer to be a better OO programmer.

OO has been evolving over the years, and it has a lot to do with changing paradigms and technologies like n-tier architecture, garbage collection, Web Services, etc.. the kind of things you've already seen. There are fundamental principles such as maintainability, reusability, low coupling, KISS, DRY, Amdahl's law, etc. you have to learn, read, experience, and apply it yourself.

OO is not an end on its own, but rather a means to achieve programming solutions. Like games, sports, and arts, practices cannot be understood without principles; and principles cannot be understood without practices.

To be more specific, here are some of the skills that may make one a better programmer. Listen to the domain experts. Know how to write tests. Know how to design a GUI desktop software. Know how to persist data into database. Separate UI layer and logic layer. Know how to write a class that acts like a built-in class. Know how to write a graphical component that acts like a built-in component. Know how to design a client/server software. Know networking, security, concurrency, and reliability.

Design patterns, MVC, UML, Refactoring, TDD, etc. address many of the issues, often extending OO in creative ways. For example, to decouple UI layer dependencies from logic layer, an interface may be introduced to wrap the UI class. From pure object-oriented point of view, it may not make much sense, but it makes sense from the point of view of separation of UI layer and logic layer.

Finally, realizing the limitations of OO is important too. In modern application architecture, the purist data + logic view of OO doesn't always mesh very well. Data transfer object (Java, MS, Fowler) for example intentionally strips away logic part of the object to make it carry only the data. This way the object can turn itself into a binary data stream or XML/JSON. The logic part may be handled both at client and server side in some way.

Something that's worked for me is Reading. I just had a Bulb moment with this book... David West's Object Thinking which elaborates Alan Kay's comment of 'The object revolution has yet to happen'. OO is different things to different people.. couple that with with the fact that your tools influence how you go about solving a problem. So learn multiple languages.

Object Thinking David West

Personally I think understanding philosophy, principles and values behind a practice rather than mimic-ing a practice helps a lot.

Many years ago when I didn't know much about object oriented design I heard one guy said something like "How can you write a text editor without polymorphism?" I didn't know much about OOP and so I couldn't judge how wise that though was or ask any specific questions at that time.

Now, after many years of software development (mostly C++), I've used polymorphism many times to solve various problems when designing software. Yet I've never created text editors. So I still can't evaluate that guy's idea.

Is using polymorphism so essential for implementing a text editor in object-oriented languages and why?

Is using polymorphism so essential for implementing a text editor in object-oriented languages and why?

Depends on what kind of text editor you're talking about.

You can write notepad without OOP. But you most likely will need OOP for something like MS Word or OpenOffice.

Design Patterns: Elements of Reusable Object-Oriented Software uses text editor for examples (i.e. "case study") of Design Pattern application. You may want to check out the book.

Part of my project is write text editor that used for type some rule and my application compile and run it. Writing compiler was end and release beta version. In final version we must add undo and redo in text editor.I use file and save it periodically for text editor. How to design undo and redo to my text editor? What is change in structure of persistent of file?

Read a book Design Patterns: Elements of Reusable Object-Oriented Software. As far as I remember, there is a pretty good example.

I am on the quest to be a good OO-developer. OO intrigues me, because I understand the patterns, know why composition gives you more flexibility then inheritance, and more of such wisdom. However, I came to the conclusion that I know how to implement a factory of a singleton, but that I do not know how to come up with a robust OO design.

I have a bunch of books

  1. Design Patterns by the GoF
  2. AntiPatterns Brown et al.
  3. Refactoring by Fowler
  4. Code complete 2

They might be very good books, but they don't teach you to architect an application. I am often paralysed by some very basic decisions (example). I am looking for a book that teaches the when and why. There are many books about hammers and nails, but I have yet to find a book that tells you something about their practical relationship.

What book was most instrumental in making you a confident OO-architect/designer?

  1. "Object-oriented software construction" by Bertrand Meyer

Most fundamental work about object-orientation ever published. This is absolutely must have book for every "object-oriented" programmmer.

2. "Object-Oriented Analysis and Design with Applications" by Grady Booch et al

Not so formal as Meyer's book, but this book can open your eyes on many questions in object-oriented world and in software development in general

3. "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma et al.

This is famous "Gang of Four" book about design patterns

4. "Refactoring: Improving the Design of Existing Code" by Martin Fowler et al.

This is another classical book. First part perfectly describe many problem that modern software developer may faced during his work: code smells, readability vs performance, premature optimization drawbacks and many other topics.

5. "Thinking in Java" by Bruce Eckel

This book may help many beginners not only in Java language but in object-oriented way of thinking too.

6. "Touch of Class: Learning to Program Well with Objects and Contracts" by Bertrand Meyer

Excellent textbook by famous author.

Craig Larman's Applying UML and Patterns summarized a lot about what I had learned from experience. What I like about it is that it addresses all the aspects of software design -- which includes things like iterative design and development. Don't stare too hard at the use of UML: design descriptions are a means towards an end, and I found Larman's approach fairly pragmatic. You can't just code: you have to communicate your intentions (and understand what is needed). UML and cleanly designed, well commented code are some of the means towards that end.

And, of course, as others mention: no book will make you a good developer or designer. But it might help accelerate the process.

So, in reading this site, it seems that the shop in which I work does a lot of things wrong and some things right. How can I improve the code that I work with from my colleagues? The only thing I can think of is to lead by example - start using Boost, etc. Any other thoughts?

You probably have to look more closely at what it is your shop does wrong and what they do right. What can you actually change there? What can you change about your own practices that will improve your skills or that of your team? It can be difficult to realize change in an entrenched shop. Try proposing code reviews (on your code first), which could lead to discussion.

For tangible items, I'd look at Scott Meyers' Effective C++, etc. Develop your skillset and you will either help improve others around you or move on to a shop that will. Also, look at the Gang of Four's Design Patterns book.

I am a new to professional development. I mean I have only 5 months of professional development experience. Before that I have studied it by myself or at university. So I was looking over questions and found here a question about code quality. And I got a question related to it myself. How do I increase my code understanding/reading skills? Also will it improve the code quality I will write? Is there better code notation than Hungarian one? And is there any really good books for C++ design patterns(or the language doesn't matter?)? Thank you in advance answering these questions and helping me improving :)

P.S. - Also I have forgot to tell you that I am developing with C++ and C# languages.

How do I increase my code understanding/reading skills?

Read read read. Learn from your mistakes. Review answers on SO and elsewhere. When you can think back on a piece of code you wrote and go "aha! I should've done xyz instead!" then you're learning. Read a good book for your language of choice, get beyond the basics and understand more advanced concepts.

Then, apart from reading: write write write! Coding is like math: you won't fully grock it without actually solving problems. Glancing at a math problem's solution is different than getting out a blank piece of paper and solving it yourself.

If you can, do some pair programming too to see how others code and bounce ideas around.

Also will it improve the code quality I will write?

See above. As you progress you should get more efficient. It won't happen by reading a book on design patterns. It will happen by solving real world problems and understanding why what you read works.

Is there better code notation than Hungarian one?

It depends. Generally I avoid them and use descriptive names. The one exception where I might use Hungarian type of notations is for UI elements such as Windows Forms or ASP.NET controls, for example: using btn as a prefix for a Submit button (btnSubmit), txt for a TextBox (txtFirstName), and so on but it differs from project to project depending on approach and patterns utilized.

With regards to UI elements, some people like to keep things alphabetical and may append the control type at the end, so the previous examples become submitButton and firstNameTextBox, respectively. In Windows Forms many people name forms as frmMain, which is Hungarian, while others prefer naming it based on the application name or form purpose, such as MainForm, ReportForm, etc.

EDIT: be sure to check out the difference between Apps Hungarian and Systems Hungarian as mentioned by @Tobias Langner in a comment to an earlier response.

Pascal Case is generally used for method names, classes, and properties, where the first letter of each word is capitalized. For local variables Camel Case is typically used, where the first letter of the first word is lowercase and subsequent words have their first letters capitalized.

You can check out the naming conventions and more from the .NET Framework Design Guidelines. There is a book and some of it is on MSDN.

And is there any really good books for C++ design patterns(or the language doesn't matter?)?

Design patterns should be applicable to any language. Once you understand the concept and the reasoning behind that pattern's usefulness you should be able to apply it in your language of choice. Of course, don't approach everything with a "written in stone" attitude; the pattern is the goal, the implementation might differ slightly between languages depending on language features available to you. Take the Decorator pattern for example, and see how C# extension methods allow it to be implemented differently than without it.

Design Pattern books:

Head First Design Patterns - good beginner intro using Java but code is available for C++ and C# as a download (see "book code and downloads" section on the book's site)

Design Patterns: Elements of Reusable Object-Oriented Software - classic gang of four (GOF)

Patterns of Enterprise Application Architecture - Martin Fowler

If you're looking for best practices for quality coding in C++ and C# then look for the "Effective C++" and "More Effective C++" books (by Scott Meyers) and "Effective C#" and "More Effective C#" books (by Bill Wagner). They won't hold your hand along the way though, so you should have an understanding of the language in general. There are other books in the "Effective" series so make sure you see what's available for your languages.

I'm sure you can do a search here for other recommended reading so I'll stop here.

EDIT: added more details under the Hungarian Notation question.

I am very eager to learn in depth OOP concepts and most importantly how they can be applied in "real life". So far, I have read many references and many tutorials online but they all lack something: They do not provide a way to fully understand how object oriented programming can be truly used. In fact, it seems that most tutorial focus on OOP "syntax" as opposed to "the art of OOP design". Since OOP is a set of concept/idea/best practice in thinking about a problem and tackling that problem in a way to allow a better productivity I really want more. I want something to help me think as an "OOP designer" and not an "OOP programmer". Can someone provide with me a resource (preferably an online resource) that actually provides a non trivial example on how to apply OOP? Although I am aware that OOP is language agnostic, I would prefer examples in C#.

I have been working at a few different companies now and every one has different rules about how to name classes and packages. They each have different package layouts and workflow between classes. Through these experiences I have picked up an understanding of how to layout out a project; however, I would like a more concrete definition of how to layout a project. This question is more about uml than about naming conventions.

What I am curious is what are the official architecture definitions regarding the following (I have seen helpers used as utilities and managers used as helpers etc).

  • "class" helper
  • "class" utility
  • "class" factory
  • "class" manager
  • simple "class"
  • default "class"
  • my "class"

To be honest, I am not sure what you mean by most of these terms. If you are talking about design patterns then I believe the Gang of Four book (Design Patterns) has diagrams of each of the patterns that they use. If you are talking about something else, you might be overcomplicating things.

Also, where would you expect to get an "official" definition on terms that are not themselves official?

I'm kind of new to the design patterns concept.
C# is my primary programming language. (I use VB from time to time). I don't want to write sloppy code which is inflexible, not extendable and buggy.
Whenever I see a design pattern in action, I enjoy the logic behind it and understand it well, But unfortunately, I'm having trouble implementing them in my projects.

You see, there are a lot of design patterns (120+ I think) and I am sort of lost among them when I want to decide which one to use.
When it comes to use them in action, I have no idea what to choose.
All I get from tutorials are some fairly simple code snippets which is far away from the production environment. except DDD pattern which I have managed to learn it well since There are at least 2 good books and many resources about it.

Now my question:
Is there anywhere that I can find some real samples using various design patterns? At least some "more practical" samples. Do you know anywhere that I can find such books/samples/resources for other patterns as well?

I'd start with the Head First Design Patterns book. It's not nearly as complicated as some of the other books and is meant to be a learning experience instead of a reference.

Much better for learning from scratch in my opinion. Head First books are pretty good about presenting the material in interesting ways and do a nice job of keeping you interested. This book also tries to tie in each pattern to a pseudo real-life example. Their examples might not be pertinent to what you are working on, but they at least deal with the same types of issues as real world problems (I think the first example deals with writing a duck simulation video game).

Also Head First Design Patterns focuses on cramming your brain with as many patterns as possible so you can recognize when you are in a situation to use one and be well equipped enough to at least get started. This is where a specific reference, such as the GoF book might come in handy.

However, keep in mind that Head First books typically focus on complete beginners. Their books don't make for good learning materials after you reach the intermediate stage in a given topic.

I still feel like the original gang of four Design Patterns book is the best way to learn this. The focus isn't on using the pattern in a specific language, or a specific place, but really describing why the patterns exist.

Once you truly understand why the patterns exist (not just how they work), using them in your own production code comes naturally.

There are countless examples on the internet all you have to do is search. As far as books, I would recommend "Design Patterns: Elements of Reusable Object-Oriented Software"


Understanding of design patterns comes with time and experience. Unless you are very talented, in the beginning you'll probably write code that could be structured more efficiently and you wont even notice. Don't worry about that too much.

The thing with design patterns is learning to see their benefit. The particular shape of a pattern usually has very definite reasons. Learning to use a pattern is easy once you have figured out the reasons why organizing code that way is beneficial. Ask questions, set up hypotheses, experiment and see if you were right.

For reading, I'd suggest Design Patterns Explained and the SourceMaking site Matthieu suggested is also good.

I'm looking for project suggestions that would force me to "get my hands dirty" with advanced C++ features. I'm talking about projects that would utilize the full power of the language (STL or even boost (didn't use it much yet)).

Why? Because I want to learn, I want to find new challenges. At work, things start to be boring, really. I was used to constantly encountering new things, new ideas and features. This is most of the time not the case of legacy company code, as you can imagine. And still, looking at some questions and answers here that delve into the depths of templates, shared pointers and all that stuff I happen to find myself lost, not knowing the answer or even worse - not even understanding what's going on.

That's why I'm looking for something I could code myself, using preferably only C++ (+ boost perhaps) - a command line utility, no graphics please. And I really do not want to join any open source community. Looking at others' code is helpful, I know. But that's what I do at work a lot so... no thanks. The project can be anything, meaningful or meaningless, a useful utility or just something made up that has no real usage. The only requirement is, that it would force me to really test my C++ skills. Or at least it should be very difficult or even impossible to code with basic knowledge of C++ - I'm the kind of person who is never satisfied with code that just works, so I believe this will force me to learn. But bear in mind that I'm a working man and my time is limited, so answers like "code your own OS" really won't help much.

A fairly objective answer: I always thought that the most powerful thing about OO development was polymorphism. And the uses of it are best observed when dealing with Design Patterns.

So, I recommend getting the Design Pattern bible by GoF and writing code that uses it. The application? Can be any, as stated before, because nothing forces you to use any advanced features of anything whatsoever.

(want proof? some of the most complex systems in the world are written in COBOL by people with zero theoretical knowledge in CS)

I started a project a long time ago and created a Data Access Layer project in my solution but have never developed anything in it. What is the purpose of a data access layer? Are there any good sources that I could learn more about the Data Access Layer?

A data access layer is used to abstract away the storage and retrieval of data from its representation. You can read more about this kind of abstraction in 1994's Design Patterns

Recently I came about this concept of Design Patterns, and felt really enthusiastic about it. Can you guys suggest some resources that help me dive into Design Patterns?

You know, for me, one of the best books out there is Head First Design Patterns. I personally like the style that they use to communicate the material.

The gang of four design patterns book is the standard. I recommend it if you're comfortable with C++.

Head first design patterns is good too, especially if you like visual aids and want to feel like you're learning design patterns in a '50s diner. Examples are in Java.

There are sometimes multiple ways to implement patterns in a given programming language (for example see this discussion of options for implementing the Singleton pattern in C#), so it might be worth getting one book to succinctly describe the common patterns, and another to suggest the best way to implement them in your favorite language.

Martin Fowler's website has plenty of information: Much of this is covered also in his book, Patterns of Enterprise Application Architecture.

I find Design Patterns Explained to be a good introductory text. The Gang of Four book is a reference for those who already understand patterns.

Wikipedia, the Gang of Four book, and if you're specifically interested in C# implementations there's a decent site here.

I find that whenever I begin writing an app in Java/C#, things start off good, but over time, as the app becomes more complex, it just gets more and more complicated. I've become aware of the fact that I'm not very good at design and high level architecture. All my classes become fairly strongly coupled and the design isn't "elegant" at all. I'm fairly competent at "low level" programming. That is, I can get just about anything done within a function or a class, but my high level design is weak and I'd really like to improve it. Does anyone have pointers to techniques, books, etc. that would be helpful in making me a better software engineer?

The answer to your question could fill a book on its own, but I'd suggest you take a look at design patterns.

The classic book on the subject is referred to as the "Gang of Four" book:

Gang of Four Design Patterns Book

Martin Fowler is also highly regarded in the field.

I disagree about starting with a book on design patterns or refactoring.

In my opinion, for a solid OO design, you should first be familiar with the main OO design principles, then understand how your problem can be represented in those basic principles. Then you can start discovering opportunities for applying design patterns and refactoring techniques in order to achieve those fundamental principles.

I would start with this book:

Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin

In this book, Robert Martin describes the fundamental principles that make a good OO design, all of them related to encapsulation, coupling and modularity:

  • The Open/Closed Principle
  • Liskov Substitution
  • Dependency Inversion
  • Granularity
  • Common Closure
  • Reuse
  • No Cyclic Dependency
  • Stability Of Dependency
  • Abstraction And Stability

After all, almost every Design Pattern and Refactoring technique I have seen documented in GoF and Fowler is aimed at achieving one of several of these basic principles, depending on their relative priority for a given scenario.

Obviously, reading some of the recommmended books will help. I think Head First Design Patterns is definitely less abstract than GoF book.

The primary question I ask is "Is this code doing something very specific that could be re-used anywhwere else?" If so, put in in a class in an assembly that allows for re-use.

If you truly are just starting then one thing I used to do was to consider each database table an 'object'. So each database table represents a class. The purists will tell you this is a disaster, but I found it a good way to get myself started thinking in object terms.

I have been learning more and more javascript; it's a necessity at my job. We have a web application that uses a lot of javascript and I will be doing more and more every day. I have read bits and pieces about design patterns, but was wondering if someone could just give me a cut and dry example and definition. Are they something that would benefit me? Or is it more high level?

As design patterns are language agnostic, I would recommend reading one of the classic books on the subject. My favourites are:

However, these aren't beginner books by any means and you might get more value out of some of the many web resources and tutorials out there (Wikipedia has some reasonable explanations).

My own experience is that the object model in javascript is a bit trickier to understand than others such as PHP or Ruby and hence, applying design patterns isn't always that easy. Libraries such as Prototype provide functions for making inheritance easier to work with and this makes programming Javascript in an OO way much easier.

I recently used Javascript to implement the Active Record pattern using Prototype, which you can read about more about here if you want:

Is there a resource that defines and gives guidance to naming objects in software? For instance, when to call something a service vs a handler? When to include nouns or verbs in the name.

I'm looking for something definitive to settle arguments and provide guidelines for my team.

The classical book on Design Patterns from the GoF is quite useful for this:

  • It gives design-related naming conventions (which is one of the largest benefits of patterns),
  • but also lists a lot of other good concepts, names and definitions (e.g. framework vs. toolkit).
  • Since it's a classic, it does set a standard (naming convention) that is either understood or can be looked up.

I've read Head First Java, and I understand how OOP works. Here's my problem: I'm a PHP programmer, and while I've used OOP in PHP, I'm having trouble figuring out what should be an object and what methods to give it.

For example, let's say I have a app that allows people to log in and edit a document. Why should the document be an object if there will ever only be one instance? Should I give the deleteDocument() method to the document object or the admin object? The document is the one being deleted, but the admin is the one performing the action.

So my real question is, coming from a procedural background, how do I figure out what should be objects and what should have what methods?

There's no answer that always holds. If you're interested in object-oriented design, I recommend this book.

As for your question of how to figure out what should be objects and what methods they should have, a good heuristic is to ask yourself if having some ability is essential to being some thing. Here's an example I remember from my OOP class... You're keeping track of people and pets in an application. Should the person class have a getPets() method? Well, is having a pet essential to being a person? No. A better solution might be to have a separate relationship class representing the pet ownership.

or the other way around?

I use generic lists all the time. But I hear occasionally about IEnumerables, too, and I honestly have no clue (today) what they are for and why I should use them. So, at the risk of having something on the net forever more proclaiming my ignorance, I humbly post this question.

John Skeet and others have offered a good synopsis of the functionality of List over IEnumerable, so I thought I'd fill in the other half of the question which is "What are the benefits of using IEnumerable over List?".

First, IEnumerable provides a more generic contract for representing a collection of things you can iterate over and therefore allows you to adhere to the Principle of Least Privilege. In other words, IEnumerable should be preferred over its derived types where enumeration is the only behavior that needs to be exposed for the task at hand. This is beneficial because exposing information and/or behavior unnecessarily opens your API up to possible unintended usages which can pose a security issue or can cause unintended coupling between your API and its consumers.

Second, IEnumerable is an abstraction for enumeration whereas List is one implementation of that abstraction. Following the guidance of Design Patterns - Elements of Reusable Object-Oriented Software, programming to abstractions over implementations aids in making applications more resilient to change by allowing implementations to be changed later without impacting consuming code. If you do need list behavior, you should expose IList rather than List directly.

What is the difference between Builder Pattern and Flyweight Pattern in terms of usage, as both of them deals with large number of objects?

The Builder pattern is used to create many objects, whereby the Flyweight pattern is about sharing such a collection of objects.

These two patterns both deal with "composites", i.e. objects that may have several elements, but they don't need to be used together at all. The archetype use case for Flyweight is where a pool of a few dozen characters objects are used over and over in a text editor application (this is the example given in the "GoF" book)


Moving from a .NET / SQL Developer role to a more of an architect one. Can anyone reccomend any good books for modern Software Architecture in enterprise?

Appreciate your help.



Domain Driven Design by Eric Evans.

I am a developer having 4 years of .Net coding experience, And never cared much about design patterns in my carreer. Recently i have been called for an interview with one of the biggies in the IT, have done 5 rounds (problem solving, pair prograaming , logical reasoning, 2 rounds of tech interview) of interview and didnt offer a job.

The feedback i got from them is am not good at design principles though they are satisfied with my technical & logical reasoning skills. This one made me think that knowing design patterns are the only way to solve the problems?

Though i never used much of a design patterns in my coding, i always tried to implelement the basic principles of OOPS

I could use these principles to design a system thats loosely coupled and open for enhancements and easy to maintain. Eventtually these are the core constructs of all the design patterns.

But my problem is to find a right pattern for the right problem. I know this knowledge will not come by just reading all the books published in design patterns and practises. this knowledge comes with the experience of building different systems.

Is there any use cases available for the pattern-problem matching.. And your suggestion on learning design principles?


Try this book, it is funny and gives you not only how to implement the pattern, also when to do it.

Even though you use C#, I'd suggest going through some of the books on patterns. First would be the GoF book - Design Pattens. Then try reading some book on Enterprise Design Patterns. As you read, you'll recognize (or see) the Pattern. This is generally an "Aha" moment.

You'll also recognize the same from your own code. Knowing patterns will help you in good designing. It helps in knowing the patterns as you'll immediately recall the pattern when a problem related to it arises.

The programming principles you specified are good and DO follow them. However they are more at a class level. Moving higher up to the System design, Patterns will be more helpful.

Most importantly - Patterns give you a vocabulary to discuss design ideas with whole team.

I have this code

class Duck {
  protected $strVocabulary;
  public function Learn() {
   $this->strVocabulary = 'quack';

  public function Quack() {
   echo $this->strVocabulary;

The code is in PHP but the question is not PHP dependent. Before it knows to Quack a duck has to Learn.

My question is: How do I make Quack() invokable only after Learn() has been called?

No, that does not violate any OOP principle.

A prominent example is an object who's behavior depends on whether a connection is established or not (e.g. function doNetworkStuff() depends on openConnection()).

In Java, there is even a typestate checker, which performs such checks (whether Duck can already Quack()) at compile time. I often have such dependencies as preconditions for interfaces, and use a forwarding class whose sole purpose is protocolling and checking the state of the object it forwards to, i.e. protocol which functions have been called on the object, and throw exceptions (e.g. InvalidStateException) when the preconditions are not met.

A design pattern that handles this is state: It allows an object to alter its behavior when its internal state changes. The object will appear to change its class. The design pattern book from the Gang of Four also uses the example above of a network connection either being established or not.

I understand procedural programming (well, who doesnt) and want to get a good understanding of OOP and after that functional. I'm just a hobbyist so it will take me an age and a day, but its fun.

Does anyone have any ideas for what I can do to help? Project ideas? Example well documented code thats out their?

I am currently using C++ but C# looks a lot nicer to work with.

I'd recommend working mainly with a strongly-typed language like C# or Java, as so many of the design patterns and general OOP principles are geared towards strong typing (GOF, Refactoring, Uncle Bob). Ruby is wonderful but a lot of common OOP principles like coding to interfaces won't apply.

Spend some time with Uncle Bob's SOLID principles. Go slowly, paying particular attention to Single Responsibility. If you don't get anything else from Uncle Bob, get SRP in your head and apply it early and often.

I also like Uncle Bob's idea of code katas. I'd recommend working through the bowling game kata.

There are some great OOP books from Head First covering Object-Oriented Analysis and Design and Object-Oriented Design Patterns.

I recommend you read Object Thinking by David West. There is very little code in the book, but a lot of talk about how to model.

A couple things I wish someone would have told me when I was starting out are:

  1. When modeling objects, you should focus on behaviors more than the shape of the data.
  2. Although many OO tutorials model real world things such as animals and vehicles, many of the things we model in OO software are concepts and constructs (things that have no physical representation in the real world).

I want to isolate database code from GUI design. For a reasonable time I've been reading/searching/skimming on topics like mgm/mvp/mvc/persistence/objects etc. I really have difficulty in designing a reusable object hierarchy/framework. Delphi is a great tool for RAD but when you want to work things out in a different way the documentation seems ineffective. I want to develop some king of persistence for data access and wiring data into an object/object list easily. And to integrate data display in a versatile manner (using existing components dbaware or not, create export/import routines for multiple formats). Where should I start? Do you know any tutorials with code? For example mastapp demo included in Delphi installation is a great source for RAD-way as a startup. I need the equivalent in OOP :) with comments & tutorial

As Dispatcher stated, this is a lot of work, but it pays off in the end. I strongly suggest looking at more than one of the existing systems. Don't just settle on the first one you find. Try to understand how they work and how well your vision of your program matches the concepts of the framework.

Get a few good books on patterns. You will find them invaluable as you continue down this path and will be referenced often. I suggest GOF for the basics, and Patterns of Enterprise Application Architecture for the database object model side of things. Most of the concepts in these libraries are based on the patterns discussed in these books.

I will like to see if everybody could share any good training sources on OOP on PHP language.

Good Training Sources for OOP (Object Oriented Programming) PHP, anyone ?

I've seen numerous tutorials, mostly superficial, some of them bad.

Please share anything good either commercial or free, Video or Written.

It's a bit more on the advanced side of OOP, since it's about design patterns, but I really like Martin Fowler's Patterns of Enterprise Application Architecture ( And you can never go wrong with the Gang of Four's pattern book (

The nice thing about learning patterns is that they're language agnostic. Learn a pattern, use it in (almost) any language :)

Many people say they are using factory pattern in their project. But when i actually see their implementation it looks totally different from definition what i have read in head first book. In the book they have described two kind of factory pattern i.e

Factory Method:- A class specifies its sub-classes to specify which objects to create based on some parameter. So we expect here some abstract method in base class whihich will be implemented by child class and pupose of that will be to create some object

Abstract Factory:- Provides an factory (in form of interface or abstract factory)for creating families of related or dependent objects without specifying their concrete classes.

I have a question here on what do they mean by family of dependent or related objects. Lets refer to As per my understanding it means that in FinancialToolsFactory (in the link) is able to create TaxProcessor which is a family of products where actuall concreate products are CanadaTaxProcessor and EuropeTaxProcessor . So here we will have n number of concrete factories(in this case CanadaFinancialToolsFactory and EuropeFinancialToolsFactory) which will be extending/implementing abstract factory in this case FinancialToolsFactory.

Please let me know if above understanding is correct as i think its the crux of Factory pattern.

Second question:

What people are doing on the name of factory pattern is below:

public class MyFactory
    public static <T> T getObject(Class<T> cls)
        if (cls == null)
            throw new IllegalArgumentException("Invalid className");

        T daoObject = (T)map.get(cls);

        if (daoObject == null)
            daoObject = loadObject(cls);

        return daoObject;

They are just passing class like Example.class from main method and getting the object instance for that specific class. Now if we go by actual concept of factory pattern which is described in beginning(from head first book) and other websites it does not follow any of the two factory patterns. To me it looks like a utility class where we are passing the class and getting the object instance. Please let me know if you folks agree with this?

what do they mean by family of dependent or related objects

Using an example from Design Patterns by the Gang of Four:

  • AbstractFactory (WidgetFactory)
  • ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
  • AbstractProduct (Window, ScrollBar)
  • ConcreteProduct (MotifWindow, MotifScrollBar, PMWindow, PMScrollBar)

public abstract class WidgetFactory {...}

public class MotifWidgetFactory extends WidgetFactory {...}

public class PMWidgetFactory extends WidgetFactory {...}

Let's start with the MotifWidgetFactory. It will produce a family of concrete products that extend or implement the abstract products. Since they are all built by the same factory, they play nice together. You cannot make a PMScrollBar work with a MotifWindow.

What people are doing on the name of factory pattern is looks like a utility class where we are passing the class and getting the object instance.

Your example is a factory in that it produces an object. In this case, retrieving a singleton from a Map. It does not follow the "Factory Method" or "Abstract Factory" patterns and is therefore only a factory in name.

The several uses to which the <title> tag is put complicates the question…

  • As browser window or search result titles, it would seem to make little difference — there's enough room for everything and the display order is unrelated to the title.

  • For tab and taskbar / dock titles, space is at more of a premium. Placing the page name first makes it easier to distinguish between multiple pages on the same site, but if the page names are generic ("Search Results", "Intro to CSS"), it may be more important to distinguish between sites rather than between pages.

  • In bookmark titles, having the site name first will both make them easier to find and allow you to group them by doing a simple sort, but users can easily alter the title to their liking (and often do), making the provided "default" title less critical.

What other factors should be considered? Is there a commonly-accepted "best practice"?

Interestingly, Jakob Nielsen recently (March 2008) posted an "update" to his classic usability guidelines, listing some situations in which he now considers it a better idea to put the site name on the <title> tag before the specific page name / page content.


Start search engine links with your company name when both of the following conditions hold:

  • The link appears as a hit for queries that typically produce a SERP (search engine results page) that's full of junk links.

  • You have a widely recognized and well-respected company name.


Note that this new guideline applies only to the links that appear in external search engines, such as the GYM (Google, Yahoo, Microsoft). is currently doing this. For example, the title of the page for the classic "Gang of Four" design patterns book is " Design Patterns: Elements of Reusable Object-Oriented Software":

If I want to allocate millions of objects of a class Foo, and I want to be memory- and time-efficient, how should I design the Foo class?

Obviously, Foo should not contain much member data.

Also, I guess, it should not use virtual functions?

And how costly is it for Foo to derive from a Base class? And from several Base classes?

Are there any other tips for making millions of Foo objects very efficient?

Have a look at the Flyweight pattern. The GoF book does a much better job than Wikipedia at explaining the pattern, though.

I'm a huge fan of the classic Design Patterns book. I very diligently worked to learn most patterns and how they are used (and when they should be avoided). However, I frequently encounter teams where I am the only one touting the book on a regular basis. I was hoping that learning this book would make it easier to explain concepts to other developers, but most have yet to invest the time to learn such topics.

These are major systems that need a solid architecture. I don't want to constantly say "read the book". How do I encourage the regular use of design patterns without coming across as pompous? Has anyone been successful in having an entire team learn and use design patterns?

I would suggest not evangilizing design patterns, instead advocate specific designs/approaches for specific problems as they are encountered.

Later when a similar situation occurs, you can harken back to the approach you took for the earlier problem. Then you can call it a "pattern" that the team has seen used to solve real problems with real benefit.

I would also not strictly adhere to the design patterns in the book for their own sake. It may blind you to good suggestions from non design-patternistas or blind you from real problems that may be specific to your environment/problem domain.

I'm looking for ways/tools/projects to translate Java bytecode into other programming languages or, failing that, at least into a structured representation (like XML). Ideally open source, naturally.

I've looked at ASM, the "bytecode manipulation and analysis framework". It doesn't support translation to other representations, but looks like a good foundation for such a project. Sadly, none of the projects listed on their users page comes close.

Try BCEL (byte code engineering library). You can implement a Visitor interface, which you can use to generate what ever you want (source code in another language, a custom AST , xml, what ever).

I used it for a project in college where I (mostly) modified a program analysis framework that worked over Java source code into one that could also work against Java byte code. That task involved generating nodes for the analysis framework's internal AST representation.


I briefly skimmed the documentation for the "ASM" project you mentioned. It looks like it defines several vistior classes. You should be able to use those to do what you want as well.

If you are not familiar with the visitor pattern, check out the description here. Also, if you haven't read it yet, the "Gang of Four" book is a good read.

In most of the factory pattern implementations, the getInstance method is usually declared as static. The main advantage of factory pattern is to hide the implementation details, but why does getInstance() method needs to be static? Is instantiating a new Factory Object a bad practice?

XYZFactory factory = new XYZFactory(); 
XYZObj obj = factory.getInstance(TYPE);


XYZObj obj = XYZFactory.getInstance(TYPE);

A lot of factory methods are used to offer an instance of the class itself, without the class exporting any constructors (see e.g. Josh Bloch item 1). If the factory method were an instance method, you wouldn't have an object of the class to start with.

Furthermore, getInstance() is usually independent of any existing instance, so it should be declared static. If it depends on one, a prototype (i.e. clone()) is often preferred.

Finally, you should distinguish between factory method public static getInstance() and an abstract factory, which is a class that hides implementation details often for several interfaces. You must, of course, be able to instantiate subclasses of the abstract factory. You can find a great introduction to creational patterns (Abstract Factory, Factory Method, Prototype, amongst others) in the classic Design Patterns book from the Gang of Four. It also gives an example of a non-static factory method intermixed with a prototype. So you see, many variants are possible...

Is the observer design pattern already defined in STL (Like the java.util.Observer and java.util.Observable in Java) ?

The Observer design pattern is not defined in the STL. You can refer to the "Gang of four" Design Patterns book or a Google search should provide enough details to implement it. If this question isn't answered soon, I'll post a quick example.

Q1. In my university studies of object-oriented modelling and design they recommend thinking about what an object can do for its method, and what its responsibilities are for its attributes. All attempts at clarification have resulted in further confusion.

This tends to generate a class diagram with actors who have all the actions, and inner classes which only hold data.

This doesn't seem correct. Is there another way of thinking about how to model the objects?

Q2. Also, the course seems to emphasize modelling the objects after their real-world counterparts but it doesn't necessarily make sense in the domain model. IE. In a medical practice, they have Patient: CreateAppointment(), CancelAppointment() but that is not how it would be implemented (you would modify a the appointment collection instead). Is there another way of thinking about this?

Example Q1

Secretary: RecordAppointment(), RecordAppointmentCancellation()

Appointment: time, date,... (no methods)

Example Q2

Doctor: SeePatient()

While SeePatient is a use-case, it does not make sense for a method on the actual class. How do you think about this?

Unfortunately, the roadblock you've hit is all too typical in academia. Academic projects tend to start with video rental stores, libraries or student registration systems (yours is a variance of this with a doctor's office) and then inheritance is taught with animals. The guideline you've provided is also very typical

they recommend thinking about what an object can do for its method, and what its responsibilities are for its attributes

In fact when beginners ask I usually explain an object's property's are the things it knows about itself and its methods are the things it knows how to do. Which is really just another way of saying exactly what you have there. As you've discovered this way of thinking quickly breaks down when you start discussing more tangible systems and not just examples.

For instance the guideline works pretty well with this object:

public class Tree
    public int Height { get; set; }
    public void Grow(int byHowMuch)
        Height += byHowMuch;

While this certainly fits the bill your right to think that it doesn't "feel" right:

public class Secretary
    public void MakeAppoinment(Patient patient)
        //make the appointment

So what's the solution? It's a matter of taking what you are being taught and applying it. Learning and understanding design patterns will help a lot with developing systems which are more functional than a tree that knows how to grow.

Recommended reading:

To solve the issue you're been presented I would probably use a combination of inherited person classes and interfaces, which would perform their actions through a series of service classes. Essentially a secretary, doctor, and patient would all inherit from person and each of these classes could be passed to accompanying service classes. The service classes may or may not do things like SeePatient(). Please don't take this example to mean that person classes wouldn't have methods.

Stack Overflow has more than a few related questions which may be of use:

Additionally, it would be good to check out:

Finally, there isn't a single definition of what makes an application object oriented. How you apply patterns, principles etc. will define your program. The fact that you are asking yourself these questions shows that you are on the right track.

So this question of mine all began when I started to do unit testing for a simple 2 line of postNotification and addObserver. From this similar question here you can see that to make it testable you need to add ~20 lines & part away from the common way of writing your code.

Facing this problem was actually the first time I understood the difference between Unit Testing and TDD. Unit testing is easy if your code is testable ie if you are following the TDD mindset. Next I was brought to how can I write testable code, which I didn't find much guidelines, every tutorial simply just jumps into writing a unit test. Apple own documentation has nothing for this.

My initial thought was that I need to aim for 'functional programming' and write my functions in a pure function way. But then again this is very time consuming and may require lots of refactoring in existing codes or even for new projects lots of added lines and I'm not even sure if that is the correct approach. Are there any suggested guidelines or standards for writing testable code in an easy way?

What I know myself already: I know that you shouldn't write any code, unless there is a test for it to fail, so basically I have to write the test first and as soon as I get an error, even a compiler error then I would have to switch back to the actual class being tested write whatever necessary and make my test code not give any errors , then switch back to the test class and continue writing my test and fixing compile errors until done. Then run the test and see if it checks what I want it to check.

For all tests I should make sure that my tests would pass and fail exactly where I expect to fail ie the test would pass when it's expected to fail.

What I don't know is how can I smoothen the process in a more easier way.

I am not asking for how to write a testable code for NSNotificationCenter, I am asking for general guidelines for writing testable code.

This is a rather large question, and one where developers' views sway to very different directions. It is also important to note that making code testable is in many essential ways not a Swift specific question: a lot of what makes you able to write testable code routinely and conveniently actually relies on you following some fundamental, generally applicable principles. Often test driven design practices help you indirectly, by validating you have followed practices that make executing your code via tests plausible, beside bringing you other programmer productivity and reliability benefits. So, unfortunately writing testable code is not a question of learning some mechanical tricks of working with Xcode, rather than often a proof of you having designed and planned the programs and libraries you write keeping to some good practices.

I'll do my best to link below to some Swift specific resources to demonstrate the more general principles I tend to myself follow to make my code testable.

  1. Making your code testable is often a side effect of following sound object oriented design principles.

  2. Following a sound object oriented design is often itself the side effect of good higher level architectural decisions. Basically, think early and often about the kinds of types you plan to introduce in the object graph of the program. What are the roles and dependencies between them? Are any of the dependencies in your object graph hard to meet or correctly construct when executing your code from different contexts (e.g. from UI code vs a unit test)?

    • There is a lot of computer science literature about architectural design patterns. The Gang of Four remains a valuable book to read about this topic (although not all of it applies to your typical Swift program).
    • Take a look at this Swift design patterns demonstration for an overview of how many common design patterns can be implemented in Swift.
    • Especially if your code is for a mobile app, you should read about VIPER, a mobile app oriented architectural pattern emerged out of the typical architectural needs of iOS apps.
    • To link design patterns to the SOLID principles listed above, the "Single Responsibility" principle is perhaps the one principle most glaringly violated in many large Cocoa programs that is a result of bad architectural practices, also resulting in very difficult to test code. People in fact often for jokingly refer to MVC as applied in practice in Cocoa as the "Massive View Controller".

The above points raised are in no way Swift specific, and I would expect not terribly controversial claims. Swift does however also offer language features that also help you write reliable, bug free code, in part as these language features help you make your code testing friendly. Here's a few of good Swift practices:

  • Use value types when you can: Swift is well suited for writing programs which minimise automatic reference counted references (pointers). This carries with it performance benefits, but also improves your chances of writing reliable code that minimises unexpected dependencies and data races which can be difficult to capture in testing.
  • Keep things immutable when you can: the syntax conventions and type system in Swift help you avoid mutable state, which amongst other things has a negative impact on testability of your code (configuring your object graph for testing can become difficult, as will achieving real-world usable test coverage of your code if the possibile state space in your program is large).
  • Apple has also made available some guidance on the architectural matter of value types and immutability that also touches on testability of your code.
  • Use protocols when you can: to understand why, read up on the Liskov substitution principle :-) More seriously, preferring protocols over concrete types helps you write testable code for instance by for allowing you to fulfil dependencies in a test setting with test specific types that fake or mock some resources irrelevant for your tests.
  • Use functional programming techniques (when it makes sense): often composing functionality with functions helps you write readable, flexible code that avoids mutable state. I recommend Functional Swift by Chris Eidhof and others as a good guide to applying functional patterns in Swift.

Again, this question is large and I am really just scratching the surface with my answer, in order to make the point that there is no single magic bullet to testability – it's something you achieve as a result of following many best practices when designing your code.

As with all development, CFML via ColdFusion, Railo or OpenBD we run into common programming problems. For these problems must programmer turn to patterns (or anti-patterns). However the classic resources like GOF and the modern Head First books both tend to focus on Java.

While java is beautiful in its own right, all three cfml engines are essentially java applications, that said not all or even many design patterns can or should be used in the java way when writing cfml.

I would like to know what resources/patterns you have found useful when working with cfml? Or what you changed adapting a java or smalltalk pattern for use in cfml?

Personally I found both of these presentations to be interesting:

CFMeetup: Design Patterns and ColdFusion By Sean Corfield


Design Patterns By Cameron Childress


Stumbled upon, looks promising.

For a site you may want to check Object-Oriented ColdFusion. Its still a work in progress, but it may help.

regards, larry

From the chapter on FlyWeight Pattern inside Gang of Four the FlyWeight pattern is applicable when most object state can be made extrinsic.

What does extrinsic state mean ? I get the feeling that this pattern is used for sharing of objects . If objects are to be shared , then how can that object even have any state at all ?

Whatever the specific wording in that bulleted list, it is important to understand the message: Flyweight applies to the case where an important part of data can be shared among many objects because it is immutable. The example with font faces makes this quite clear; an example from everyday Java is java.util.regex.Pattern, the holder of immutable extrinsic state, vs. Matcher, the flyweight that reuses it and holds local intrinsic state. Many Matchers can exist in parallel, all reusing the compiled regex on the inside.

This quote makes things clearer than the one from your question:

The more flyweights are shared, the greater the storage savings. The savings increase with the amount of shared state. The greatest savings occur when the objects use substantial quantities of both intrinsic and extrinsic state, and the extrinsic state can be computed rather than stored. Then you save on storage in two ways: Sharing reduces the cost of intrinsic state, and you trade extrinsic state for computation time.

If, in future, you were only able to use a single one of the canonical patterns defined in the Gang of Four book, which one would you choose and for what reason?

Not a design pattern, but to me this principle was definitely the most influential on my programming style of the whole book:

Favor object composition over class inheritance.

Combined with the other principle "Program to an interface, not an implementation", most design patterns follow naturally.

Choosing one pattern as the most important is in my opinion impossible. They all have their purpose and complement each other. Its like asking if a hammer or a screwdriver is more useful. It depends on the problem, sometimes you have a nail and sometimes a screw.

I have been coding for a few years and still feel that my knowledge is not broad enough to become a professional. I have studied some books related to design patterns, but I know there are many others.

So could somebody list the patterns and principles which you think are good to learn to become a better programmer and more professional?

Programming Languages I work on: C#, Ruby, Javascript.

Encyclopedic knowledge of design patterns will get you nowhere. Plenty of experience applying them will. This will teach you when to use them and when not to.

That said, the original Design Patterns book is still one of my favorites. Pick up other patterns as you go along.

Martin Fowler's Patterns of Enterprise Application Architecture to build up a shared vocabulary with other developers (e.g. Repository, Active Record, Domain Model, Unit of Work).

Douglas Crockford's Javascript: The Good Parts to actually understand how Javascript works.

And I'd really recommend getting into TDD (Test Driven Development). There are a bunch of good TDD books but if you are doing brownfield development (which most of us are) then I'd really recommend Michael Feather's Working Effectively with Legacy Code.

And finally the book that shows you just how refactored and clean code can be: Uncle Bob's Clean Code.

I have two years worth of PHP experience however I have never worked with design patterns. I have recently been given a task at work that has made me question the wisdom of that decision.

I have been asked to create a system that:

  1. Insert orders into a database. These orders can have a multitude of attributes and control logic that needs to be applied. The system will not be directly responsible for a front end, it will receive commands via an API.

  2. Write the scripts that extracts orders from the database, decide which supplier to send with and create the associated files for uploading to a provider. File formates vary (XML, CSV).

  3. Process incoming files from suppliers in the various formates (XML, CVS) and update the databases. Also FTP will have to be utilised to gather the files from the remote host.

I would like a central control class that can service each of the required functions, one point of access so to speak. This would then extend into the various specific functionality as required.

I am wondering if it is worth learning a design pattern to facilitate this system, if so could someone point me in a direction as there are many. Any advise on my issue would be very helpful.

Thanks in advance

Yes it's a worthwhile effort, however as it will not solve your problem. If you have been coding without them you sometimes use them in a mixture of patterns and thing are not always clear. Having names and template may make your code clearer and easier to maintain.

In the last 2 year I have been brushing up on design patterns and how to better model solution, and I believe it has payed off.

I personally read used these books for my studies:

I do think studying design design patterns can help you improve your design. Having clear names will aid people that coming on later.

I'm going to create the comparison table of existing automated C++ refactoring tools as well as explore an ability of creation of such tool, free and open-source.

My question is: what refactorings do you really use in your everyday work? There are obvious things like renaming variable/class/method, but is there something specific for C++, like dealing with templates, STL, copy constructors, initializers, etc., etc?

I'm interested in building of realistic picture of all that little problems that C++ developer is facing each day in his coding and that could be automated at least in theory. I'm talking to my colleagues but that's probably not enough.

Thanks in advance.

Take a look in Martin Fowler's Refactoring: Improving the Design of Existing Code and Refactoring to Patterns by Joshua Kerievsky. These in turn reference the GoF Design Patterns book so get that too.

If you can beyond the basic Rename Feature and Extract Function then you might be onto a winner.

I'm reading a lot about good and bad practices in OOP design. It's nice to know your design is bad, or good. But how do you get from bad to good design? I've split the interface (xaml) and codebehind from the main businesslogic class. That last class is growing big. I've tried splitting it up into smaller classes, but I'm stuck now. Any ideas on how to split large classes? The main class has 1 list of data of different types. I'm doing calculations on the total, but also on the individual types. I've got methods to perform these calculations which are called from events handled in the codebehind. Any ideas where to go from here?

Additional Info:

We are already about 6 months into this project. I've worked with object oriented laguages for years (first c++, java and now c#), but never on a large project like this one. I believe we've made some wrong turns in the beginning and I think we need to correct these. I can't specify any details on this project at the moment. I'm going to order one or two books about design. If I separate all the classes, how do I stick them back together? Maybe it's even better to continue this way to the first release and rebuilt parts after that, for a second release?

I highly recommend picking up Code Complete. It's a great book that offers tons of good advice on questions like yours.

To give you a quick answer to your question about how to split large classes, here's a good rule of thumb: make your class responsible for one thing, and one thing only. When you start thinking like that, you quickly can identify code that doesn't belong. If something doesn't belong, factor it out into a new class, and use it from your original class.

Edit: Take that thinking down to the "method" level, too - make your methods responsible for one thing, and one thing only. Helps break large (>50 line) methods down very quickly into reusable chunks of code.

Refactoring by Martin Fowler is an excellent book about how to change the design of your software without breaking it.

Design Patterns works similarly to algorithims but tells you how to combine objects to perform various useful tasks.

Finally Martin Fowler has a variety of useful design pattern for applications. For example Passive View

Michael Feathers's "Working Effectively with Legacy Code" is supposed to be very good, but I'll confess that I haven't read it myself.

Same goes for "Refactoring to Patterns."

I'm still new to OOP, and the way I initially perceived it was to throw alot of procedural looking code inside of objects, and think I'd done my job. But as I've spent the last few weeks doing alot of thinking, reading, and coding (and looking at good code, which is a hugely under-rated resource), I believe I'm starting to grasp the different outlook. It's really just a matter of clarity, simplicity, and organization once you get down to it.

But now I'm starting to look at things as objects that are not as black and white a slamdunk case for being an object. For example, I have a parser, and usually the parser returns some strings that I have to deal with. But it has one specialized case where it has to return an array, and what goes in that array and how it's formatted has specialized rules. This only amounts to two lines plus one method of code, but this code sticks out to me as not being cleanly fitting in the Parser class, and I want to turn it into its own "ActionArray" object.

But is it going to far? Has OOP become a hammer that is making me look at everything like a nail? Is it possible to go too far with turning things into objects?

Design patterns are your friend. A class rarely exists in a vacuum. It interacts with other classes, and the mechanisms by which your classes are coupled together is going to directly affect your ability to modify your code in the future. With poor class design, a change that you make in one class may ripple down and force changes in other classes, which cause you to have to change other classes, etc.

Design patterns force you to think about how classes relate to each other. For example, your Parser class might choose to implement the Strategy design pattern to abstract out the mechanism for parsing. You might decide to create your Parser as a Template design pattern, and then have each actual instance of the Parser complete the template.

The original book on Design Patters (Design Patterns: Elements of Reusable Object-Oriented Software is excellent, but can be dense and intimidating reading if you are new to OOP. A more accessible book (and specific to Ruby) might be Design Patterns in Ruby, which has a nice introduction to design patterns, and talks about the Ruby way of implementing those patterns.

I need a mock implementation of a class - for testing purposes - and I'm wondering how I should best go about doing that. I can think of two general ways:

  1. Create an interface that contains all public functions of the class as pure virtual functions, then create a mock class by deriving from it.
  2. Mark all functions (well, at least all that are to be mocked) as virtual.

I'm used to doing it the first way in Java, and it's quite common too (probably since they have a dedicated interface type). But I've hardly ever seen such interface-heavy designs in C++, thus I'm wondering.

The second way will probably work, but I can't help but think of it as kind of ugly. Is anybody doing that?

If I follow the first way, I need some naming assistance. I have an audio system that is responsible for loading sound files and playing the loaded tracks. I'm using OpenAL for that, thus I've called the interface "Audio" and the implementation "OpenALAudio". However, this implies that all OpenAL-specific code has to go into that class, which feels kind of limiting. An alternative would be to leave the class' name "Audio" and find a different one for the interface, e.g. "AudioInterface" or "IAudio". Which would you suggest, and why?

Just as I would not hand-author mock objects in Java, I would also not hand-author them in C++. Mock objects are not just stubbed out classes, but are test tools that perform automated checks like making sure certain methods are called, or that they are called in order, etc. I would take a look at the various mock object frameworks for C++ out there. googlemock looks interesting, but there are others.

Regarding how to abstract out the concept of controlling Audio resources from the implementation, I definitely favor using a C++ "interface" (pure virtual base class) with a generic name (e.g. Audio) and an implementation class named for what makes it special (e.g. OpenALAudio). I suggest you not embed the word "interface" or "I" into your class names. Embedding type or programmatic concepts into names has been falling out of vogue for many years (and can force widespread renaming when you, for example, elevate an "interface" to a full-fledged "class").

Developing to interfaces is an object-oriented concept and thus appropriate for C++. Some of the most important books on design specifically targeting C++ are all about programming to interfaces (which in C++ terms means programming using pure virtual base classes). For example, Design Patterns and Large Scale C++ Software Design.

In web development we use java .net or php5 . All are OO. and have all the OO features.

But in real time websites do these OO features play any major role other than inheritance.?

Can anybody list some with real time examples.

In application development there may be a vast use of OO. But in case of websites, does OO playing a major role? How?

Back in 1995 the book Design Patterns managed to produce this phenomenal insight on page 20:

Favor object composition over class inheritance

Since then, proper object-orientation has been about that instead of inheritance. Particularly, the SOLID principles describe a set of principles for object-orientation that are applicable for any code base where maintainability is important. Polymorphism is important, but inheritance is irrelevant.

That applies to web applications as well as any other type of application.

Let's say I have two models:

class Book
    public $book_id;
    public $book_author_id;
    public $title;

class Author
    public $author_id;
    public $author_name;

I'm used to writing something like this:

$DB->query("SELECT book_id, title, author_name 
            FROM book 
            LEFT JOIN author 
                ON book_author_id = author_id

Let's assume, that I'm not interested in having separate queries for this association. How do I proceed? Here are some things I've heard:

  • create a MySQL VIEW of the JOIN
  • create a model class of the VIEW

The application I'm working on involves dozens of tables and was highly optimized in procedural code (almost no SELECT * anywhere, for instance). I'm refactoring to make it more maintainable (I'm the original creator, too), but I would like to have the flexibility of using joins when I need to without compromising the structure of my files and DB calls.

A possibly related question I have is related to including other models:

class Author
    public $author_id;
    public $author_name;

    /* @var Book */ //<--don't really fully understand this but I've seen something like it somewhere
    public (array) $authors_books;

I'm still searching for answers, but if you could send a link my way, that would be appreciated.

What you are calling "models" are actually domain objects. They should be responsible for dealing with domain business logic, and have nothing to do with storage.

The storage-related logic and interaction should be handled by separate group of objects. One of most sensible solution is using data mappers. Each mapper can deal with multiple tables and complicated SQL.

As for your query, the result of such query would contain information, appropriate for passing to a collection of domain objects.

BTW, that query is quite useless. You forget that each book can have multiple authors. Take for an example this book - it has 4 different authors. To make this query useful, you should have to do GROUP_CONCAT() based on either author_id or book_id.

When implementing such JOIN statements, the database response most likely will be a collection:

$mapper = $factory->buildMapper('BookCollection');
$collection = $factory->buildCollection('Book');

$mapper->fetch( $collection );
foreach ( $collection as $item )
$mapper->store( $collection );

P.S. Your code example seem to be leaking abstraction. It is a bad practice to let other structures to access object's variables directly.

P.P.S. It seems that your understanding of model part of MVC is quite different from how i see it.

My question is : in PHP are interfaces really useful for developers that build website applications on their own ? Isn't an abstract class providing all the things an interface provides ?

If an interface is just a "contract" isn't the developer aware of the things the class should implement ?

The only single benefit I can think of is that a class can implement multiple interfaces but again how useful is this .. when you know everything a class should implement. You just force yourself to implement those methods.

As you can figure out I'm still waiting for that A-HA moment when I really understand why an interface is useful.

To wrap this up and put it simple : When should I use interfaces and why not use abstract classes instead ?

"Programming to an Interface and not an implementation" is a principle introduced by the GoF in their books Design Patterns: Elements of Reusable Object-Oriented Software.

Quoting Erich Gamma on the principe:

Once you depend on interfaces only, you're decoupled from the implementation. That means the implementation can vary, and that's a healthy dependency relationship. For example, for testing purposes you can replace a heavy database implementation with a lighter-weight mock implementation. […]

So this approach gives you flexibility, but it also separates the really valuable part, the design, from the implementation, which allows clients to be decoupled from the implementation. One question is whether you should always use a Java interfaces for that. An abstract class is good as well. In fact, an abstract class gives you more flexibility when it comes to evolution. You can add new behavior without breaking clients. […]

In Java when you add a new method to an interface, you break all your clients. When you have an abstract class, you can add a new method and provide a default implementation in it. All the clients will continue to work. As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. It isn't always possible to define an interface in an abstract class, but in the light of evolution you should consider whether an abstract class is sufficient.

Read the full interview here

So, You can use an interface or an abstract class. You just have to consider the trade-off. IMO, it's worth using interfaces, even if you are alone. You rarely know what your app will look in the end. The waterfall is a myth, so you will have to face change during development and interfaces make it easier to embrace it.

You might also be interested in:

and some more:

Ok, i'd like to firstly make you notice that i have looked for "php mvc design patterns" and so and i haven't really found what i was looking for; still now, writing my question, i cannot find any related and so specific question as i am going to ask. But i know i'm probably wrong, anyway consider this question and a question pack that could be usefull togheter.


  1. I was wondering how we should consider the design patterns. I mean: What are they? Are they simply binaries that help us designing consistent application? Are they so used? Why?
  2. Where could i find a list about every design patterns on the web? Or at least the 5-10 most used design patterns?
  3. Do Phpbb, Wordpress or Joomla (that i know pretty well) use a design pattern? If yes, which?
  4. I googled MCV PHP and found about 3 italian articles and read about 5 of the first pages ranked and i didn't understand pretty much nothing. They were conflicting and seemed to me confusing. I did understand that it is usefull to separate business login, script and view (?) but i didn't got anything else. I am probably stupid or something but where could i find a nice and official (means written by the Gang of Four or someone who actually know what he is talking about) mvc tutorial or documentation related to php?
  5. Are there simple examples about design patterns and how they are better then (normal) writing styles? Are there simple examples about a mvc or other design pattern? For example a simple blog written with a design pattern?


I'd prefer free solution first. I don't like frameworks, so please don't refer to them even if (i know) they have mvc and other valid design patterns and benefits. I still don't like them. Thanks


I'll choose my accepted answer after tomorrow, so, please, take your time to answer.

You would probably get better results googling for MVC PHP instead of MCV PHP. Design patterns can be applied to all object oriented languages so you might be best advised to look into THE design pattern book and into Object Oriented Programming with PHP.

There also is an article series on DZone about practical PHP patterns.

Closed as exact duplicate of this question. But reopened, as the other Singleton questions are for general use and not use for DB access

I was thinking of making an internal data access class a Singleton but couldn't convince myself on the choice mainly because the class has no state except for local variables in its methods.

What is the purpose of designing such classes to be Singletons after all?
Is it warranting sequential access to the database which is not convincing since most modern databases could handle concurrency well?
Is it the ability to use a single connection repeatedly which could be taken care of through connection pooling? Or Is it saving memory by running a single instance?

Please enlighten me on this one.

From "Design Patterns: Elements Of Reusable Object-Oriented Software":

It's important for some classes to ahve exactly one instance. Although there can be many printers in a system, there should only be one printer spooler. There should only be one file system and one window manager. ...

Use the Singleton pattern when:

  • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
  • the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code

Generally speaking, in web development, the only things that should actually implement Singleton pattern are in the web framework itself; all the code you write in your app (generally speaking) should assume concurrency, and rely on something like a database or session state to implement global (cross-user) behaviors.

What books should you read to improve your code and get used to good programming practices after getting a taste of the language?

C++ Coding-Standards: 101 Rules, Guidelines, and Best Practices

---- Herb Sutter and Andrei Alexandrescu

alt text

Meyers' Effective C++, "More Effective C++" and "Effective STL".

Design Patterns by the 4 guys affectionately nicknamed "the gang of four".

Lakos' Large Scale C++ Software Design.

There are of course many others, including many truly good ones, but if I had to pick 3 on C++ (counting Meyers' three thin, information-packed volumes as one;-) these would be it...

What is your perspective on downcasting? Is it ALWAYS wrong, or are there cases where it is acceptable, or even preferable or desired?

Is there some good measure/guideline we can give that tells us when downcasting is "evil", and when it's "ok"/"good"?

(I know a similar question exists, but that question spins out from a concrete case. I'd like to have it answered from a general design perspective.)

An example for "legal" downcasting is Java pre 5.0 where you had to downcast container elements to their concrete type when accessing them. It was unavoidable in that context. This also shows the other side of the question though: if you need to downcast a lot in a given situation, it starts to be evil, so it is better to find another solution without downcasting. That resulted in the introduction of generics in Java 5.

John Vlissides analyzes this issue (aka "Type Laundering") a lot in his excellent book Pattern Hatching (practically a sequel to Design Patterns).

When it comes to the use of design patterns, I am guessing there are three types of shops. Those who wouldn't know a pattern if it hit them in the face - these usually prefer the Ctrl-C / Ctrl-V approach to code-reuse. Those who spend hours a day searching their legacy code in hopes of implementing one more great pattern - these usually spend more time refactoring the code of simple programs than would ever be spent in a hundred years of maintenance. And finally, those who walk the middle path using patterns when they make sense, and coding whatever comes first for minimally exposed code.

I'm wondering if anyone has locked down a good approach to a balanced incorporation of pattern use in the software development life cycle. Also, what is the best resource on the Web for patterns, their motivating factors, and their proper use?


There are lots of different 'pattern' families out there, but taking your question its broadest terms...

I'd recommend:

Offline (my favourites):

Offline (popular):

  • GoF Design Patterns
  • Fowler's Refactoring: Improving the Design of Existing Code

I agree with these references, but there are not newbie friendly. To quick start learning design patterns the easy way :

Head First : design pattern

Then your can check the more advanced books once you got the big picture (a lot of practical examples ;-))

The definition and original answer is the origin of the concept, in Design patterns. This book deals with the concept at a very theortical level, rather than the management speak that has infiltrated the area. Their view is that design patterns are just names for common idioms; they enumerate some and justify their positions.

They avoid the "What design pattern should I use" type of question, instead dealing with problem as "Am I naturally stepping into a well known area? If so, can others experience help me?". Design patterns, to me, are not like prefab components you glue together to make a solution. They are just guidance repositories for when you come across a situation similar to one others have countered, and give names to allow people to refer to the general situations in conversation.

While reading some programming books, I notice that the authors says that, in OOP, you may have some confusion while understanding the main idea of OOP.

And hell yeah!. I had some confusion. Did you have the same and what makes this confusion to programmers(even experienced programmers)?!

And if you had it, how could you beat this ?!


Once you understand the oo basics take a look at design patterns and design principles (e.g. by reading Head First Design Patterns). It will teach you how you should actually use the tools that oo gives you. While this is no substitute for practical experience it can certainly speed up the learning process.

OOP takes a "problem oriented" approach to programming as opposed to the traditional "machine oriented" approach used in languages like C and Pascal. Learning OOP can be quite tough if you've programmed extensively in procedural/functional languages. It is to these programmers that things tend to be more confusing. If you are new to programming, you'll probably find things a lot less confusing since you're starting off with a fresh mind.

Having said that, I've seen many programmers who've worked extensively with languages like Java and claim to be good OOP programmers when they were actually far from it. Sure they use Java language features like interfaces, inheritance etc, and create objects "which are instances of classes", and "send a message to an object". Most people use a lot of OOP jargon because they are exposed to it. But when it comes down to writing a simple application their resulting code exposes their poor understanding.

My advise to you is don't get caught in using jargon alone. Question and learn the underlying concepts diligently. You might have your first semi-nirvana (like I did) when you learn polymorphism and the benefits it brings to code re-usability. Another semi-nirvana when you understand the trade-offs between reuse via inheritance and reuse via composition. In the end, you will know that you've understood OOP well if you able to design well, or rather, a good OO design is easily a good measure of how well you understand OOP.

If you are serious about OOP, you should read the first two chapters of the GOF book on Design Patterns. It might be a little tough on new programmers, but it lays the crux of the thinking behind OOP. This book is an important reference which any serious OOP programmer should have. If you understand the concepts in this book well, consider yourself to be a good OO programmer.

Why do we need design patterns like Factory, Abstract Factory and Singleton?

Design Patterns provide easy to recognize and use OOP solutions to common problems. They're inherently easy to maintain, because many people are familiar with them. This is very similar to how google works. Everyone knows HOW to google, so when you get a query like "What is the purpose of design patterns", you can very quickly use this common interface to solve a problem.

Design Patterns also solve specific programming challenges regarding usability and maintainability. Pick up the Gang of Four book and have at it.

As discusses in The c++ Programming Language 3rd Edition in section 12.2.5, type fields tend to create code that is less versatile, error-prone, less intuitive, and less maintainable than the equivalent code that uses virtual functions and polymorphism.

As a short example, here is how a type field would be used:

void print(const Shape &s)
  case Shape::TRIANGE:
    cout << "Triangle" << endl;
  case Shape::SQUARE:
    cout << "Square" << endl;
    cout << "None" << endl;

Clearly, this is a nightmare as adding a new type of shape to this and a dozen similar functions would be error-prone and taxing.

Despite these shortcomings and those described in TC++PL, are there any examples where such an implementation (using a type field) is a better solution than utilizing the language features of virtual functions? Or should this practice be black listed as pure evil?

Realistic examples would be preferred over contrived ones, but I'd still be interested in contrived examples. Also, have you ever seen this in production code (even though virtual functions would have been easier)?

When you "know" you have a very specific, small, constant set of types, it can be easier to hardcode them like this. Of course, constants aren't and variables don't, so at some point you might have to rewrite the whole thing anyway.

This is, more or less, the technique used for discriminated unions in several of Alexandrescu's articles.

For example, if I was implementing a JSON library, I'd know each Value can only be an Object, Array, String, Integer, Boolean, or Null—the spec doesn't allow any others.

My take is: It depends.

A parameterized Factory Method design pattern relies on this technique.

class Creator {
        virtual Product* Create(ProductId);

Product* Creator::Create (ProductId id) {
        if (id == MINE)  return new MyProduct;
        if (id == YOURS) return new YourProduct;
        // repeat for remaining products...

        return 0;

So, is this bad. I don't think so as we do not have any other alternative at this stage. This is a place where it is absolutely necessary as it involves creation of an object. The type of the object is yet to be known.

The example in OP is however an example which sure needs refactoring. Here we are already dealing with an existing object/type (passed as argument to function).

As Herb Sutter mentions -

"Switch off: Avoid switching on the type of an object to customize behavior. Use templates and virtual functions to let types (not their calling code) decide their behavior."

As usual there is a lot of code in my LoginActivity and I really would prefer to separate the Activity responsibilities from the Google Play sign in concerns.

After rewriting this LoginActivity code several times, in many different apps, the easy (and not so elegant) solution was create the Google API client as a Application class object. But, since the connection state affect the UX flow, I never was happy about with this approach.

Is there an elegant way of place the GoogleApiClient outside the Activity?

0. TL;DR

For the impatient coder, a working version of the following implementation can be found on GitHub.

Reducing our problem only to the connection concept, we may consider that:

  1. It has finite states.
  2. It encapsulates the connection client.
  3. It is (rather) be unique.
  4. The current state affect the behavior of the app.

1. State Pattern

This is a behavioral pattern the allow an object to alter its behavior when its internal state changes. The GoF Design Patterns book describes how a TCP connection can be represent by this pattern (which is also our case).

A state from a state machine should be a singleton, and the easiest away of doing it in Java was to create Enum named State as follows:

public enum State {
        void connect(Connection connection) {
        void connect(Connection connection) {
    OPENED {
        void disconnect(Connection connection) {
        void revoke(Connection connection) {
    CLOSED {
        void connect(Connection connection) {

    void connect(Connection connection) {}
    void disconnect(Connection connection) {}
    void revoke(Connection connection) {}

The Activity will communicate with the Connection abstract class (which holds the context) through the methods connect(), disconnect(), and revoke(). The current state defines how these methods will behave:

public void connect() {

public void disconnect() {

public void revoke() {

private void changeState(State state) {
    currentState = state;

2. Proxy Pattern

The class GoogleConnection inherits from Connection and encapsulates the GoogleApiClient, so it must provide both ConnectionCallbacks and OnConnectionFailedListener as follows:

public void onConnected(Bundle connectionHint) {

public void onConnectionSuspended(int cause) {

public void onConnectionFailed(ConnectionResult result) {
    if (state.equals(State.CLOSED) && result.hasResolution()) {
        connectionResult = result;
    } else {

public void onActivityResult(int resultCode) {
    if (resultCode == Activity.RESULT_OK) {
    } else {

The methods onSignIn(), onSignUp(), onSignOut(), and onRevokeAndSignOut are required on the second step of this explanation.

public void onSignUp() {
    try {
        Activity activity = activityWeakReference.get();
        connectionResult.startResolutionForResult(activity, REQUEST_CODE);
    } catch (IntentSender.SendIntentException e) {

public void onSignIn() {
    if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {

public void onSignOut() {

public void onRevokeAndSignOut() {
    mGoogleApiClient =;

3. Singleton Pattern

Since there is not need to recreate this class repeatedly, we provide it as a singleton:

public static Connection getInstance(Activity activity) {
    if (null == sConnection) {
        sConnection = new GoogleConnection(activity);

    return sConnection;

public void onActivityResult(int result) {
    if (result == Activity.RESULT_OK) {
    } else {

private GoogleConnection(Activity activity) {
    activityWeakReference = new WeakReference<>(activity);

    googleApiClientBuilder = new GoogleApiClient
           .addApi(Plus.API, Plus.PlusOptions.builder().build())
           .addScope(new Scope("email"));

    googleApiClient =;
    currentState = State.CLOSED;


4. Observable Pattern

The Connection class extends Java Observable, so one or many activities can observe the state changes:

protected void onCreate(Bundle bundle) {
    mConnection = GoogleConnection.getInstance(this);

protected void onDestroy() {

protected void onActivityResult(int request, int result, Intent data) {
    if (Connection.REQUEST_CODE == request) {

public void update(Observable observable, Object data) {
    if (observable == mGoogleConnection) {
        // UI/UX magic happens here ;-)

Being a Java developer in an agile development cycle, I have learnt that it is essential to make sure I design my classes in a manner that I can refactor them easily without much of a pain. I want to know, what are the best practices that you follow in your daily design/development cycle that helps you to perform refactoring easily.
For example, I know that I should hide the implementation details behind an interface. So that event if I am changing the implementation tomorrow, I am not disturbing the client code which consumes this APIs. Similarly I should use “factory design pattern” wherever possible so that the change of implementation classes can be controlled from one factory class rather than find out all the places and change them.
Similarly I would like to know what all best practices that you are following which will help me.

I would recommend picking up two books if you're going to be doing a lot of java.

I'd recommend Effective Java and Design Patterns: Elements of Reusable Object-Oriented Software.

I want code for: syntax highlighting (of programming languages)
Language: C# or assembly x86 (preferably C#)
Platform: Windows
Qualifications: most efficient implementation possible / most professional / the way that big corporations like Microsoft do it
Rephrased: How do I implement syntax highlighting in C# for Windows in the most efficient way presently known?

Elaboration (feel free to skip - not needed to answer question :)):
I don't want just any way of implementing it - I've already seen several.
What I'd like to know is how Microsoft does it so well on Visual Studio (whichever version).

People keep trying to reinvent the wheel when it comes to syntax highlighting. I don't understand why.
Is this considered a very hard problem? I've seen implementations that only highlight what's currently showing on the screen, I think that's the way to go... (it used some clever API to know which lines of a textbox were actually showing).
I've also seen implementations using RichTextBox and I think that's not the way to go (maybe I'm wrong here) - I think something like subclassing the routine that draws text on the regular textbox and changing its brushes might be better (maybe I've seen that somewhere - I doubt I'd think of that myself)
Also I've heard that some people implement it with AST just like a compiler would be coded (the lexer part, I think?) - I'd hope that that's overkill - I don't see that as being efficient. (uneducated guess)

If it's indeed a hard problem, then how do the big corps always get it right? I've never heard of a way to break the syntax highlighting in Visual Studio, for example.
But any other tool that implements it does so poorly, or worse than the big guys.
What's the official "this is the best way and any other way is less efficient" way of doing it?

I really don't have any evidence that Microsoft's way is better, but seeing that they probably know more about Windows API than anybody else, I'd guess that there way of implementing it is the best (I would love to be wrong - imagine being able to say that my implementation of syntax highlighting is better than MS's!)

Sorry for the disjointed elaboration.
Also I apologize in advance for any faux-pas - this is my first question.

As with anything code.... there rarely is a "best" way. There are multiple ways of doing things and each of them have benefits and drawbacks.

That said, some form of the Interpreter Pattern is probably the most common way. According to the GoF book:

The Interpreter pattern is widely used in compilers implemented with object-oriented languages, as the Smalltalk compilers are. SPECTalk uses the pattern to interpret descriptions of input file formats. The QOCA constraint-solving toolkit uses it to evaluate constraints.

It also goes on to talk about it's limitations in the applicability section

  • the grammer is simple. For complex grammars, the class hierarchy for the grammer becomes large and unmanagable. Tools such as parser generators are a better alternative in such cases
  • effeciency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

Understanding this, you should now know why it's better to pre-compile your reusable RegEx first before performing many matches with it. If you don't, it will have to do both steps every time (transformation, interpretations) rather than building the state machine once, and applying it efficiently several times over.

Specifically for the type of interpretation you are describing, Microsoft exposes the Microsoft.VisualStudio namespace and all of it's powerful features as part of the Visual Studio SDK. You can also look at System.CodeDOM for dynamic code generation and compilation.

Can someone send me an article or a book where i can find how to use design patterns inside UML class diagrams? Extra points for references having a case study and a summary about how to use design patterns throughout the UML class diagram.

Can you please tell me some tutorials/books about thinking a large application in c#. I have worked with 3 tier, but i need something more specific:

a way to design panels, so that for specific users specific panels will load and specific dlls a database management so that when a user modifies an entry, others can not modify that entry should i use entity framework or should i go old school with db and class creation

any links on the above will be greatly appreciated

thanks a lot!

Kind of a broad subject but two books I would recommend giving a read regardless of what language you are doing or the specifics of your project:

If you have specific questions about how to accomplish something I would post it on here or google it.

That's not gonna be covered by a single book or tutorial, trust me. You need to decide a UI framework, data access technology, patterns and the overall architecture. And of course you need an in-depth knowledge on .NET framework, & how the CLR works. It's nothing C# specific. Since you have UI customization (Panels) requirements, WPF is definitely a better candidate for UI framework.

That being said -

  • For C#: Pro C# 2010 and the .NET 4 Platform

  • .NET & CLR: CLR via C#

  • UI Framework - WPF: Pro WPF in C# 2010

  • Use MVVM with WPF. MVVM will keep you on track maintaining the Separation of Concern. You can follow Microsoft's Prism guideline. For large applications with sophisticated UI requirements Prism is a better choice. You might need to use Dependency Injection. MEF is there to go hand-to-hand with MVVM & Prism.

  • Yes, Entity Framework can handle concurrency issues, but that its available in almost all data access framework. Entity Framework provides lots of other facilities, but when using it you should have clear idea of what you're doing. Programming Entity Framework is definitely gonna help.

Microsoft .NET: Architecting Applications for the Enterprise - with a very good code example and there is a chapter on concurrency

Professional Enterprise .NET

ASP.NET 3.5 Website Programming: Problem - Design - Solution

I guess, there are not any online recources that could compete the complexity of these books.

I am learning STL and design patterns . i wanted to know is there any document or link that explains how design patterns are implemented in STL i did the google but not able to get much data

STL makes extensive use of templates. GoF call this parameterized types. Templates are useful for customizing a design pattern solution or in coming up with a new, intuitive solution. (For more details, see the section "Inheritance versus Parameterized Types" in "Design Patterns: Elements of Reusable Object-Oriented Software"). The advantage of getting familiar with STL (and boost) is that they are a good source to learn about templates (and meta-programming) in C++, which in turn can be used in devising better designs.

I think that your problem is that design patterns are not implemented in STL. They can be implemented in C++ and use containers and algorithms from STL but STL and Design Patterns are not related in any other way.

My advice would be to learn about STL by reading something like Nicolai Josuttis' excellent book The C++ Standard Library: A Tutorial and Reference or STL Tutorial and Reference Guide. This will help in learning what the STL can do for you. Then dig into implementing design patterns in C++ using your knowledge about the STL.

I considered this scenario: objects that roughly look like this:

class PhyisicalObject
  virtual void Update() = 0;
  friend class PhysicsController;
  void DoUpdate() { this->Update(); }

There's a controller class called a PhysicsController that manages the dynamics of a pool of physical objects by calling their DoUpdate() method. This method, in terms, calls an overloaded version of the Update()function where a numerical integrator is used to compute the objects position, velocity and acceleration step-wise. I thought that having an interface implying this functionality would be a good starting point:

class IIntegrator
  virtual void opertor() (const vec3& pos, const vec3& vel, vec3& outPos, vec3& outVel);

Now inheriting this IIntegrator abstract class and providing the implementation for various methods is the next step (explicit Euler, RK4, Verlet, Midpoint, Symplectic Euler and perhaps some semi-implicit/IMEX or implicit ones would be excellent). The problem is that I don't see clearly how to do the following two things:

  1. Each physical object computes its own acceleration at any of its vertices in different ways (considering the objects consist of masspoints connected through springs or some kind of constraining objects). This function must be passed to the integrator, but it is object specific. It is possible to get pointers to non-static methods, but how would this fit the IIntegratorinterface?

  2. When an object calls its Update() method, what happens behind the scenes is that an integrator is used to provide the functionality. I'd like to switch the integration method on the fly, perhaps. Or at least instantiate the same kind of object with different integrators. To me, it sounds like a factory doing that and, for on-the-fly integrator switching.. perhaps a strategy pattern? What solution would be quite elegant and efficient in this context?

Without going into implementation details, here are a few design patterns that might be applied to your problem

  • Factory or Prototype To create objects at startup from a file, or clone them during run-time, respectively.
  • Composite This might be used to model PhysicalObjects, either as stand-alone objects or collections connected by strings, springs or gravitational forces.
  • Iterator or Visitor This might be used by PhysicsController to iterate over all physical objects (composite or stand-alone) and apply a function over them.
  • Strategy To select different IIntegrator objects and their integration functions at runtime.

Apart from the GoF book (Amazon), a good online resource is here

I keep reading over and over again that one should avoid using singletons for various reasons. I'm wondering how to correctly handle a situation where a class represents a unique system resource. For example, a AudioOutput class using SDL. Since SDL_OpenAudio can only be open once at a time it makes no sense having more then one object of this type and it seems to me preventing accidentally making more then one object would actually be good.

Just wondering what experienced programmers think about this, am i missing another option ?

Using design patterns wisely is a tricky questions, and it requires a lot of practice.

I have seen a lot of people using Singleton just because it "sort of" fits what they need to do. And this often results in disasters, for example in case of multi-threaded environments, or just as it was meant to hide a design flaw and needed a complete system redesign later on.

I'd say you need to think about a few things when considering Singleton:

  • Do I really need to have only one instance of my object? Am I not trying to hide some design flaw?
  • Does it make sense that my object can be accessed globally?

But I'd say don't spend too much time on it: it may not be always the best solution, but this is still an acceptable solution in some cases, and unless you're in a multi-threaded environment, you'll probably rarely have issues. It's mainly a design choice.

If you want to gain more knowledge about design patterns, I advise this book, which is pretty much the reference on the topic.

I'm an embedded programmer - primarily very small systems where I deal with data as bits, not objects.

I'd like to learn how to program for Mac and PC using their native libraries (Cocoa and .Net). I've hacked a few things together in Xcode and Visual Studio, but I feel like I'm hacking, not programming. I put things in AwakeFromNib without knowing if that is inviting a bug or bad style or just fine. There are fundamental concepts of programming for desktop applications that I need to learn, I think.

Can you recommend resources or books on the subject? I'm especially interested in how to write good code for this scale of program - collections of best practices, coding standards, etc.

Edit: There are lots of resources available on good code in general. Those are definitely must-reads, but I am looking here for resources that are specific to writing desktop applications. Resources that would say, for instance, what typically belongs in AwakeFromNib, not just when this callback is triggered.

A good book on design patterns will take you a long way in getting a feel for how to work with some of the built in structures in cocoa, like awakwFromNib, windowDidLoad, etc.

Here's one recommendation:

After you've read a couple of chapters in that book, you might want to pick up a good book that goes specifically into the framework and development environment you want to start learning about.

enter image description here

I have a menu with multiple DropDowns. I added code but at present, it entirely resides in the code-behind file. I want to use any design pattern to handle in an easy and uncluttered way the variety of choices.

The report generation criteria is prepared as follows:

Report Type DropDown options include:

  1. Scheme Type-wise
  2. Scheme-wise
  3. District-wise
  4. Block-wise
  5. All

By default, only the first DropDown is enabled. Selecting an option from this DropDown, enables the respective DropDowns.

Not only this, values of Scheme, District and Block DropDowns also change when an item is selected from any of these DropDowns or Scheme Type DropDown using AJAX.

It involves a variety of SQL queries and Enabling/Disabling DropDowns often. My present code has become cluttered with many IF and EndIfs.

I want to know whether Observer pattern or any approach using Classes be used to simplify this operation. Any way to make this multiple selections and filling of DropDowns manageable and simple?

Edited below to clear requirements

Let me clarify further.

The first DropDown is the key DropDown which is enabled by default when the page opens. All the other DropDowns are disabled by default. But this does not mean that Cascading DropDown is the correct choice because, the selection from the child DropDowns is random.

The whole plan is to simplify the code in an understandable form for each DropDown. There are many Ifs and ElseIfs involved to pick the correct query depending upon the selection.

For example: The user selects, District-wise report from the Report Type primary DropDown. In this case, three child DropDowns are enabled, viz.

Scheme Type



If user selects "ALL" from Scheme Types List, all types of schemes in all categories gets filled in the Scheme DropDown.

If user selects a particular Scheme Type from the options: Urban, Rural or Other, the Scheme DropDown filters the name of the schemes.

Now, Scheme DropDown also has an option ALL. The user can select ALL or pick any particular scheme.

Same is with District. If ALL is selected, schemes in the Scheme DropDown takes all schemes in all districts, but if a particular district is selected, the Scheme DropDown must fill the filtered schemes of this district.

Please note that in this case, we are now moving in a reverse order because District DropDown is again filtering the Scheme DropDown.

The same is applicable with the Block DropDown.

There are variety of conditions to be checked other the selected option. Suppose the user didn't select any option or the user selects ALL.

I want to create separate classes with the names of each DropDown. These classes should keep hearing notifications (Observer) for any changes in the DropDown.

I guess I was able to clarify.

If I'm understanding your paradigm correctly, really, you have one drop-down (Report Type) that determines whether to select by Scheme Type, Scheme, District, or Block (or all of the above). If you did not have the "All" option, I would suggest either having only two drop-downs (one for Report Type and one whose label changes to match) or eliminating the Report Type drop-down and putting a radio button next to each of the others to select which you want. When including the "All" option, you might not to complicate things much more; for instance, you could add one more radio button and enable all four drop-down lists.

However, you ask about the Observer Pattern. From GoF, the Observer Pattern is useful when:

  1. An abstraction has two aspects, one dependent on the other;
  2. A change to one object requires changing others, and you don't know how many objects need to be changed; or
  3. An object should be able to notify other objects without making assumptions about who these objects are.

I'm not entirely sure any of these situations applies here. The second situation has some similarities to your problem, but you do know what needs to be changed and how. If the only updating you are doing is by Report Type, it's just a matter of enabling or disabling the right drop-down menu. However, you say that the other drop-downs affect each other, probably in the "All" option. Even in this case, I'm not sure the Observer Pattern per se is the most helpful. Since you are populating the drop-downs using SQL, I'm guessing you might be using a number of different stored procedures (or ad-hoc queries) depending which parameters you need. What I might suggest instead is to have only one query per drop-down, making judicious use of NULL. For example, to populate Block from the other values, you might have:

    @SchemeTypeId INT NULL,
    @SchemeId INT NULL,
    @DistrictId INT NULL
SELECT b.BlockId, b.BlockName
FROM   Blocks b
INNER JOIN SchemeTypeBlocks stb ON b.BlockId = stb.BlockId
INNER JOIN SchemeBlocks sb ON b.BlockId = sb.BlockId
INNER JOIN DistrictBlocks db ON b.BlockId = db.BlockId
WHERE  (@SchemeTypeId IS NULL OR stb.SchemeTypeId = @SchemeTypeId)
AND    (@SchemeId IS NULL OR sb.SchemeId = @SchemeId)
AND    (@DistrictId IS NULL OR db.DistrictId = @DistrictId)
ORDER BY b.BlockName

Without knowing your database, I do not know exactly what will work, but the idea is that you just pass NULL for anything you do not yet have selected. This could perhaps simplify your code a bit.

If this doesn't answer your question, let me know what I can clarify.

I'm looking for a good online resource of software patterns. Preferably something with a comprehensive selection and concise well written explanations, not just a collection of links. .Net examples would be nice, but not essential.

Grab this book:

P of EEA By Martin Fowler

Here's the online info of that book

I recommend Head First Design Patterns book from Freemans. These are general design patterns applicable in most OO languages. I recommend this book as an introductory book to design patterns. After this book the GOF book would be another recommendation (but not as a first book).

I'm reading this article about perils of trying to mimic OOP in JavaScript and there's the following:

In JavaScript, factory functions are simply constructor functions minus the new requirement, global pollution danger and awkward limitations (including that annoying initial capitalized letter convention).

JavaScript doesn’t need constructor functions because any function can return a new object. With dynamic object extension, object literals and Object.create(), we have everything we need — with none of the mess. And this behaves just like it does in any other function. Hurray!

Am I right to assume that given this approach we should replace this code:

function Rabbit() {
    this.speed = 3;

Rabbit.prototype = {
    this.getSpeed = function() {
        return this.speed;

var rabbit = new Rabbit();

With this:

function RabbitFactory() {
    var rabbit = {
        speed: 3

    Object.setPrototypeOf(rabbit, {
        getSpeed: function() {
            return this.speed;

    return rabbit;

var rabbit = RabbitFactory();

Basically I would distinguish 3 approaches to create an object in JS:

  • Class
  • Constructor
  • Factory

Here are 3 examples (considering your Rabbit's one)

// class
class Rabbit {
  constructor() {
    this.speed = 3; 
    // it would be so nice to have just 'static const speed = 3;' instead of
    // using constructor for that
  getSpeed() {
    return this.speed;
let rabbit1 = new Rabbit();

// constructor
function ConstructorRabbit(){ }
ConstructorRabbit.prototype.speed = 3;
ConstructorRabbit.prototype.getSpeed = function() {
  return this.speed;
let rabbit2 = new ConstructorRabbit();

// factory
const rabbitProto = {
  speed: 3,
  getSpeed() {
    return this.speed;
function factoryRabbit () {
  return Object.create(rabbitProto);
let rabbit3 = factoryRabbit();

I'm not sure that there are so many pros to use only factory for creating objects, but probably I can single out the one. As mentioned in the article if we refer to very famous 'Design Patterns', so we should prefer object composition instead of class inheritance. And I'm totally agree with that postulate, thus returning back to JS and ES6 classes, we can say that prototype delegation may be better than class inheritance in some cases.

But also, we shouldn't forget this (as mentioned in the article as well) statement: "How it’s implemented doesn’t matter at all unless it’s implemented poorly". And this one, I would say, is a really good one.

Is it really important to know algorithms to build mobile applications? I have strong understanding of development tools and design pattern as well as strong knowledge of OOP and MVC.

So, is it required to know hardcore algorithms to become a good mobile application developer?

I can understand that if you want to create games then YES it is obvious that we must know all the AI related algos to be competent. But I am asking for just simple data driven application building.

I think it's irrelevant being for the mobile area or not. You should always try to achieve the best possible solution (there aren't perfect ones). In the mobile area, particulary, performance is very important, because we are talking about small devices, that although in recent years have been getting a major hardware boost, you should always take special care. I always use memory leaks to check if something is wrong with what I do. I also check the heap memory to see if there is something consuming too much memory. Battery is also a concern and you should also test if your application is using too much.

At the moment I am really focusing on the architecture of the application, a working application in the current standards (at least on my owns) is not enough. Knowing patterns is a powerful tool, and you should read about those (one of the best is this one). Maintenance's costs are a major factor these days, and you should try to achieve the maximum code reusability and cleanness. Always assume that the client will change spec and always keep in mind that someone else in the future will maintain your code, so avoid long methods and over complex code (unless you have to do it). Also remember to leave comments, even if something is really simple, be humble... In a month you might not now what that "simple" stuff did. Those things are fairly easy to achieve when you are starting a project from scratch but a pain when you need to start thinking about those when the project is going to production in one week..

So as for your question: is it required to know hardcore algorithms to become a good mobile application developer?

My answer is: No, it helps, but there are others important parts when developing, besides algorithms.

I've currently completed one of two phases of a project that required I write database information to XML using C++. While use of a third party tool was used to do the actually formatting of XML tags and data, I still had to design a model along with business logic to take the database tables and map them into XML structures.

For this I ended up creating an individual class for each XML structure, resulting in a large amount of classes (~75). Each class had the knowledge of how to read its associated table and serialize itself to XML through the third party tool. In the end the system worked very well ( on time and budget ) and output errors were extremely easy to find.

Phase two is almost identical however instead of formatted text it will be binary data. So while I am still considering utilizing the same strategy used in phase one, I would like to inquire, is a better method or design pattern that would lend itself to this problem? Particularly, due to the large amount of dependancies in some of the XML classes in phase one, unit testing was very difficult.

You are describing a classic application of the Visitor pattern. You need for two purposes to traverse your object model, one time outputting XML, the other time binary data. It's well explained in the gang of four's book.

Each element of your model has to accept a visitor of a recognised type (typically IVisitor), and it then calls a method called, typically, AcceptVisitor on this visitor. This is the method that translates the object into XML, binary data, printable format or whatever. It may also then direct the visitor to child objects and so on. Then you write an XmlVisitor that implements IVisitor, and "visit" your structure with it - the result is XML. Similary, you can "visit" with a BinaryVisitor and get your binary output.

Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.

Quoted from GoF:

Use the Factory Method pattern when

  • a class can't anticipate the class of objects it must create
  • a class wants its subclasses to specify the object it creates
  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.

I am a web application developer using Coldfusion 9. I have incorporated the use of cfc's in my code for some time. I would done like to incorporate more OOP principles in my design.

I am looking for books, tutorials, videos, etc that cover application design and interaction using OOP principles.

Most of the material I've found covers the object design but not they are used in application design.

Thank you for your suggestions.

Once you are past the fundamentals of Object-Oriented concepts, you need a solid handle on how to apply those concepts to your real-world projects.

An understanding of the basic Design Patterns is of significant value. You will want to start with Design Patterns: Elements of Reusable Object-Oriented Software, which defines these patterns, many of which are commonly used in OO design and development. For a more real-world, personal approach to the patterns, consider Head First Design Patterns, which builds off the first book, and demonstrates real problems that poorly designed OO systems suffer from, and how you can begin to think about solving them.

You will also want references to actual ColdFusion-related implementations of OO systems. Object-Oriented Programming in ColdFusion is a very good start.

Finally, you should immerse yourself in existing, well-known ColdFusion applications that employ OO techniques. ColdBox is a framework for building CFML-based websites that implements many OO techniques, including Aspect Oriented Programming and Dependency Injection and you can learn a lot from this framework and websites that have been build using it.

So I've been reading about template methods on Objective-C and I am trying to understand what's so special about them. From my understanding any method in a Base class can be over-ridden and super can be called? So is a template method anything more than overriding a method in the base class?

If I'm wrong, can you please explain what a template-method-pattern is, and can you provide an example?

From my understanding any method in a Base class can be over-ridden and super can be called? So is a template method anything more than overriding a method in the base class?

Yes, this is much more that just overriding a base class method. Template methods is a way to implement an algorithm where some steps are subclass dependent. For example consider a method in Base which has three major steps, f1, f2 and f3. Each steps contains a number of statements. Here f1 and f3 are same in all subclass, but f2 is subclass dependent. So what to do here? You can override the whole method in subclass copying statements of f1 and f3, but that is a waste. So you provide only f2 in subclass. And in this is way you define the algorithm (execute f1, then execute f2, then execute f3) in base class but provide overriding hooks for subclasses (f2). Note that, template method in base class is final, so subclass can't change the algorithm, e.g. it can't change the order of f1, f2 and f3, neither subclass can omit the steps f1, f3.

In short, Template Methods pattern is not just overriding, it is the use of inheritance to handle some specific situations. This is not Obj-C specific, and I can't provide you anything specific to Obj-C. To get an overall idea about this pattern, I recommend the followings:

  1. Design Patterns book by GoF
  2. Head First Design Patterns
  3. Wikipedia article on Template Method

And there are also tons of tutorials/articles on web. The basic idea is not Obj-C dependent.

Some of people recommend the factory pattern in java. I am not aware of that. What is the main objective to use the factory pattern in java and Give me your suggestion which type of pattern is useful?

The objective depends on the type of factory pattern, e.g. Abstract Factory: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes." from Design Patterns

Most factory patterns allow you to loosen the coupling between the creation request and the class of the object created. This allows you to reserve the right to change your mind.

This approach is commonly used to enable unit testing with stub or mock objects.

This question is similar to

  1. What is the most common design patterns for any windows forms application?
  2. UI Design Pattern for Windows Forms (like MVVM for WPF).

But I would like to ask something more specific: I want to know what design patterns Microsoft use to built their impressive array of desktop apps suites, including VS 2008, Microsoft Office and so on.

Anyone has any ideas? I look around but I can only find vague details, at most. There doesn't seem to be a lot of information out there on this.

Edit:OK, maybe I would relax the question a little bit: Anyone knows how any major software producers ( not just Microsoft) build their desktop application?

The design patterns found in the Gang of Four book all came from examining real-world software applications and seeing what common solutions were used. I would guess that the patterns presented in the book were also generalized to be more useful to a general population.

Given that fact, I would expect that any medium or large scale application would contain at least a few patterns or variations on patterns described by the Gang of Four.

Are there set design patterns or does each individual sufficiently skilled software developer recognize and reduce their code to develop new patterns. Effectively creating their own "design" patterns.

Edit - Thanks for the responses. In reality I'm just refactoring and/or reducing code where the problem should have first been compared to existing design patterns before the code was written. If a match was found then I should have used it otherwise I'm simply refactoring code (which is not a bad thing and usually doesn't produce any new generally useful "patterns".)

There certainly are set, recognized patterns, as laid out nicely by the "gang of four"'s Design Patterns book. There are also patterns like CAB and SCSF that teams like the Microsoft Patterns and Practices team publishes. Does that mean that every pattern is covered? Certainly not. Developers and teams often come up with their own patterns that achieve their needs and that they use across their entire project.

So we'd like to not reinvent the wheel - use patterns that are already out there - but don't feel that you're constrained to only what others are doing.

As a new grad attending interviews, I feel that the sections I do the worst are in system design questions like How will you design a search engine? Or How do you support google like instant responses

I make answers and it sounds convincing to me, but I feel I can do better by studying such systems themselves to get an understanding of the problems that arise and needs to be solved. Can the community point me to resources (blogs, online classes, text books, white papers, academic publications anything.,) to help me along this task?

Some articles and books about architecture:

And of course the regular design pattern books.

Do you know any resource/s that teaches design patterns by scenario.

Ex : One day x person needs a converting A/C tool between different country resources.....

Answer : Adapter Pattern .. because....


Design Patterns, Gang of Four.

In a language agnostic point of view, you should buy definitely this (easy to learn through examples):

or Refactoring To Patterns for a more cause-and-effect approach:

Five years ago I used to program in SAS. Since then I've been doing software QA of various types. Mostly manual (video games + web apps) testing with a tiny bit of automation.

I'd really like to shift careers back into programming. Specifically the Android platform has caught my attention. These are the books I've been reading and working through.

  • Learning Java, Third Edition - O'Reilly
  • Beginning Android 2 - Mark Murphy
  • Hello, Android - Ed Burnette

However, I think I need something that looks at programming from a less language dependent standpoint. Something that takes a bird's eye view if that makes sense.

It's very easy to see how particular functions work, but I'm looking to get a better sense of how all the pieces fit together. How does one split up an app into individual classes and packages? Do I have a method in main that shuffles my deck of cards (object) or does the class deck of cards have a method I can call to shuffle itself?

I think I'm looking for a book on object oriented design?

I've also been working through the tutorials and examples at and also in the three books I've been reading so far.

Maybe I just need to spend more time coding though?

You might want to read about design patterns. The classic book is Design Patterns by the "gang of four", Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

The books that did the most for me are: Agile Software Development, Principles, Patterns, and Practices (among many other design issues, this one actually tackles strategies for organizing an app into packages, which is pretty interesting) and Head First Design Patterns which is, I think, a much easier read than the Gang of Four book mentioned earlier.

Good luck!

I am learning C++ I don't know much about this stuff except the fact that programming design pattern is neccesary when actually working in large projects.I hope its correct to some extent.

Is this common to all object oriented languages or do I need to look specifically into C++ design patterns.

Also How does it helps you.Is this realy important to learn as a C++ programmer.

Please suggest

You will hear discording opinions about design patterns, in the programming community at large.

In my opinion, it is sure that there are abstractions that patterns encapsulate that are really useful (factory, singleton, delegate, etc.). I use patterns a lot, but I myself am sometime puzzled by the apparent lack of depth or level of insight that you get by reading a pattern description. This is also in tune with the proliferation of design patterns that specialize for any kind of things.

When the design hey are useful, they are a very good means of communication and certainly they guide you through the process of designing or defining the architecture of your app. They are useful both for small project and for large ones, and they can be applied at different granularity levels.

Patters are a generic concept and all programming languages support them. Anyway, if you work in C++, a book focusing on it is best, because you will get the pattern adapted to the characteristics of the language.

In my opinion, the really fundamental book about design patterns are:

GoF, Design Patterns: Elements of Reusable Object-Oriented Software

VV.AA., Pattern-Oriented Software Architecture Volume 1: A System of Patterns

VV.AA., Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects

Design patterns are solutions to commonly occuring problems in Design phase of a project.These patterns provide the solutions which we can use independent of programming language.For e.g. there is Singleton design pattern which ensures that there is only one instance of a class.Now there are numerous occaions on which this may be required.You can use the solution of these pattern and use in your code.

They provide the re usability in Software development .Put simply, design patterns help a designer get a design right faster.

For more better understanding you could refer Design Patterns: Elements of Reusable Object-Oriented Software

I am looking for a good and short article+examples of how working with interfaces. I am not interesting the technical part, but I need the design part. For example, how to programming using interfaces, when and how create implementations, design patterns for regular development with interfaces.

I have many similar classes that repeat themselves in several ways. I want to use interfaces and abstract classes in order to make things more modular - but I can't find out how to do it properly.

This book as been the canonical reference for design patterns and contains examples of using interfaces. However you may want to start at an even more fundamental level. Thinking in Java is what got me into object oriented programming, there are likely similar titles for C# though the content of the book should be mostly agnostic of the language. You may also search for online tutorials on object oriented programming.

Edit: Great book about patterns and their implementation and usage in C# is C# 3.0 Design Patterns

@Naor, its seems, based on your above comment "It doesn't seem logical to create interface for each class I have - right?" that the best book for you to read is HEAD FIRST; DESIGN PATTERNS - it has an incredible and easy way of teaching how to use an apply design patterns. I first read of them in this book and it has definetly changed my mind!!! By reading this you'll be able to read more complicated stuff like Martin Fowler, Patterns of Enterprise Application Archtecture - which I believe approaches exatcly what you want, real world applicatoins of patterns. Going straight to to GoF, or M. Fowler, or more complicated stuff may disspoint you or make you just lose time.

I had a, lets say, deficient program design/architecture class in undergrad and thus am really struggling on how to design programs given a problem*. I was wondering if there was a set of resources (books, websites, etc) or problems(kind of like** or path to help me work on this deficiency.

I'm looking for resources/problems/etc to better learn design/architecture patterns within programming.

A great example: For my job, I have implemented an MVC framework in PHP(custom, because I want to learn). I needed to bake User management into this framework and am just struggling with the implementation (I understand to use the $_SESSION var, I just want to user management to be modular and flexible like the rest). This post is not intended to solve my user management issue. I know fixing the design issue will fix this naturally.

I've looked around these here forums and haven't seen any great list of resources to draw off of. If anyone has anything or point me to a post that I missed, feel free to point me there. I really appreciate any insight/help/resource/etc that might be pointed out to me.

*I am familiar and can work with OOP/MVC frameworks, not completely proficient but I can do it **ProjectEuler, where I am tends to be more functional than anything else. I'm slowly working towards integrating OOP etc. But my architecture skills in programming are terrible.

tl;dr: I'm looking for resources/problems/etc to better learn design/architecture patterns within programming.

I'm not really sure what the question is, but if you are only looking for some resources, there is this a good book for architectures - Patterns of Enterprise Application Architecture by Martin Fowler, with some parts available online.

Than there are GoF patterns summed up by Gamma.

Software architecture in practice can be useful too.

Some basic intro to architectures is in this paper, it's kinda old, but still valid...

Basically, GoF patterns, Enterprise patterns and GRASP are patterns you should be aware of...

Was this helpful?

I would start with Head First Design Patterns and the Architecture sections of Code Complete by Steve McConnell. I think those 2 are the best introductions to the concepts and then move into the other stuff.

I have an abstract base class with two inherited classes. In both these classes I define a virtual method that is used by the constructor. Now I need to create a copy constructor, but I can not declare the copy constructor as virtual, but I want the method call inside it to be dependent on the type of object that is fed as argument. How can I solve this?

Right now I use the base class to define the type of argument, this doesn't work since the method I call inside the copy constructor is not defined in the base class.

Basically I need the copy constructor to be virtual.

There is a nice discussion of the Prototype Pattern here which could be helpful.

Prototype [Go4]


A "factory" class can't anticipate the type of "product" objects it must create.


Derive all product classes from an abstract Product base class that declares a pure virtual clone() method. The Product base class also functions as the product factory by providing a static factory method called makeProduct(). This function uses a type description parameter to locate a prototype in a static prototype table maintained by the Product base class. The prototype clones itself, and the clone is returned to the caller.

The reference to 'Go4' is for the seminal book on Design Patterns written by the "Gang of Four" authors.

I have an application that models a tree, with classes Tree, Node and Edge (I need the Edge class!), and I'm not sure how to represent the relationships in the class diagram for this. I've read other posts about this, but am still in doubt.

The Tree object have a pointer to a Node (its root), which I believe defines an one-way association (Tree -> Node) with multiplicity 1..1 in both ends. Is it right?

Each Node object have pointers to the edges that comes out of it (Edge objects). Since these edges only exist if the node exist, I believe it's a composition association.

But then I have, in each Edge object, a pointer to the target Node of the edge. How can I represent this relationship, considering I already have the Node -> Edge composition described above?

Also, if you're still reading :), each Node have a pointer to its parent Node. Here, I would use an one-way unary association, but I don't know which name to use for this relationship.

Thanks for any help.

The handling of a Tree structure in OO is solved by the Composite Design Pattern.

You seem to be slightly confused by the difference between aggregation and composition. Use composite when the lifetime of the whole and the part are equal, use aggregation where the lifetime of the parts is different, i.e. you add and/or remove parts from the collection.

I have a question. I need to create a little thing to do with products. Now I can have say 7 different types of products. Some are subtypes of others e.g.

 - Vans
   - petrol
   - diesel
 - City
 - Hatchback
 - Saloon
 - Estate
   - petrol
   - diesel

Now, for the sake of the argument all my City, Hatchback and Saloon cars are hybrid/gas/whatever and I do not plan to sell petrol and diesel ones. However there is a possibility that I may have petrol and diesel saloon cars sometime in the future, but it's not like I am going to have 20+ types of products. If it is going to go up I will have probably 2-3 more types.

From what I understand Prototype Pattern may be good one here for I will be able to avoid duplication between estate->petrol and van->petrol ... but then again Van cars will have different characteristics than say city car e.g. maximum loading dimensions.

I have been reading extensively about design patterns and one thing I remember for certain is not to use pattern when you don't need it. Now the question is - do I need it?


The Decorator Pattern is probably the most straight forward one to use and would be a good one to extend concrete objects functionality and/or characteristics.

Here is some light reading: Head First Design Patterns - CH3 pdf

FYI, couple must have's for learning and referencing design patterns regardless your language of choice:

1) Head First Design Patterns

2) Patterns for Enterprise Application Architecture

3) Design Patterns: Elements of Reusable Object-Oriented Software

And sites:

1) DoFactory

2) StackOverflow Design Patterns Newbie

There are a few others, I'll have to dig them up.

I have been looking for tutorials or books about design patterns in qt and so far i have found one book, "Introduction to Design Patterns in C++ with Qt 4".Has anyone read this book?.Also,where can i read about design patterns implemented in qt?.

Introduction to Design Patterns in C++ with Qt 4 uses Qt 4.1 to demonstrate its concepts. So much has changed since Qt 4.1 that I suggest first learning about design patterns, and then learning Qt (separately). Once you understand design patterns, you can browse the Qt source code and be able to recognize the patterns yourself.

Design patterns - Elements of reusable object oriented software is a great book on design patterns with examples in C++.

I'm looking for a good book or article about design patterns and their use, the examples should be in java / c++ would be nice or any other object oriented programming language.

Can you recommend anything?

thank you.

Three things I'd suggest:

Design patterns - Elements of reusable object oriented software - THE original design patterns book. Has examples in C++.

Head first design patterns - a very nice books detailing design patterns in Java. An enjoyable view.

Real world examples of design patterns in JDK - a terrific Stack overflow answer by BalusC.

i need to start refine my memory so i like to practice a bit do you know good site like : for java?

I would say you can use java exercises....just write it in c++, its the same...
from The "Gang of Four":
Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

For reference and you'll be set up :)

Is Abstract Factory just a set of Factory Methods? Or is there any other difference between these patterns?

According to Design Patterns, p. 95:

AbstractFactory classes are often implemented with factory methods, but they can also be implemented using Prototype.

Is there a shortcut to take a base class and transform it into one of its derived classes inside of a program? For example:

Let's say I have three classes, a base class and two derived classes:

class cColor {

class cBlue : public cColor {

class cRed : public cColor {

and then I create a Color class inside of my program:

int main(){
cColor unsaturated
return 0;

Is there someway to transform unsaturated from a cColor class to a cBlue or cRed class? Would a similar solution be to store unsaturated in a pointer, create a new cBlue or cRed class from the pointer and then delete unsaturated?

What you want is to use the State pattern from GoF page 305, what you are proposing is very dangerous casting an instance of a base object to a derived class that it is not. Admittely you might get away with your simple example, but that will fall apart as soon as a derived class adds some state, or alters the vtable.

I've been a software developer for 10 years and came all the way from a wild world of assembly language programming, then server side of C++ and COM, and for the last 5 years I was comfortably settled in a quiet world of .NET, C# and development of business applications.

The problem is - the last couple of years was so comfortable and I was also spending almost half of my time doing a BA's work, that I feel like I forgot a good part of low level C# language, Design Pattern and ASP.NET. And after almost 5 years of not using C++ for a big projects my skills in that language are even worse.

That does not mean I can't program - I do it every day and quite successfully - but I feel what I would not be able to pass most of tough job interviews should the need arises, which is very likely in a current recession. And the reasons I think I would not pass - is that I forgot all the standard things what usually people are being asked on the interviews (e.g. I use the design patterns - but if you ask me - which pattern what that - I would probably not give you the correct name, because all he DP for me are just a smart ways of using static functions and virtual functions).

Can someone please point me to a resource or give me an advice (can I have both please?), how can I quickly (in a week or so) could brush up my knowledge of C#/.NET, DP and ASP.NET to the level of the very good senior dev (whom I was a 2 years ago). As for the C++ - I am willing to spend a month to get my knowledge back again, but this is of less priority.

Please do understand me right - I am not a newbie and all these things I knew before - just want to be back in business 100% again.

Thank you.

Design Patterns are covered in many books today. The stanard of course is the "Gang of Four" book named "Design Patterns".

Put OO, Agile and Pattern together

Another book is more hands-on and combines Design Patterns with an other new thing -- "Agile Development". The good thing is, that design patterns are presented in live examples and interestingly presented in context. I think Robert C. Martin also brings a lot of insight into many OO development principles. The book is called Agile Software development.

But of course, it depends how far you want to go. Do you really want to brush up your knowledge (then I could maybe give further hints) or do you want to just be upto date for interviews?

I've worked with designing databases for a loooong time, and these days I'm working in C# too. OO makes sense to me, but I don't feel that I have a good grounding in the deep theory of OO design.

In database land, there's a lot of theory around how to design the structure of a database, the main notion being normalisation. Normalisation directly steers the structure of a database and to some extent dictates how to arrange entities in a database.

Are there any similar concepts behind how to design the structure of an Object-Oriented program?

What I'm reaching for is one or more underlying theoretical principles which naturally guide the developer into the "correct" design for the solution to a given problem.

Where can I look to find out more?
Is there a go-to work I should read?


Thanks to everyone for their answers. What I'm reading seems to say that there is no "Grand Theory of OO Design", but there are a bunch of important principles - which are largely exemplified by design patterns.

Thanks again for your answers :)

The book "Design Patterns" is your next step.

But, you don't have to use an OO approach to everything. Don't be religious about it. If a more procedural approach feels more straitforward, then go with that. People new to OO tend to overdue it for a while.

I think Agile Software Development, Principles, Patterns, and Practices is quite good.

It provides a lot of in-depth disccusion of OO principles listed here:

  • The principles of Object Oriented Design and Dependency Management
  • SRP — The Single Responsibility Principle
  • OCP — The Open Closed Principle
  • LSP — The Liskov Substitution Principle
  • DIP — The Dependency Inversion Principle
  • ISP — The Interface Segregation Principle
  • REP — The Reuse Release Equivalency Principle
  • CCP — The Common Closure Principle
  • CRP — The Common Reuse Principle
  • ADP — The Acyclic Dependencies Principle
  • SDP — The Stable Dependencies Principle
  • SAP — The Stable Abstractions Principle

Be careful some of the design patterns literature.

There are are several broad species of class definitions. Classes for persistent objects (which are like rows in relational tables) and collections (which are like the tables themselves) are one thing.

Some of the "Gang of Four" design patterns are more applicable to active, application objects, and less applicable to persistent objects. While you wrestle through something like Abstract Factory, you'll be missing some key points of OO design as it applies to persistent objects.

The Object Mentor What is Object-Oriented Design? page has mich of you really need to know to transition from relational design to OO design.

Normalization, BTW, isn't a blanket design principle that always applies to relational databases. Normalization applies when you have update transactions, to prevent update anomalies. It's a hack because relational databases are passive things; you either have to add processing (like methods in a class) or you have to pass a bunch of rules (normalization). In the data warehouse world, where updates are rare (or non-existent) that standard normalization rules aren't as relevant.

Consequently, there's no "normalize like this" for object data models.

In OO Design, perhaps the most important rule for designing persistent objects is the Single Responsibility Principle.

If you design your classes to have good fidelity to real-world objects, and you allocate responsibilities to those classes in a very focused way, you'll be happy with your object model. You'll be able to map it to a relational database with relatively few complexities.

Turns out, that when you look at things from a responsibility point of view, you find that 2NF and 3NF rules fit with sound responsibility assignment. Unique keys still matter. And derived data becomes the responsibility of a method function, not a persistent attribute.

I was reading "Design Patterns: Elements of Reusable Object-Oriented Software", (specifically the chapter about the prototype design pattern) and it stated that...

"Prototype is particularly useful with static languages like C++ where classes are not objects, and little or no type information is available at run-time." (pg 121)

(emphasis mine)

I had always thought that classes were synonymous to objects, and I'm confused as to what this statement means. How are classes not objects, and why does it matter if a language is static?

In C++, this declares a class:

class A {
  int a;

whereas this declares an object:

A a;

One cannot interrogate a class a run-time, as one can interrogate an object. It makes sense to say, "object 'a', what is your address? Please invoke operator+. etc." In C++, with its static typing, it makes no sense to say, "Class A, what is your list of members? Please add a new member, "b"."

In other languages (Python comes to mind), one can manipulate classes in this way, because each class is also an object. In addition to serving as a template for objects, the class itself is an object -- it can be printed, modified, etc.

Kindly, why should I supply the Generic class on the left side (variable declaration) and right side (object assignment) ? I can technically skip it left or right (see alist2, or aList2), what is the drawback of aList2 and aList3 compared to aList1 ?

ArrayList<String> aList1 = new ArrayList<String>();
ArrayList<String> aList2 = new ArrayList();
ArrayList         aList3 = new ArrayList<String>();

Bonus question, just came into my mind and it compiles, but what would that mean for aList4 and aList5?

ArrayList<String> aList4 = new ArrayList<>();
ArrayList<?>      aList5 = new ArrayList<String>();

Thank you in advance.

Kind regards, Hermann

You should use the Generic class that is best for your implementation. That is if you only care about having a collection of items you should use Collection, if you need to preserve order you should use the interface List. The reason for this is that you should:

Program to an interface not an implementation GoF

Why is this good? Well because it makes it a whole lot easier to change implementation. Suppose that you'd like to change from ArrayList to LinkedList in the future. Then it's just a matter of changing the call to new ArrayList to new LinkedList. The same goes for your own code, try to always use an interface to any class that isn't just a dataobject. This will make you think about the interfaces between your objects instead of the implementation, that way you can always code up something crappy at first and then refine your implementation whenever you find that you need to without breaking your code.

article for more info

So why is it bad to not infer the type to your examples? Well mainly because the program won't know what types the list contains, which means that either you have to cast those objects to their type by knowing the type or by figuring out the type.

As for why aList2 is bad I'll just refer to this discussion

Maybe I'm little morose, but I do not feel comfortable with that book. Anytime I ask someone for a good book on this subject they recommend me Head First.

Is there another "excellent book" that is not the Head First ? More straightforward and less fun.

Thanks in advance.

There's the classic Design Patterns: Elements of Reusable Object-Oriented Software, aka the "Gang of Four" (GoF) book.

The Head First book is great for an introduction to the topic and makes it more approachable and less dry than the GoF book.

Obviously, "Hello World" doesn't require a separated, modular front-end and back-end. But any sort of Enterprise-grade project does.

Assuming some sort of spectrum between these points, at which stage should an application be (conceptually, or at a design level) multi-layered? When a database, or some external resource is introduced? When you find that the you're anticipating spaghetti code in your methods/functions?

There is no real answer to this question. It depends largely on your application's needs, and numerous other factors. I'd suggest reading some books on design patterns and enterprise application architecture. These two are invaluable:

Design Patterns: Elements of Reusable Object-Oriented Software

Patterns of Enterprise Application Architecture

Some other books that I highly recommend are:

The Pragmatic Programmer: From Journeyman to Master

Refactoring: Improving the Design of Existing Code

No matter your skill level, reading these will really open your eyes to a world of possibilities.

Someone in other question told me to implement following in my java program. but i am very new to java and i don't know how to start or convert my simple program into that catregory

Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
dependency injection. 
program to the interface:

NOw does that come inside some framework framework. i mean should i start learning spring and these things will come with that and i don't need to learn from one by one.

Or i can implement above technologies one by one without framework.

Any tutots for that

In short:

  • Data Access Layer is a module of your application that provides interface to your data. Data may be in SQL database, XML, file wherever. You write interfaces and classes that provide interface to access data usually as VO or DTO via DAOs
  • Service Layer contains most of the use-case logic. Service layer interacts with Data Access Layer to perform tasks in given use case. I did not find a good article on introductory service layer. You may see here and there
  • Controller is the one that interacts with Service Layer and/or Data Access Layer and/or other controllers in order to perform a specified client's tasks.

    For example, a sign-off button controller will request a sign-off action/service to invalidate user's sessions on all services that user is logged on to, then it will choose an appropriate view or log-off web-page to forward user to.
  • Presentation is your user interface. It can be a web-page made of HTML or Java Swing window or anything that user interacts with. GUI commonly known term for it. This is what your users will be interacting with using mouse clicks, scrolls, swipes, drag-and-drop. These actions are mapped with controller which performs action based on what user performed on UI.
  • Dependency Injection is a way to wire various components. There are a lot of resources on web. You can look in Martin Fowler's this article. It's basically a mechanism that allows components to behave much like plug-and-play devices, if you know what plug goes where.

    Spring is a good implementation of dependency injection. You may not want to write your own framework, and at this stage, you should rather not. There is a Spring MVC framework that can do things for you.

But I suggest you start from very basic. Instead of jumping on jargon, read from basic. Start with a good book on application development using Java. You can also look into

You might want to check out Domain Driven Design. The Code samples are in Java. The things you listed are design related more than any specific technology.

The benefits of using composition over inheritance are quite well known;

What are the cases in which the opposite is preferable?

Practically, I can see the advantage of forcing a base constructor, but I would like to know other people's opinion about other cases/domains.

I believe the famous recommendation of "favor composition over inheritance" was coined in the GoF Design Patterns book.

It says (p.20):

Favor object composition over class inheritance.

Ideally, you shouldn't have to create new components to achieve reuse. You should be able to get all the functionality you need just by assembling existing components through object composition. But this is rarely the case, because the set of available components is never quite rich enough in practice. Reuse by inheritance makes it easier to make new components that can be composed with old ones. Inheritance and object composition thus work together.

Nevertheless, our experience is that designers overuse inheritance as a reuse technique, and designs are often made more reusable (and simpler) by depending more on object composition. You'll see object composition applied again and again in the design patterns.

Notice that this statement refers to class inheritance, and must be distinguished from interface inheritance which is fine.


Both are ways to achieve reusability, but the advantage of composition over inheritance is dynamism. Since the composition can be changed dynamically at runtime this represents a great advantage, whereas inheritance is statically defined at compile time.


Also, composition is based on using the public interfaces of the composed objects, therefore objects respect each other's public interfaces and therefore this fosters encapsulation. On the other hand, inheritance breaks encapsulation since child components typically consume a protected interface from the parent. It is a well known problem that changes in the parent class can break the child classes, the famous base class problem. Also in inheritance parent classes define the physical representation of subclasses, therefore child clases depend on parent classes to evolve.


Another advantage of composition is that it keeps classes focused on one task and this foster cohesion as well.


Evidently a problem with composition is that you will have more objects and fewer classes. That makes a little more difficult to visualize your design and how it achieves its goals. When debugging code it is harder to know what is going on unless you know what exact instance of a given composite is currently being used by an object. So composition makes designs a bit harder to understand in my opinion.

Since the advantages of composition are multiple that's why it is suggested to favor it over inheritance, but that does not mean inheritance is always bad. You can achieve a great deal when inheritance is properly used.

Interesting References

I would suggest a study of GoF Design Patterns to see good examples of both types of reusability, for instance a Strategy Pattern that uses composition vs a Template Method that uses inheritance.

Most of the patterns make a great deal of interface inheritance and then object composition to achieve their goals and only a few use class inheritance as a reusability mechanism.

If you want to delve more the book Holub on Patterns, on chapter 2 has a section called Why extends is Evil that delve much more on the liabilities of class inheritance.

The book mentions three specific aspects

  • Losing Flexibility: The first problem is that explicit use of a concrete-class name locks you into a specific implementation, making down-the-line changes unnecessarily difficult.
  • Coupling: A more important problem with implementation inheritance is coupling, the undesirable reliance of one part of a program on another part. Global variables are the classic example of why strong coupling is bad. If you change the type of a global variable, for example, all the code that uses that variable—that is coupled to the variable—can be affected, so all this code must be examined, modified, and retested. Moreover, all the methods that use the variable are coupled to each other through the variable. That is, one method may incorrectly affect the behavior of another method simply by changing the variable’s value at an awkward time. This problem is particularly hideous in multithreaded programs.
  • Fragile-Base-Class Problem: In an implementation-inheritance system (one that uses extends), the derived classes are tightly coupled to the base classes, and this close connection is undesirable. Designers have applied the moniker “the fragile-base-class problem” to describe this behavior. Base classes are considered “fragile” because you can modify a base class in a seemingly safe way, but this new behavior, when inherited by the derived classes, may cause the derived classes to malfunction.

We are developing a middleware SDK, both in C++ and Java to be used as a library/DLL by, for example, game developers, animation software developers, Avatar developers to enhance their products.

What I would like to know is this: Are there standard "Best Practices" for the development of these types of API?

I am thinking in terms of useability, readability, efficiency etc.

There are lots of ways to design apis, depending on what you are solving. I think a full answer to this question would be worthy off a whole book, such as the gang of four patterns book. For Java specifically, and also just OO programming in general, I would recommend Effecitve Java 2nd Edition. The first is general and alot of popular programming patterns, when they apply and their benefits. Effective Java is Java centered, but parts of it is general enough to apply to any programming language.

Take a look at Framework Design Guidelines. I know it is .NET specific, but you can probably learn a lot of general information from it too.

What does it mean to Decorate a class or parameter?
What's the purpose and when would I do this?

Links to resources and direct answers are welcome.


Decorator was one of the original 26 patterns described in the Gang of Four "Design Patterns" book. They describe it well here.


Decorator : Add additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes

Patterns are language agnostic. They are descriptions of solutions to common problems in object-oriented programming. It's possible, even preferred, to discuss them without reference to a particular language. The examples in the original book were written in C++ and Smalltalk. Neither Java nor C# existed when the book was first published in 1995.

Here is definition of Strategy Pattern:

Strategy - defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

So, Strategy separate a functionality into two parts: one which doesn't change, and another which can change at some future time.

And, in MVC, they say that:

the controller is the strategy for the view

It means controller is vary and View might not change in the future.

I don't understand so much,yet. I think both of them can change in the future.

Please explain for me why people say that.

I suspect you may have seen the note "the controller is the strategy for the view" in the C3 wiki section on Model View Controller As An Aggregate Design Pattern, which is interesting, but a bit terse.

The idea is described a bit more completely in the introduction of Design Patterns, where the section on MVC says:

MVC also lets you change the way a view responds to user input without changing its visual presentation. You might want to change the way it responds to the keyboard, for example, or have it use a pop-up menu instead of command keys. MVC encapsulates the response mechanism in a Controller object. There is a class hierarchy of controllers, making it easy to create a new controller as a variation on an existing one.

A view uses an instance of a Controller subclass to implement a particular response strategy; to implement a different strategy, simply replace the instance with a different kind of controller. It's even possible to change a view's controller at run-time to let the view change the way it responds to user input. For example, a view can be disabled so that it doesn't accept input simply by giving it a controller that ignores input events.

The View-Controller relationship is an example of the Strategy design pattern. A Strategy is an object that represents an algorithm. It's useful when you want to replace the algorithm either statically or dynamically, when you have a lot of variants of the algorithm, or when the algorithm has complex data structures that you want to encapsulate.

Summarizing this a bit, you can use the same view with different controllers to have different behavior in different parts of your system, you can replace the controller at run-time to enable or disable particular functions, and the controller encapsulates the complex interactions of updating the model.

Hey guys , i'm a software Eng. student at my third year now i'm taking design patterns in a " software Design " course the problem is that those stuff are really hard to get do you know any simplified guide or videos to understand those concepts ?! my major is exam is next week and i need to prepare early , i hope you can give the simplest reference to understand them

I've heard that the Head First Design Patterns book does a good job at making things easy to understand if you're having issues.

I would check out Heads First Design Patterns by Kathy Sierra. She was the person who created the Heads First Series. It's much easier to understand compared to the Gang Of Four Book (although this is a good book), and it's set as a tutorial, and not just a book which talks about them.

I am a vc++ developer but I spend most of my time learning c++.What are all the things I should know as a vc developer.

I don't understand why people here post things about WinAPI, .NET, MFC and ATL.

You really must know the language. Another benefit would be the cross platform libraries. C++ is not about GUI or Win32 programming. You can write Multi-Platform application with libraries like boost, QT, wxWidgets (may be some XML parser libs).

Visual C++ is a great IDE to develop C++ application and Microsoft is trying hard to make Visual C++ more standard conform. Learning standard language without dialects (MS dialect as well) will give you an advantage of Rapid Development Environment combined with multi-platform portability. There are many abstraction libraries out there, which work equally on Windows, Linux, Unix or Mac OS. Debugger is a great app in VC++ but not the first thing to start with. Try to write unit tests for your application. They will ensure on next modifications that you did not broke other part of tested (or may be debugged:) code.

Do not try to learn MFC or ATL from scratch, try to understand STL. MFC is old, and new version are more or less wrapper around ATL. ATL is some strange lib, which tries to marry STL-idioms (and sometimes STL itself) and WinAPI. But using ATL concepts without knowing what is behind, will make you unproductive as well. Some ATL idioms are very questionable and might be replaced by some better from boost or libs alike.

The most important things to learn are the language philosophy and concepts. I suggest you to dive into the language and read some serious books:

When here you will be a very advanced C++ developer Next books will make guru out of you:

Remember one important rule: If you have a question, try to find an answer to it in ISO C++ Standard (i.e. Standard document) first. Doing so you will come along many other similar things, which will make you think about the language design.

Hope that book list helps you. Concepts from these books you will see in all well designed modern C++ frameworks.

With Kind Regards,

I am new to the pattern way of coding and would like to start implementing patterns in my code. I have a webservice that has multiple operations and receives different xml inputs for each operation(having its own schema). I would like to implement a pattern to validate the input provided.

My design: Have an interface IValidate implement the interface to EntityAValidate, EntityBValidate etc.., each implemented validate method will check for validity of the xml and also do the individual node validation such as the string cannot have special characters etc..,

My questions : Can we use any other design? please let me know the pattern name How can I reuse some common validations like numeric check, date check across operations How can the selection of corresponding validator be done automatically?

I would recommend you to start reading about DP and then get to know many of them. This way you will just realize when and which one fits or not your needs. Design Patterns are meant to be used when you do have an specific need, its means that "the most you use the better" is a very bad approach. Hope it helps!

Im leaving two recomendations on DP literature; Head First - Design Patterns and Elements of Reusable Object Oriented Software

I am writing a small website and for every page, I am putting a server name to its header:

func httpSignUp(rw http.ResponseWriter, req *http.Request) {
    rw.Header().Set("Server", SERVER_NAME)

I am wondering if there's a way that I can set http.ResponseWriter's default server name, so I don't have to use the same line over and over?

"Prefer composition to inheritance" - Gang of 4

Inheritance simply wasn't designed into Golang in the first place. ;)

If you are looking for detailed explanations on the why part, I believed this has been answered on SO, hence I would just point you to it: Embedding instead of inheritance in Go.

Well, you can actually achieve the same result with adapter design pattern, which enables you to extend functionality from a built-in library, and to me, its way more flexible than inheritance.

func adapter(h http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        r.Header().Set("Server", SERVER_NAME)
    h.ServeHTTP(w, r)

Or pass in serverName as parameter:

func adapter(h http.Handler, serverName string) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    r.Header().Set("Server", serverName)
    h.ServeHTTP(w, r)

Finally, you have the flexibility to choose which handler(s) to be 'inherited':

http.Handle("/path", adapter(your_handler))

Or if its meant for every handlers, just 'inherit' to the root-handler:

http.ListenAndServe(port, adapter(root_Handler))

I can't get my head around OOP in JavaScript.

Many years ago, I used to dabble in programming BASIC and learned a bit of COBOL and FORTRAN in school so I am somewhat familiar with procedural programming, but I never learned any of these to a very high level of proficiency or complexity. I've also done a few hackey things with JS but I guess it was mostly procedural in nature rather than OOP.

Recently, I've decided to train myself to become a web developer and learn JavaScript properly, and based on the rave reviews, I decided on Head First JavaScript Programming as my textbook.

The problem I am having is that I can't figure out how or why using objects is really any different or better than using functions and variables. I've looked around at a ton of tutorials and videos but they all say the exact same thing as the book. "Objects are useful because they are analogous to everyday items in real life such as a car. A car has a model year, a make, a weight, a color, etc... A car can also do things such as start, stop, go, etc. They are functions inside the object and called 'methods'." and that is followed by "this is how to create an object:"

var myCar = {
    make: "Chevy";
    year: 2004;
    kilograms: 2000;
    color: "blue";
    go: function() {

Great. Now I know that objects are somehow analogous to real life things and I know how to make one with properties and methods. I get that.

And I can access these property values by calling them as follows:

a = myCar.make;
b = myCar.year;
c = myCar.color;

I can also call the function (or method):


Wonderful. But I STILL can't figure out WHY I want to do it this way. Why is this better than the following?

myCarMake = "Chevy";
myCarYear = 2004;
myCarKgs = 2000;
myCarColor = "blue";

function go() {

Other than how the code is organized, I don't understand how it's any less procedural. Statements are executed in order, after all. And I don't see what the advantages are to doing all of this.

I keep thinking that what I really need in order to understand this is to see two programs that do the same thing, one coded procedurally with normal variables and functions, and the second one programmed with OO in order to see the difference and how these objects interact with each other in an advantageous way.

I find that all the textbooks and websites that I have found never explain how similar things behave differently or why one is better than the other and there are few if any examples of how to tie it all together well. Most books and tutorials just tell you what you can do but not why you'd want to do that or choose one way over an other. (Irrelevant to this question but another thing I'm wonder about is, I know I can assign a function to a variable but WHY would I want to do that?)

To be clear about what I am looking for, my question is, can someone show me a program that is programmed both ways (both do the same thing and are simple enough for a beginner but complex enough to show why OOP might be needed or advantageous) to highlight the differences and explain why it's better?

In practice, if you have a small script or application, you will not see the difference. But once you move towards larger applications and bigger code bases, you'll see that OOP works much better than PP.

Here are some high-level advantages of the OOP approach over the PP:

1) Modularity and maintainability

The code becomes modular, the related data and methods are packaged into objects.

This makes it much easier to keep the code under control. It is complex to see this on few lines of code, but as your code grows, the procedural code most often turns into a mess.

With OOP your code is naturally splitted into smaller parts (objects) and even as the codebase grows, it is still easy to keep the code in order. The modularity leads to better maintainability - it is easier to modify and maintain the code.

2) Flexibility

It is much easier to replace the part of the code with some different functionality.

For example, you can have the Logger object which writes logs to files. But then you decide to write logs to the database instead.

With PP approach you would need to go over the whole code base searching for something like log_to_file(message, file_name) and replace with something like log_to_db(message, db, table_name).

With OOP you just create the new DbLogger and "plug it" into the system instead of the previous file logger, so the code which logs data will still look the same, like logger->log(message). Even better, you can decide on the type of the logger run-time, for example, read the setting from the configuration file and create whether file logger or db logger.

3) Testability

With OOP it is much easier to take our part of the code (object) and test it alone. If it depends on other objects, these can be replaced with fake implementations (test mocks), so you can really test the piece of code alone.

Just to demonstrate the difference, let's imagine that instead of one car, you now have three (also the go method should really do something with the variables, otherwise it doesn't make much sense):

var myCarMake = "Chevy";
var myCarYear = 2004;
var myCarKgs = 2000;
var myCarColor = "blue";

var yourCarMake = "Ford";
var yourCarYear = 2001;
var yourCarKgs = 1990;
var yourCarColor = "white";

var hisCarMake = "Ferrari";
var hisCarYear = 2011;
var hisCarKgs = 2990;
var hisCarColor = "red";

function go(make, year, kgs, color) {
    alert(make + " " + kgs + " " + year + " " color);

go(myCarMake, myCarYear, myCarKgs, myCarColor);
go(yourCarMake, yourCarYear, yourCarKgs, myCarColor);
go(hisCarMake, hisCarKgs, hisCarKgs, hisCarColor);

Notice some of the properties of this code:

  • busness-logic code (the definition of car properties and the go method) is mixed with the client code (the part where we call go), we can not separate them, because client code refers to the global variables we created (like myCarMake)
  • many repetitions (like CarMake is written 6 times) and it looks messy
  • easy to make the error (there are errors in last two calls)
  • hard to maintain - if we add a new parameter for the car, we will have to go over all the code base

Now the version with object (to simplify the code, I keep it as a simple object and separate constructor function, see this for other ways to define the object):

var CarPrototype = { // empty object-prototype
    make: "",
    year: 0,
    kilograms: 0,
    color: "",
    go: function() {
        alert(this.make + " " + this.kgs + " " + this.year + " " this.color);

// function that constructs the new object
function createCar(make, kgs, year, color) {
    var car = Object.create(CarPrototype);
    car.make = make;
    car.kgs = kgs;
    car.year = year;
    car.color = color;
    return car;

var myCar = createCar("Chevy", 2004, 2000, "blue");
var yourCar = createCar("Ford", 2001, 1990, "white");
var hisCar = createCar("Ferrari", 2011, 2990, "red");


And some properties of this code:

  • the business logic is clearly defined and separated from the client code, client code is not aware of internal structure of the car object
  • less repetitions and in general the code looks clearer
  • once the object is defined, it is really complex to make the error (you just do myCar->go(), no parameters passing, no chance to mix them or pass in the wrong order
  • easier to modify (if we add a new property for the car, the myCar.go() calls in client code don't need to be changed)

For sure, I didn't mention all the reasons to use OOP over PP, but I know this from practice - try to spend some time learning OOP principles and start using it and you'll see the huge improvement in code structure. You will make mistakes and do things wrong in the beginning, but the result will anyway be better than procedural code.

The general approach here is more important than specific language constructs, you can use same principles in C (which is not an OOP language) and in javascript (which has a specific OOP support) as well as in other languages.

I don't know a resource which compares PP and OOP side by side, but I think you don't really need it. Just look at examples of OOP applications and imagine how these would look like if written in procedural style.

My favorite book about OOP is Design Patterns, it demonstrates how elegant and powerful can be interaction between objects. Probably, you will also need to find something where basic OOP concepts are explained (already mentioned encapsulation, polymorphism, inheritance) and principles (most notably SOLID).

I find myself rarely using object oriented principles when I design applications. I am looking for a good reference for Object Oriented design. I'm using C# as my programming language and would like to have a reference which helps to make use of the OO contructs provided by C#. But basically I need a good book to derive some inspiration.

Check out Evan's DDD

I have been reading on Design Patterns recently, and there's something I don't understand about the Proxy Pattern.

quote from the book:

  1. A virtual proxy creates expensive objects on demand. The ImageProxy described in the Motivation is an example of such a proxy.

I get it that this pattern can be used to create expensive objects on demand. And this example also illustrates the usage quite well.

Below is the constructor of the proxied class RealImage. Method loadFromDisk() denotes the expensive procedure.

   public RealImage(String fileName){
      this.fileName = fileName;

And the proxy class ProxyImage in the example does just what it is intended to do: to create expensive objects on demand.

But my question is: why can't we just remove the expensive loadFromDisk() method from the constructor and put it somewhere it is absolutely needed,

like here?

  public void display() {
          loaded = true;
      //then display

So why bother using a proxy at all?

The problem the proxy pattern solves in this situation is code duplication. Imagine a situation where you have dozens of method similar to display() where loaded flag needs to be checked. Your code would look like this:

public void display() {
        loaded = true;
    //then display
public void resize(double scale) {
        loaded = true;
    //then resize
... // more methods go here
public void save() {
        loaded = true;
    //then save

Even if you put the if(!loaded){... code into a method and call it from all methods, you need to remember to perform the call. This is error prone, and may cause problems down the road, especially for new programmers coming into the project.

I have created my own Tree implementation for various reasons and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised.

In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation.

So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't want to override those methods because they also contained shared logic that shouldn't be duplicated!

The problem can be boiled down to this:

public class Foo {
    public String value() { return "foo"; }

    public Foo doStuff() {
        // Logic logic logic..
        return new Foo();

class Bar extends Foo {
    public String value() { return "bar"; } 

new Bar().doStuff().value(); // returns 'foo', we want 'bar'

The first thing that popped into my head would have a 'create hook' that extending classes could override:

public Foo createFooHook(/* required parameters */) {
  return new Foo();

Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... wrong about it.

It's like cooking while naked-- it feels dangerous and unnecessary.

So, how would you deal with this situation?

So, after getting my copy of Design Patterns and opening it for what I'm fairly sure is the first time ever I discovered what I want.

It's called the Factory Method and it's mostly a perfect fit. It's still a bit ugly because my super class (Foo in the above example) is not abstract which means subclasses are not forced to implement the hook.

That can be fixed with some refactoring though, and I'll end up with something to the effect of:

abstract class AbstractFoo {
    public String value() { return "Foo"; }

    public AbstractFoo doStuff() {
        // Logic logic logic
        return hook();

    protected abstract AbstractFoo hook();

class Foo extends AbstractFoo {
    protected AbstractFoo hook() { return new Foo(); }

class Bar extends AbstractFoo {
    public String value() { return "Bar"; }

    protected AbstractFoo hook() { return new Bar(); }

new Bar().doStuff().value(); // Returns 'Bar'!

I have written a text editor program in C++ that has simple commands: LEFT, RIGHT, HOME, END, BACKSPACE, DELETE, INSERT, and now I need to perform the UNDO and REDO functions. In my program the user must be able to undo no more than the last ten commands. I would like to use a vector implementation to accomplish this, but I have no idea how to set this up. I'm not sure how to store the cursor position and the character into a vector. Can someone offer some help?

#ifndef CURSOR_H

#define CURSOR_H

#include <stdlib.h>
#include <iostream>

template <class Object>
class Cursor;
// Incomplete Declaration

template <class Object>
class CNode

                CNode( const Object & theElement = Object( ), CNode * n = NULL ) : element( theElement ), next( n ) { }
                Object  element;
                CNode *next;
                friend class Cursor<Object>;

template <class Object>
class Cursor
  Cursor( );
  bool isEmpty( ) const;
  void makeEmpty( );
  void left ( );
  void right ( );
  void del ( ); //This is the delete operation. I named it del instead of delete as delete conflicts with a C++ keyword.
  void back ( );
  void insert( const Object & x );
  void home ( );
  void end ( );
  void undo ( );


  void printText ( ) ;

  CNode<Object> *header;
  CNode<Object> *cursorPosition;

//#include "Cursor.cpp"

Look at the Memento Design Pattern and also in GOF

It exists for this very specific requirement. You may have to use it in combination with other Design patterns (e.g. Command, Iterator, FlyWeight etc)

Memento Intent

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

Command Intent

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

i just graduated from a polytechnic where i was taught quite basic programming (at least in my opinion, like VB Calculators and such)

so now in my current job, i feel that that's not enuf. i am wondering from my basic foundation how can i build up my skills? i am picking up C# 3.0 (4.0 seems to be out soon) WPF, LINQ

the issue that i face now is for windows applications, how can i have an app that can manage various database tables, ie. add, edit, delete, list dialogs. i dont want to have them as separate forms. i also dont want to spam everything in 1 screen.

what i like is something like outlook. where i have a accordion side navigation. then when i click something, it loads up in the main screen, maybe with closable tabs.

i was linked to MSDN Patterns & Practices when i posted something similar in MSDN. but it seems to be a big jump. i am missing alot in between.

there are patterns, MVC, and such ... whats the best for Windows app? i use MVC for my web development

I would advise that you read the book 'Design Patterns' by Erich Gamma et al. (Amazon link:

i'm currently in the process of modifying a legacy editor application and i need to add in a few data structures which i have made into a class of it's own which i later add to a collection object. but thus far i'm little bit blurry on where to put all of my functions which is related to that object. i'm thinking maybe OO like design, but i'm not quite sure how to do this in vb6. else all the functions are currently in a module mdl file. which are set as public function.

is there any good reference, book or whatever which i can learn more about how to properly design for vb6 app? for the current work and for future work i guess.


Another good source of information is Deborah Kurata, she's written a series of books about OO coding in VB. Less well known than Rocky Lhotka (who is excellent), and concentrates more on pure OO, not the ORM/DB layer that he does.

All the reference cited so far are good. However the Design Patterns by the Gang Of Four is usable for Visual Basic 6. The trick to remember that most of the pattern talked about in Design Patterns rely on implementing interfaces which VB6 can do well. In fact you will find most design patterns involve implementing interfaces.

This is because most design patterns focus on setting up how various objects interact as opposed to reusing behavior. So interface become much more important.

Design Patterns by the GoF Patterns by Martin Fowler The various GUI and presentation patterns is the most applicable in my opinion.

My own application is structured completely as a series of design patterns. For example I use a Passive View for my presentation layer. The various views called command objects which does the actual modifications of the model. I use factories to retrieve the list of reports, file types, and shapes my software support. All done in VB6 using the Design Patterns book by the GoF.

I'm currently learning to program, and I didn't take CS classes so I'm basically starting out on the bottom. I have been putting together code on and off for many years, but haven't really had a good understanding of essential concepts needed for enganging in bigger projects. Object-orientation is an obvious one, and I feel I'm beginning to understand some of the concepts there. Then there is a lot of buzz and methodology, such as MVC, UML, SCRUM, SOLID and so foth and so on.. I've looked at many of these but I'm always stumped as most explanations seem to require some understanding of other concepts.

I want to learn this stuff the "right" way, so where do I begin?

What are the overarching constructs I need to understand that enable me to understand all the underpinnings of software architecture/design/development?

What am I missing?

Are there constructs and concepts that can and should wait until I've cleared the foundation?

When you are working with any modern general purpose language, it is probably a good idea to get a handle on patterns (MVC or Model-View-Controller is one). The book by the "gang of four" is a must read for this, or at least research a few and use it as a reference. clicky

Refactoring is another concept that should be in your arsenal. The book by Martin Fowler on this subject is a very nice read and helps understand the aforementioned patterns better also a little explanation about UML is included.

Can't post more than one hyperlink so...

search on amazon for: Refactoring, Improving the design of existing code

When you want to communicate your designs UML (Unified Modelling Language) is the 'tool' of choice for many people. However UML is large and unwieldy but Martin Fowler (again) has managed to boil it down to the essentials.

search on amazon for: UML Distilled (make sure you get the most recent one)

SCRUM is one of many methods that is used to manage software development groups, I do not think there is much merit in learning that when you are just starting out or on your own. Especially not in detail.

Hope it helps...

PS: SOLID I haven't heard about yet, somebody else has to help you there.

Stay away from ACRONYMS (including those you've listed) and Methodologies(tm). At least in the beginning.

Read good books. Start with this one: Pragmatic Programmer. Learn algorithms and data structures, possibly from Introduction to algorithms by Cormen et al.

Write a lot of code. Practice is more important than anything else.

I'm familiar with both the Wizard Book:

Structure and Interpretation of Computer Programs

and the Dragon Book:

Compilers: Principles Techniques and Tools

However, I'm curious to find out which other classic academic textbooks people would consider essential reading for a programmer.

A must have 'Design Patterns: Elements of Reusable Object-Oriented Software'

aka Gang Of Four

I'm having trouble wrapping my head around state-based functionality for an invoicing system we are currently building. The system will support calculation, manual approval, printing, and archiving of invoices.

At first I thought we should use the State Pattern to model this. An invoice would be the context, which delegates printing, archiving, etc. to its currently assigned state.

But this is obviously a bad idea, because the different states (created, approved, printed, archived) should not support the same operations. E.g., you shouldn't be able to print an invoice, which hasn't been approved before. Throwing exceptions for unsupported operations would be a violation of LSP. I found a general description of this problem here.

Does anybody have an idea, how to implement this appropriately?

PS: I'm aware that this might sound like some lame-ass homework assignment, but it's not; I need this for a real world system.

Whether the State Pattern is really appropriate to your situation is not certain, but if it's not, Liskov is not the reason. Throwing some sort of "invalid operation in current state" exception can be defined as possible and valid in the state interface, and then subclasses doing this do not violate LSP.

The classic example used for the State Pattern in the GoF Design Patterns book is a TCPConnection, which definitely has operations not supported or sensible in all states. You can't transmit on a closed connection, for example.

I'm looking into converting a big switch statement in my code into more manageable chunks using the State pattern.

I've been reading about it in the Design Patterns book, and also looking at a tutorials point example here.

The code in that example looks wrong to me, since the author is calling the State functionality from outside the Context. Is that correct?

It's my understanding that it is the context that should be the wrapper for the states, and State changes should most likely be handled from within each State object. Otherwise it kind of defeats the purpose right?

While googling to try find the Design Patterns book State pattern diagram below:

State Behavioral Pattern

I came across this example, which is much more in line with my thinking. So am I correct in thinking the Tutorials Point example is incorrect, and the State should be changed either by the states themselves, or by the Object that holds the Context with a call to context.request()?

Is there a valid case for doing it like in the Tutorials Point example? I can't see it myself, if you do it that way you're just going to end up with another switch or if statement.

The code in that example looks wrong to me, since the author is calling the State functionality from outside the Context. Is that correct?

Yes you are true, the given example poorly illustrates the State pattern it is much more a Strategy here because the Context object receives a new behavior instead of adapting it itself.

...and the State should be changed either by the states themselves, or by the Object that holds the Context with a call to context.request()?

Right. It is the responsibility of the State classes to set the "next state" of the context. A state machine can easily be created using the State pattern:

  • Context is the machine which the current state is updated, it holds some decisional information
  • Each states defines the action performed and test "transitions" to other states according to the context. If a transition occurs, the context's state is updated to a new state.

Is there a valid case for doing it like in the Tutorials Point example? I can't see it myself, if you do it that way you're just going to end up with another switch or if statement.

I see two reasons to update the state of the context from the outside :

  • Choosing the initial state of the context (could be injected by constructor)
  • Interrupt or reset the context, it is often the case in the embedded world when receiving an ISR for example.

I'm new to MVC and EF, so excuse me if my question is not clear or easy.

I have read some tutorials about EF Code-First approach and now I'm trying this tutorial Getting Started with EF using MVC.

Using Code-First approach I'm using the POCO classes to define my DB model, DB logic, DB validation, UI validation and some UI logic. So I can use these classes(or objects) in my presentation layer or use them as JSON objects when dealing with Web-Services(or in JavaScript code).

My question: Isn't that mixing some logic together? I mean shouldn't I use like special view-model classes for presentation and these classes should have the UI logic and validation ?!

Is it good practice to send the POCO object to the view(or to the client in general) ?

Finally i need some guidance on how to organize my project layers or folders? I see many ways and I'm confused about what to choose or what format I should base my own on?!!

You should not use your data entities in higher layers of your application. Transform/compose/copy data from DAL into view model or business classes using a library like Automapper. This keeps the layers of your application independent and hides your database schema from end users.

Keep in mind that MVC is only concerned with presentation, all real work should happen in other layers of your app. I try to keep layers independent and use a little bit of glue code to bundle them into an app. I may write data access and business logic layers when working on MVC project, but then re-use in a command line utility. There are a lot of books that talk about writing quality code. I personally found Clean Code, Code Complete 2, and Design Patterns extremely helpful.

I need some info on Design Patterns i.e.

In S/W designing, An architect comes across various scenario's so which Design pattern to apply if scenario is ....

Please let me know if there is any such tutorial or any book that explains use this patterns if scenario is ... use that if scenario is .... and so on

Thanks in advance.

Web reference: wikipedia is not.. bad?

for some instant gratification try this

for light on the pot reading, head first design patterns. is cute and whimsical.

once that sits right you could go to the source

In my recent project I have a class like this:

class layer1 {
myclassa l1dataa; // layer1 data
myclassn l1datan;

void l1datatransformsa()
  myotherclassa l2dataa; // layer2 data
  myotherclassn l2datan;

  many operations; // way too many operations for a single method

void l1datatransformsb() {}

The method l1datatransformsa invokes local data and is quite long and robust. I would like to divide its code into smaller meaningful portions (methods) which all work on the same local layer2 data. It can be done in few ways, though none of them seems good enough to me, therefore I'm asking for recommendation on how should it be done:

  • Breaking the code of "many operations" into private methods of class layer1.

Cons: I would have to pass as arguments to those new methods references to all layer2 data, which is not very elegant as there is too many of them

  • Rewriting the method l1datatransformsa as a nested class of class layer1 with layer2 data declared as its data members. Then it would be possible to split "many operations" into members of the nested class.

Cons: To access layer1 data from nested class I would have to use reference or pointer to the instance of enclosing class. This will make me include many changes in the code of "many operations" and will make the code less clear. It would be even worse if one would think of a need of splitting in the same manner one of methods of nested class.

The basic idea behind all this is to have a comfortable way of keeping your local data close to the functions or methods which use it and only to them at every layer of your program.

ADDED: "many operations" which we we want to split work both on almost all data members of class layer1 and all local data layer2. They work on layer2 data sequentially and that's why they can be splitted easily, though it's a bit awkward 'programistically'.

-- New answer --

I removed my old answer because I thought you were looking for a trivial tips. I think you need to do some reading on the tools and techniques you have available to organize and construct software.

  1. Gang Of Four - Design Pattern Book
  2. Modern C++ Design
  3. Generic Programming

The first book is essential, the second builds up some of the concepts that are introduced in the first in C++. The third is quite academic -- but contains a wealth of information, you can probably ignore it.

I've been doing C++ for 3-4 months in a local college and I'm doing extra reading / learning using Accelerated C++ and so far, I've "finished" it. Now, I'm wondering which book to get next that'll help me code better in C++.

I've looked around and found this: The Definitive C++ Book Guide and List

I'm sorry if this question may seem stupid for most of you here but I'm a bit tight in cash and I would really want to invest in something that's "right" for me at this time.

Right now, I only know the basics of stuff like (classes, templates, STL, iterators, dynamic memory management).

Do you have any suggestions? Should I focus on STL or templates..? Or should I read something like The C++ Programming language?


If you don't want to spend money, you should learn multi-threaded programming. The basics are already in the books you have, and described in API documentation. Try to actively create a program with many threads that communicate back and forth, and then multiply the number of threads to see if you've made a good design.

You'll want to read up on Semaphores, Mutexes, and Critical Sections.

I take three approaches to multi-threaded programming:

  1. Use a PostMessage style communication between threads
  2. Pass thread-safe objects between threads through which data is stored and relayed
  3. Initialize a thread on start-up, let it run on its own, and then retrieve the data at the end of the run

If you're ready to spend money, I would recommend Design Patterns as a good next-read. It's more generic, and you'll find some of the ideas make sense.

I've successfully written a Powershell script which:

  • query AD to obtain the list of computer
  • query every computer through WMI to obtain software/hardware information
  • insert the collected data into a MySQL database.

The script works fine but I don't like how it's implemented. It's procedural and there is a lot of code duplication, causing a mess everytime I need to change something.

Now, what I would like to ask you is: what is the cleanest way to implement it in python using OOP? I've thought something similar to this (pseudocode):

Class ADquery
    function get_computers( UO ): return a list of computers in the specified UO

Class Computer
    constructor( computername )
    function query(): connect to the computer and pull the info through WMI
    function print(): print the collected info to the console (debug)
    property RAM
    property CPU


  1. In order to save the collected data into a Database, do I have to create another object (e.g. Database) and pass the Computer object to him or add a member function to the Computer class (e.g. save_db() ) ?

  2. If I go for the second option, that wouldn't cause a massive number of MySQL connections when I'm dealing with multiple objects?

Thanks a lot and sorry for my bad English

You could also grab an Object Oriented Design book from the internet or your local bookstore, e.g. Rumbaugh et al.. I would also recommend reading up on Design Patterns, e.g. the book by Gamma et. al.. I'm currently doing that, and it is really helpful to look at standard patterns of how to solve a particular problem to shape your thought process about object oriented programming.

ps Your English isn't bad at all (note that I'm also not a native speaker ;)).

I want to create customized list in c#. In my customized list I want only create customized function Add(T), other methods should remain unchanged.

When I do:

public class MyList<T> : List<T> {}

I can only overide 3 functions: Equals, GetHashCode and ToString.

When I do

public class MyList<T> : IList<T> {}

I have to implement all methods.


You can have MyList to call List<T> implementation inetrnally, except for Add(T), you'd use Object Composition instead of Class Inheritence, which is also in the preface to the GOF book: "Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20)

I was just reading this thread and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way. Generally, I run into this situation when I need to create one of several subclasses of an object based one something unknown at compile time (such as based on a config file). I use the object polymorphically once it is created.

There's another related situation when you're using a message-passing scheme (usually over TCP/IP) where each message is an object. I like to implement that pattern as letting each message serialize itself into some serialization stream interface, which works well and is fairly clean on the sending end, but on the receiver, I always find myself examining a header on the message to determine the type, then constructing an appropriate message object using the pattern from the linked article, then having it deserialize itself from the stream. Sometimes I implement it so that the construction and deserialization happen at the same time as part of the constructor, which seems more RAII, but that's small consolation for the mess of if/else statements figuring out the type.

Any better solutions out there? If you're going to suggest a 3rd party library, it should be free (and ideally open source) and I'd appreciate it if you could explain how the library accomplishes this feat.

Read the classic Gang Of Four aka GOF. Consider [this site[( for the Factory and other patterns in C#.

Most C# developers developers, like me have a good solid grasp on the .net framework and the C# language. But I've yet to come across a book that can take a very good c# developer to the next level of C# mastery.

I am looking for a book that can help me make that transition. Dealing with issues like theory on having more robust C# code when connecting to external systems etc. Error logging techniques, and generally better memory usage, and re factoring.

Anyone know of a good book, that's worth the read?

The best book I have found for C# internals is CLR via C# by Jeffrey Richter.

Effective C# and More Effective C# by Bill Wagner come highly recommended

Not a C# book per se, but Design Patterns (Gamma et al) might be a good introduction to more abstract, architectural concepts.

Propose to consider the following problem.

Suppose we have some composite object. Are there patterns that describe the solution of mutual notification of composite object parts, when states of these parts are changed

Yes, the Mediator pattern from the original Design Patterns book.

so I have been through all the courses on programming, algorithms, etc. and did a lot of coding and some small projects. Now, I may start working on a real project, real java SE program with gui and everything, not big, but much more complicated than average school project. My experience says that when I'm having more classes in my project (say 10), it kind of gets difficult to decide from where this constructor should be called, if I should pass this parameter here or create it later and how the whole thing should work together.

can you recommend me some resources on this? Should I go the way of studying the design patterns or how do I get to design apps that have nice architecture? what is the procedure when developing an app with lots of classes and gui and so on? thanks a lot

Design patterns usually help in making an application more maintainable and also more flexible. Although which design patterns to use relies essentially on what type of problem you have.

I did go through this book, which provided me with a quick and easy way to grasp what design patterns are and how they work.

Since you are dealing with GUI related applications, my only recommendation would be to try and make your GUI and Logic seperate. This should reduce clutter and should make your code more understandable since each class deals with items related to its layer (GIU or Logic).

Breaking things down also makes your application more flexible and reusable. Cohesion vs Coupling should also be another thing which you should keep in mind.

For design patterns : Head First Design Patterns & Design Patterns: Elements-Reusable-Object-Oriented

For Effective Programming Guidelines : Recommended reading Joshua Bloch's Effective Java

I personally like to thing in a TDD approach and love to read this blog Writing Testable Code by Misko Hevery. It explains how should we focus on making code loosely coupled and testable.

And lastly keep exploring open source libraries and projects they will keep you up to date with latest trends and coding styles.

Would someone please explain to me what the below paragraph means? This is a snippet from "Design Patterns: Elements of Reusable OO software"

Part of an object's interface may be characterized by one type, and other parts by other types. Two objects of the same type need only share parts of their interfaces. Interfaces can contain other interfaces as subsets. - Design Patterns - Elements of Reusable OO software, pg 13

To understand what this means you first need to remember that the Gang of Four wrote this book back in 1994, when the vast majority of programmers in the world were not using (and had never heard of) object-oriented programming.

Gamma, Helm, Johnson and Vlissides are basically introducing the concept of interfaces here. The idea is that a piece of code that interacts with an object doesn't really need to understand how the underlying implementation happens, and that two different objects can have the same interface but have different implementations. We do that all the time today with interfaces in Java and Objective-C.

But they go further, and imply that an object may have several interfaces, one from one type (or interface), and one from another. You can do this explicitly with multiple inheritance in C++, or with multiple interfaces in Java, or just by using the same naming convention.

as the question says, i wish to learn OOP in c#. I am aware of the basics of OOP such as what does class means, what is object, and all 6-7 features of OOP. What i dont understand that how to make use this in real application? I get stuck when it comes to using all these features during development (coding).

I have code in VB.NET and now would be doing in C#. I have use VS 2005 and now using VS 2008.

Please suggest me some very good resource to learn (& especially i could implement it also) OOP in C#


Personally, I found the classic Design Patterns book quite an eye-opener when it comes to object-oriented design. From that, all else follows :)

It predates C# with about 5 years, so you will have to look at C++ and SmallTalk code instead, but learning OO is really not about the language, but rather the mindset.

Many people find that Head First Design Patterns is a more digestible alternative, but I have only flipped through it myself (it looks pretty good, though).

Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

Applying Domain-Driven Design and Patterns is the first complete, practical guide to leveraging patterns, domain-driven design, and test-driven development in .NET environments. Drawing on seminal work by Martin Fowler and Eric Evans, Jimmy Nilsson shows how to customize real-world architectures for any .NET application. You'll learn how to prepare domain models for application infrastructure; support business rules; provide persistence support; plan for the presentation layer and UI testing; and design for service orientation or aspect orientation.

Although not the book's only focus, I found Agile Principles, Patterns, and Practices in C# really useful for OOD/OOP. It covers SOLID design principles in an accessible and very readable way. Similar content is also available at the author's (Robert C. Martin) web site, Object Mentor.

Agile Principles, Patterns, and Practices in C# cover

Currently I am able to navigate between multiple user controls in silverlight. However everytime i navigate to a new user control, all the code in that user control is run again. Normally this wouldn't be a problem but, in my scenario one of the user controls takes around 50 seconds to load because of a monster query it is running via WCF service.

So how can i navigate to different user controls without creating a new instance of those user controls?

You may want to research some creational software design patterns.

I would recommend either an Object Pool or a Singleton, but the pattern you choose is going to depend on your requirements and you may find another one suits you better.

I would highly recommend you purchase Design Patterns: Elements of Reusable Object-Oriented Software. It is a fantastic, ground-breaking work which no serious C# programmer should be without.

I am new to object oriented programming and learning to design classes.

I am wondering how can i design a class which holds list of itself.

For example, I have a class named Game will following definition:


  • title
  • description
  • screenshot
  • flash (holds flash game object)

I want to display list of games on a page. What approach is good for it? Either create another class GameList and create array of Games to be listed or create a function Game.ListAll to display game list?

I feel former is better approach to do so. I need your guide please. Also i dont know what to actually study to clear my concepts in designing class and their relationships etc. Can you please suggest me a book CBT which is easy to understand ?

Thank you very much.


I think it would be a bad design to have a (static) method listAll() within Game: Games shouldn't know about other games, you would need the constructors or factory methods to take care of the list, and you couldn't handle separate lists.

So use a list outside of Game. If you do not need special behavior of the GameList, a field List where you treat the list will do. If you have special behavior, your design with GameList is the right choice.

For good OO design, I would read up in the following order:

  1. the relevant articles from the object mentors article list to get an overview. You can find links to the most relevant for you at principles of ood.
  2. a book about design patterns, my favorite still being the classical Design Patterns from the GoF
  3. read Agile Software Development, Principles, Patterns, and Practices from Uncle Bob

I am trying to figure out what 'topic' this is called, so I can learn more about it.

Basically, I'm talking about designing my applications's architecture. I'm not talking about algorithms. More like -- this class should have these methods and these instance variables, and communicate with this class in this way, this class should have these responsibilities etc.

Can anybody tell me what the name of this topic is called and how I can get better at doing this?


It sounds like you're thinking about Design Patterns. The book you want is GOF.

I have a Widget class and a CompositeWidget that is derived from it. CompositeWidget adds child management behaviour. The Widget constructor takes a CompositeWidget* parameter as the widget parent. I need to use this parent pointer to access some functionality within the CompositeWidget. For example:

Widget::Widget(CompositeWidget* parent)

This forces me to create a public method CompositeWidget::AddChild. Is is possible to keep this interface private to the class hierarchy (a little like a reverse-protected access - limited to base classes)? Am I making a design faux pas in thinking about the problem like this?

Edit: I am trying to avoid friendship (if it's possible in this case).

Answer to your concrete question: declare Widget to be a friend of your CompositeWidget and make AddChild a private member.

Alternatively, move the child management to CompositeWidget. The Design Patterns book has an extended discussion on this in their section on the Composite Pattern:

The decision involves a trade-off between safety and transparency:

  • Defining the child management interface at the root of the class hierarchy gives you transparency, because you can treat all components uniformly. It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves.
  • Defining child management in the Composite class gives you safety, because any attempt to add or remove objects from leaves will be caught at compile-time in a statically typed language like C++. But you lose transparency, because leaves and composites have different interfaces.

We have emphasized transparency over safety in this pattern. If you opt for safety, then at times you may lose type information and have to convert a component into a composite. How can you do this without resorting to a type-unsafe cast?

They go on to give a long code example, which essentially boils down to this design where the CompositeWidget contains the child management:

class Widget
    virtual Composite* GetComposite() { return 0; }

class CompositeWidget: public Widget
    void AddChild(Component*); 
    // ...
    virtual Composite* GetComposite() { return this; }   

class LeafWidget: public Widget
     // no child management here

GetComposite lets you query a widget to see if it's a composite. You can perform AddChild safely on the composite it returns.

I'm putting together a GUI with a couple of panels. In one panel there are components for the user to input various parameters. In another panel, there are buttons and a place to output a plot based on data generated using the user inputs.

I have all of the various pieces working independently now I'd just like them to talk to each other!!

When i hit one button, I would like to take all of user inputs and combine them to generate a data set and plot it. Another button then to write this same data to a file.

I have code to implement all the components individually, code to write data to a file and code to generate a plot from data. All of which works fine.

I thought that I could use the Action/ChangeEvents to take the parameters and assign them to an ArrayList. Then use this arraylist to generate the data.
I'm finding it difficult to plan an approach to tackling this.

Currently I'm using get set methods in the event handlers to set parameter levels for a particular instance of the array list, I would like to pass this instance into another class to generate the data but don't know how to make it accessible.

I hope I have provided enought information here. If anyone has any thoughts on this they would be much appreciated.

I'm trying to understand the difference between the Decorator and Singleton Pattern. For example, in Ruby if I wanted to implement a Singleton Pattern I can use the singleton class. But when I read about the Decorator Pattern in Wikipedia I feel like I would use a singleton class in that case as well.

The Singleton pattern ensures that only one instance (or a limited number of instances) of a class exists at any given time. On the other hand, the Decorator pattern is a mechanism for dynamically adding functionality (responsibilities) to an object, by changing its "skin". Singleton is a creational pattern, whereas Decorator is a structural pattern.

There really isn't much in common between the two of them, what's the source of your confusion? Wait a bit before using Ruby's Singleton module, better go straight to the original book and understand the fundamental concepts, before thinking about implementation details.

I'm working on a tic tac toe game and am wanting to implement an undo method. What I feel is the best way to do this is just setup another (multiple?) stacks, and make a copy of the 'moves' that have just taken place. Then, if undo is called, just pop the last move and repopulate the game board.

So yeah, I have the idea, but can't figure out how to implement it.

Some of what I have:

To set:

public void set(Position p, int v, int n) throws IOException { 
    if (board[p.x][p.y][p.z]!= 0) throw new IOException("Position taken");

    //Restrict 222 until all other's have been used
    if (n != 26) {
        if (p.x == 1 && p.y == 1 && p.z ==1) {
            throw new IOException("[2,2,2] cannot be played until all other positions have been taken");

    //Enforce x=1 for first 9, x=3 for next 9
    if (n < 9 ) {
        if (p.x != 0) throw new IOException("Please play on x=1 for the first 9 moves");

    if (n >= 9 && n < 18) {
        if (p.x != 2) throw new IOException("Please play on x=3 for the first 9 moves");

    board[p.x][p.y][p.z] = v;

Then there is a board method to build the board, a display method, and of course one to check for 3 in a row.

Thanks for any advice

Go directly to the Gang of Four Design Patterns book and read the section on the Command pattern. That's what you're working toward -- and making a pretty good job of it -- and it's straight forward to implement in Java once you get the idea.

I noticed the last few weeks that programmers with higher experience do not discuss "coding" issues very often, rather they discuss design issues. I really love to learn about these patterns, I know the concepts of OO Programming and Design, I'm already applying a decent amount of these principles in my daily work, I try to keep my components modular, reusable, and each one has a specific, well defined responsibilities. Lately i'v been advised to start learning about the various design patterns (the advisor recommended code complete as a start), he mentioned some names of some popular patterns (like MVC, SingleTon, and others). So SO Gurus! how should I start learning about these patterns?

Because of the detailed explanation i think i'm goona give Saua the point

  1. learn about them (I personally like the C2 Wiki, others might suggest "Design Patterns" by the Gang of Four)
  2. apply them
  3. grossly mis-apply them (prime candidate: singelton)
  4. learn why number 3 was a mistake
  5. learn to apply them properly

That's more of a observation report than an instructional list ;-)

Though Code Complete is an excellent book (it is absolutely a must-have in my opinion), it is not the best of books to learn about patterns.

If you want to learn about patterns, a good book would be the Design Patterns book by the Gang of Four. It is a reference to some of the commonly used design patterns.

As for the patterns you mention: I see the MVC pattern more as an architectural pattern then a design pattern, since it effects the structure of the entire system (the architecture) rather than a more isolated piece of code. Singleton (not singletone) is an easy to grasp pattern, though it is overused and the downsides of it are often overlooked, so I wouldn't recommend to start with it (or at least, read it, learn the idea behind it, but don't just start applying it everywhere for the sake of using it - you usually don't really need it).

It's hard to recommend a pattern to start with, but I think Factory Method, Command, and Strategy are not too hard to learn, but I'm sure others could disagree.

I study GoF Design Patterns book and have Martin Fowler's PoEAA book in list. (I also have Judith Bishop's book which I personally do not like.) But there are more patterns, such as Delegation pattern. What is its origin? Are there other patterns not mentioned in these books? Are there other "must read" books or online resources on this topic?

Design Patterns: Elements of Reusable Object-Oriented Software and The Design of Everyday Things are very good books. I especially recommend the former for its intuitive read.

Are there other patterns not mentioned in these books?

Definitely. The GoF patterns are kind of the grandaddies of it all, and fairly general, but you can have domain-specific patterns too. Like Fowler's PoEAA, as you mentioned. Or design patterns for embedded systems. But also more domain-specific than that, like Fowler's book on Analysis Patterns, which has financial and health care related patterns. Or patterns for avionics systems, like in the link available here at the Hillside Patterns Catalog.

What is its origin?

If you mean what is the origin of the Delegation pattern, I dunno, but someone has asked a similar question here.

Are there other "must read" books or online resources on this topic?

The amusingly-named "PLoP" conferences (Pattern Languages of Program Design) are the first place a fair few patterns are aired I believe.

There's a PLoP journal as well: Transactions on Pattern Languages of Programming.

I found Design Patterns Explained to be quite useful in explaining some of the original thinking behind the Gang of Four patterns. It's an explanation as opposed to a reference.

In addition to the PluralSight catalog mentioned elsewhere, NetObjectives have some great resources on patterns (and principles in general), particularly their series of webinars.

I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD policy and I have 20% unit test coverage (thank you Michael Feathers for your book!), most of it in critical parts. I have some white-box Fitness tests as well (whole business scenarios are covered there). I feel that I cannot further refactor this app and I'm safe to play hard with it. It's designed so badly, I want to rewrite it. App itself is around 20k of challenging legacy C/C++ code. There were other dependencies but I manged to decouple most of them.

All I have is Sun C++ compiler, cppunitlite, STLPort and Boost. Please do not suggest other technologies (no XML, Java etc) as this is not the option in my organization. I'd like to do it with modern C++ (perhaps play with metaprogramming...), TDD from start to the end.

There are about 30 types of msgs I need to parse. Each of them is composed of 3-10 lines, most of them are pretty similar. This is root of all evil -> lots of code duplication. Each msgs has a class describing how it should be parsed. Take a look at the main inheritance tree:

                             MSG_A                     MSG_B
                            /     \                   /     \
                    MSG_A_NEW   MSG_A_CNL      MSG_B_NEW   MSG_B_CNL

Both trees goes much deeper. There are very small differences between MSG_A_NEW and MSG_B_NEW. It should be handled by single class that could be injected with some small customization.

My initial plan it to have one generic msg class that will be customized. Some entity (builder... ?) will take a look at the msgs and initialize proper object that will be able to parse the msg. Another entity will be able to discover what line is it and this info will be used by builder. I'm planning to write several parsers that are responsible for parsing just one specific line. This will allow me to reuse it in parsing different msgs.

There are several challenges that I struggle to solve in an elegant and extensible way. Each type of msg:

has min and max number if lines - has some must-have lines - has some optional lines - certain lines must be at certain places (i.e. date cannot be before msg type), order matters

I need to be able to validate format of the msgs.

I'm not sure if I explained the design challenge here good enough. My design experience is very limited. I've been bug-fixing for a while now and finally I will have a change to do some fun codding :)

What high-level advice do you have for that? Which design patterns can you identify in this description? Main design constraint is maintainability and extensibility with performance at the bottom (we have other bottlenecks anyway...).

You probably are already aware of this, but just in case... You should pick up/borrow the Gang of Four design patterns book for help in identifying and applying appropriate patterns. This is the canonical reference, and it contains cross-references and tables to help you decide what patterns might fit your application. It might be difficult for people here to identify specific patterns that might help you, based just on that description.

I want to know more about OOP in PHP 5.2.

Can anybody help me with a link to advanced OOP tutorials in PHP?

I know about static, public and private class member attributes, but I need more info about basic and advanced OO techniques. I hope somebody can help. :)

In order to first understand OOP with PHP, you must understand the core concepts behind OOP. Tutorials won't help you correctly grasps things like abstraction, inheritance, encapsulation, and polymorphism.

Grab a book about Object Oriented Programming, that is the best way to learn. One of my favorites is:

Design Patterns: Elements of Reusable Object-Oriented Software

Design Patterns: Elements of Reusable Object-Oriented Software

If you want something more PHP oriented, I heard nothing but good things about:

PHP 5 Objects, Patterns, and Practice

PHP 5 Objects, Patterns, and Practice

Both are available at

I don't understand why so many young/new programmers have a total aversion for books when they start learning.

I want to learn Design patterns with real time example. So can any one suggest where I can start.

I believe these are the two standard references:

  1. Head First Design Patterns
  2. Design Patterns

From what I've heard, the first is easier to start with.

The steps I took to investigate this:

  1. google "design pattern books"
  2. read this question

My question might not be too correct... What I mean is:

class MyClass

    virtual void Event()

class FirstClass : public MyClass
    string a; // I'm not even sure where to declare this...


    virtual void Event()
        a = "Hello"; // This is the variable that I wish to pass to the other class.

class SecondClass : public MyClass

    virtual void Event()
        if (a == "Hello")
            cout << "This is what I wanted.";

I hope that this makes at least a little sense...

Edit: _This changed to a.

I guess that you need something like this (for a sake of simplicity, I've omitted all the unnecessary code):

class Base{
    static int m_shared;

int Base::m_shared = -1;

class A : public Base{

    void Event(){
        m_shared = 0;


class B : public Base{

    void Event(){
        if (m_shared == 0) {
            m_shared = 1;

int _tmain(int argc, _TCHAR* argv[])
    A a;
    B b;

    return 0;

To explain above, I'll explain the static data members:

Non-static members are unique per class instance and you can't share them between class instances. On the other side, static members are shared by all instances of the class.

p.s. I suggest that you read this book (especially Observer pattern). Also note that above code is not thread-safe.

Over the last 18 months i have been hard at work teaching myself PHP & Jquery and so far have become quite good at it but not having a "mentor" i have developed my own "model" for building webapps / sites. it goes like this...

I have my front end page (HTML) and a js script which i fill with lots of jquery ajax (using a get or post method then pass on a command to the php) commands which in turn reference a sometimes large php file made up almost entirley of one big "switch / case" command with all my various options.

my question is this, is there a better way to do this?

i want to advance in my skills, where should i take my model next?

To put it simply: start learning the pros and cons of the various programming patterns. Sounds like you're doing Front Controller, which is fine for simple, one-off projects. The GoF book, Design Patterns, is supposed to be really good. A friend of mine really likes the Head First version...

In your case I would make the switch to Object Oriented Programming. I've been in a similar situation like you but wasn't satisfied anymore at how my websites looked with simple procedural scripting. Switching to OOP will take quite some time to get used to, but in my opinion it was all well worth the effort.

Take your time learning OOP. First, check to learn about objects and classes and afterwards read a book on the subject (Php Objects, Patterns And Practice by Matt Zandstra is a very good one You will find out why a lot of people have made a switch to the OOP approach for web apps.

When you are used to the way of thinking in OOP, choose a framework. It doesn't make sense to write code for things that have been written 100 times before and are tried and tested approaches to common problems. A framework covers all the basic annoying stuff you shouldn't be spending your precious time on. But only choose a framework when you have really grasped the way of thinking with OOP. It's always best to learn the basics first instead of jumping right in the middle by directly choosing a framework.


I have a container object which holds a mixed bag of objects all inheriting from the MyContainedObject class. Consumers of the container class do not have direct access to contained objects, but my be interested in knowing when they change.

Design Decision:

What's the best way to listen for ChangeEvents on a specific class type? My initial thought is to do something with Generics. For example,

private TreeMap<Class, ChangeListener> listeners;

public <T extends MyContainedObject> addChangeListenerForObjectsOfType(Class<T> className, ChangeListener listener)
   listeners.put(className, listener);

When a change is detected the container class would iterate through the list and notify only listeners registered for that class type.

Other suggestions?


There are a few limitations on your proposed design that may cause problems depending on what types of listeners you want to write

  1. A listener can only register for one raw type at a time. If a listener is interested for many types, or has other criteria it wants to use to decide what objects it is interested in, it would have to register multiple times. Also, the listener might not know what types are out there!
  2. It's unclear how to handle the case where you register for a subclass of MyContainedObject, and that subclass has subclasses.
  3. Changes can happen to MyContainedObject instances that the container is not aware of

I suggest instead having a listener for the container, and have each MyContainedObject instance also support listeners:

public interface ContainerListener {
  void itemAdded(MyContainedObject item);
  void itemRemoved(MyContainedObject item);

public interface MyContainedObjectListener {
  void itemChanged(MyContainedObject item);

As Adamski suggested, if there are a limited number of subclasses of MyContainedObject, then you can make the methods more specific:

public interface ContainerListener {
  void circleAdded(Circle item);
  void squareAdded(Square item);
  void shapeRemoved(Shape item);

Alternatively, you could make the specific methods in MyContainedObjectListener.

If you decide that registering for a type meets your needs, then consider making the listener generic:

public <T extends MyContainedObject> addChangeListenerFor(Class<T> className, ChangeListener<? super T> listener)

Either way, read the GoF section on Observer, since there are multiple implementation possibilities, each with advantages and disadvantages.

There are two classes:A and B.

And I need to implement a function whoViewed,

I have two options,make it an member function of A and B.Which smells a little duplicate.

Another choice is to make it a separate class:Viewer,but it's more abstract.

If you were me,which way will you choose?

To make it more general:

what will you do when you need to get statistic information across different classes(like get the latest viewed 10 entities{which can be A or B} from database) within the scope of OOP.

Obviously duplicating the whoViewed() method in 2 places is bad, so that option is off the table. You have a third option: Create a parent class that implements whoViewed() and have A and B inherit from it. The famous Gang of Four Design Patterns book recommends favoring composition over inheritance. So this would suggest making the Viewer class you mentioned in the question. Given the limited context provided in your question, I would suggest taking the GoF's advice and going with the Viewer class.

Incidentally, if you expect the implementation of whoViewed() to be different in A and B, you could make Viewer an interface and implement the interface in A and B.

We are going to develop a strong plugin-based c++ software. There is only few source-code examples for it. Due to the big size of the project, we want to do a simple software modeling, before we start to implement it. First of all class and sequence diagramms. We are newbies to UML, due to this reason, it would be nice, to have an UML-Example for a plugin-based project. We haven't found any examples for it on the web. Design patterns we want to use are i.e. plugins, plugins manager, factory method, singleton and some others. And now my question:

Do you know a (simple) example for a UML-Project for a similar software design?

Thank you.

Cheers Alex.

  • As for "factory method, singleton and some others", expressed in class diagrams, read the Gang of Four book.
  • As for plugins, you are looking in bad places. They are to be expressed in means of component and package diagrams, not class ones.
  • As for sequence diagrams, (also state machines, timing, activity...) , they are not intended for showing the problems of structure. And plugin is a structural term. Behavioral diagrams are useful, but they don't have any specifics when used for plugins.
  • For interactions of plugins, also look for UML communication and interactions overview diagrams. And maybe look at diagrams in the book "Enterprise Integration Patterns...". Their diagrams are not UML standard ones, but IMHO, are very convenient and useful for modelling of interactions on the level of components and packages (or plugins).

What is the best way to learn about programming design? I see lots of tutorials for programming languages, but a lot of them focus on specific language syntax. I want to really get into the aspects of design, using programs efficiently, etc. Where should I start?

Read a book on algorithms.

Learn OOP and read a book on Design Patterns

Realize that making code readable is often more important than making it as efficient as possible, and most optimization should be left up to your compiler.

Qt (pronounced officially as cute (/kyut/) though commonly pronounced as Q.T. (/ˈkyu ti/)) is a cross-platform application development framework widely used for the development of GUI programs (where it functions like a cross-platform widget toolkit), and also used for developing non-GUI programs such as console tools and servers. wikipedia

Qt was created by Trolltech, and was acquired by Nokia in 2008. One month after the end of symbian development at Nokia, Nokia decided to sell Qt. From September 2012 and until now Qt is managed by the Qt Company which is subsidiary of Digia.

Current version:

The latest official release is 5.7. The major version indicates API and binary compatibility.


There is extensive official documentation (all classes) available on Qt's website, in addition to tutorials and examples. You will often see these tutorials and examples referenced in the questions and answers on this site. Qt also provides an integrated development environment named Qt Creator. Though it mainly aims at creating Qt applications, it can be used to create regular C++ applications.

Tagging recommendation:

You will often see questions tagged specifically as , , or to indicate that the question is related to Qt 3.x, 4.x, or 5.x respectively. Qt 3.x is no longer supported and Qt 5.x has been released a while ago, so the default when version information is lacking is to assume version 5.x of the API.

Writing recommendation

Qt is a cross-platform application development framework, but QT (QuickTime) - is an extensible multimedia framework developed by Apple Inc.


Qt is available under four different licenses:

  1. GNU General Public License (GPL) version 3.0
  2. GNU Lesser General Public License (LGPL) version 2.1
  3. GNU Lesser General Public License (LGPL) version 3.0
  4. Qt Commercial License (which comes in three versions with different features and prices: "Indie Mobile", "Professional" and "Enterprise")

Video Courses

Pluralsight has a series of three courses on Qt:

Introduction to Qt: A C++ Cross Platform Application Framework
Qt Quick Fundamentals
Integrating Qt Quick and C++

Pluralsight is a subscription based but if you're only interested in Qt you can send the author @todgentille a private tweet and request a week long VIP pass. You'll get unlimited access to the higher subscription level for a week that allows viewing online and offline and you can download the course materials.

Voidrealm released a full free series of Qt tutorials for beginners on his youtube channel.


Qt introductory books:

Integrated learning of Qt and C++:

Concepts of UI design:

Please check out the official Qt documentation for more details of recommended books about Qt programming.


Please do not answer poor questions that will likely get closed or even deleted later. We are aiming for high-quality in this tag and so we do not wish to encourage poor questions coming by feeding them with answers.

Big List of Resources:

¶ Link to a PDF
$ Link to a printed book

A compiler is a program which translates one language into another. Compiler construction is the process of creating a compiler.

The tag should be applied to questions concerning the programming of compilers or for questions about the detailed inner workings of compilers.

One language to another? I thought they made executables!

The notional, garden variety compiler does exactly that: it translates a human readable computer programming language (like fortran or c++ or java) into a machine executable format. Or not.

In fact many real world compilers translate a high level language into assembly code which is subsequently assembled by a separate program. The standard java compiler translate java code into JVM bytecode, which must be run by a dedicated program (the Java execution environment) which may include a Just In Time (JIT) compiler that translates the bytecode into chip native machine instructions on the fly. The earliest versions of the language that became c++ were called cfront and were compiled to c. And so on.

Big List of Resources:

(Nothing serious in this question)

Ones a time I've read such an example of "bad application architecture":

There was a "rendering application" (browser, as far as I remember), so it was told, that having "render()" method in TagA, TagUL, TagDIV classes is really bad practice, because you'll have lots of "render-code" smeared all around. So (in this example), they adviced to have RenderA, RenderUL, RenderDIV classes that would implement rendering. And tag-objects would incapsulate those renderers.

I can't understand why that's a bad practice. In this case we'll have lot's of render code smeared around Render-* objects. And, finaly, why not to have Redner-singleton with lot's of overriden methods? That sounds, at least, cheaper.

What to read to understand it better?

Will the rendering for all of these different objects be the same? If so, then it should only be implemented once, most likely in a base class. This would be a better solution than a Singleton, which serves a completely different purpose: mainly to implement a resource (notice its a resource, not a method) that should only exist once.

If each implementation of render() will be different (which is most likely the case) then there is nothing wrong with them being implemented in separate objects, this is called polymorphism. What should probably be done though, is to have a class hierarchy in which the render() method is defined in the base class (most likely as abstract) and implemented in the derived classes. This effectively formalizes the interface, meaning that any class that inherits from said base class will have the render() method available and will have to implement it.

If you have parts of the render code that are common, and parts that are specific to the derived classes, instead of having to duplicate the common parts in all the derived class implementations, you can use a Template Method pattern, whereby the base class method does the common parts, and orchestrates calling the derived class implementation(s). Here is a pseudo-code example in C++

class TagBase {
    void render() {
        // do some common stuff here
        // do some more common stuff here

    virtual void doRender() = 0;

class TagA : public TagBase {
    virtual void doRender() {
        // do your specific stuff here

Here are a few good books:

How would you explain to someone who has just started programming in Java, what the difference between ArrayLists and Iterators are?

Why I would use an iterator instead of using the get() methods of the Arraylist

An ArrayList is a particular kind of List. It's a data structure, like a tree or a map or a list.

An Iterator is an example of a design pattern for walking through a data structure. You don't navigate a list the same way you would a binary tree, but an Iterator provides an interface that describes what's common to all data structure navigators.

So you might use an Iterator to walk through an ArrayList. They aren't the same thing. One's a navigator, the other's a container.

So why would you prefer an Iterator over just using the get() method for ArrayList?

Not all collections have a get() method (e.g., Collection and Set and binary tree). If you need to switch from an ArrayList to one of those data structures you have to rewrite all the code that calls get() as well.

But if you return an Iterator, clients of the code don't have to know that you've changed implementations.

If you use a get(), you use the implementation that's given to you. If you use an Iterator interface, you can swap implementations to do things like smart proxying without affecting clients.

It's about hiding details regarding navigation from clients of a class. If you just use ArrayList it might not matter much. But if you're designing classes of your own, you might find that Iterator gives you a nice way to expose behavior without giving away private details.

I am a newbie in software engineering and I want to specialize in C++. Now, I know C++ syntax very well and use Qt. But I don't have any knowledge about UML, design patterns or the Boost Library. Which library or topics do you recommend I learn first?

Learning syntax is like learning a grammar that is a stepping stone to become a poet. To become a poet you need to know how to form sentences that are easy and catchy.

Similarly for any language you should know how to design a system that is simple and maintainable. I suggest you to learn OOP Concepts, Design Patterns, and Refactoring

I am a recent grad from UNLV (low tier) and as I have gotten out in the field found that my current employer does not use any type of design pattern. I have however seen DI and factory being hyped up as all the rage, what is a good spot to start learning basic design principles. So far I have seen and heard a lot of people recommend GoF Design Patterns, but I have been warned that it is very dry and would not really go to well with my ADD. Is there a good video series on this stuff, everything I have personally found on YouTube sucks with unreadable code in the examples. Any links to sites that has a an idiots guide would be greatly appreciated as I feel my current job is not exposing me to good habits.


I am one of those guys who recommends the GoF book on Design Patterns:

  • it is anything but dry, since the GoF selected those patterns they found repetitively, so they are very practical. Furthermore, there are implementation concerns and code examples for each pattern.
  • some say there are better and more concise books, e.g. Design Patterns books in Java or in current UML, but I have found the GoF book better, since it covers so many aspects of the patterns, their advantages and disadvantages, as well as their interrelations.
  • since the material is quite deep, I prefer this book over others and over videos, because it is structured very well. Hence I can jump around in the book and look up things very quickly, which I do frequently. Furthermore, when I read the book the first time, I often stopped at a certain point, gave it a thought and wrote some remarks in the margin. That's quite difficult with a video.

I am experience some problems in understanding how the OO pattern works, My lecturer gave me the following question but I cannot solve it after thinking whole day

Scenario for my problems.

There is a class named "ShapeManager" which manages the Shape object. A class named "Shape" has two subclasses named "Circle" and "Rectangle"

The implementation of Shape class as follow

abstract public class Shape {
    private String id;
    private double length;

    public Shape() {

    public Shape(String id , double length) { = id;
        this.length = length;
    public void setID(String id) { = id;
    public String getID() {
        return id;
    public void setLength(double length) {
        this.length = length;
    public double getLength() {
        return length;
    public abstract String getDetails();


The subclass Square as follow

public class Square extends Shape{

    public Square() {
    public Square(String id , double side) {
        super(id, side);

    public String getDetails() {
        return "Square => Id : "+getID() +", Side : "+ getLength() + ",Area : "+(getLength() * getLength());

The subclass Circle as follow

public class Circle extends Shape{
    public Circle(){
    public Circle (String id, double radius) {
        super(id, radius);


    public String details() {        
        return "Circle => Id : "+getID() + ", Radius : "+ getLength() + ",Area: "+(3.14*(getLength() * getLength()));

The ShapeManager class as follow, this is not a completed class

public class ShapeManager {
    public Shape createShape() {

    public void updateLength(String id ){

    public void deleteShape(String id) {

    public void listShapes() {



ShapeManager have an association with Shape

 ShapeManager --1------0..*--> Shape

The design of this package (All the classes above) can not be changed, implementation must be following OCP (Open-Closed Principle).

My question is: How am I suppose to complete createShape method? Without parameter, it is seemingly impossible to create an object either a Rectangle or Circle.

ShapeManager cannot create a shape if not knowing what this shape is (Square, Circle or something else). And it really doesn't know because you say the method createShare has no parameters. Either you misunderstood the question or the lecturer didn't explain it well. You should ask him/her for clarifications. If you look at the libraries of Java or any other OO language, I am pretty sure you won't find such scenario and implementation pattern as the one you gave in your example.


You should find some other reading I think e.g. the classic book The main idea of a factory is that it returns something whose type the caller doesn't know, and doesn't care about. For example, if you have a method createSocket() in some SocketFactory, this method is usually defined to return an interface or an abstract class Socket. But actually it returns new SocketImpl1() and new SocketImpl2() which are concrete classes. What the factory returns may depend on many things - a system property, the underlying OS, anything you can think of. The main idea is that the factory centralizes the creation of Socket objects at one single place. This way, if you need to make a change, you can make it just in the factory. I think this book also has some decent Java counterparts too, you may look around. Other free good sources are referenced here.

Real world examples of Factory Method pattern

I am tasked to create a reusable piece of software as a library/API. Right now I have every class as public in multiple packages and the methods within them are mostly private.

Since this is supposed to be an API, I wish to hide all the classes except for exposing a few classes and methods.

I can't use the private modifier for the classes as I refer to them in other packages within the project. I also do not want to inherit the classes unnecessarily in order to access the methods within.

What should I do to expose certain classes and methods while maintaining the ability to access them within my project?

I really suggest that you chart down the following on a piece of paper before you start designing your API.

Pre Work

  1. Have you identified all the types of interacting entities. Each entity can be formed into an object.

  2. At what layer (Controller/Facade/DAO etc ) you wish to use each of these.

  3. Are any of the Objects expected to be transferred over a network.

  4. What data will your entire API be exposing.

Designing You would normally want to do the following:- If your entities (in part 1) are related and may contain common info, create 1 entity ( Example Common) to keep the common data (like timestamps of the request, device info etc) and make others that can contain this info, inherit this entity. ensure to have the properties of the common entity as protected. Common will look something like

   public class Common{
         protected _deviceId;
         protected _reqTimeStamp;
         protected _osVersion;

         //Getters and Setters. 

For example, if you API is using the JSON request data received from Mobile Apps, you can have Common to contain the data given above in point 1. You can create another Object as follows

public class UserInfo extends Common{
         private String _userName;
         private String _userMailId;

         //getters and setters 

Try to keep minimum entities for your Data Transfer between the layers. If the service layers that your API serves, are situated on different servers, then you may want to keep it Serializable and ensure that such DTOs do not contain chunks of huge information.

Similarly, when you segregate, the functionality of your API, try to see what functionalities are similar and commonly required. Move them to abstract classes and make the implementations to the interfaces that classify other behavior extend the abstract classes.

See this example below.

public abstract class CommonBehaviour {

protected String _commonId;

public void commonBehaviourOne()
    //Behaviour common to implementations

    abstract public void overrideThisBehaviour(); 

    //getters and setters

So now if you have two types of behaviours in implementations that have a common functionality between them.

public interface Designable {


public class DesignerImpl extends CommonBehaviour implements Designable {

    public void overrideThisBehaviour() {
        // TODO Auto-generated method stub



The decision to make the classes public, private or default will be easy once you have the pre-requisites clear. You have to brainstorm, discuss amongst the stakeholders and brainstorm again. You will definitely come up with a good API

References for your help

There is plenty of information available on the internet for people who enter designing. As far as books are concerned, I referred, "Head First Design Patterns" and Design Patterns by Gamma . Although i found Gamma more comprehensive, former is good for newbies.

Let me know if this helps you.

I am writing a simple prototype code to demonstrate & profile I/O schemes (HDF4, HDF5, HDF5 using parallel IO, NetCDF, etc.) for a physics code. Since focus is on IO, the rest of the program is very simple:

class Grid
  floatArray x,y,z; 

class MyModel
  MyModel(const int &nip1, const int &njp1, const int &nkp1, const int &numProcs);
  Grid grid;
  map<string, floatArray> plasmaVariables;

Where floatArray is a simple class that lets me define arbitrary dimensioned arrays and do mathematical operations on them (i.e. x+y is point-wise addition).

Of course, I could use better encapsulation (write accessors/setters, etc.), but that's not the concept I'm struggling with. For the I/O routines, I am envisioning applying simple inheritance:

  • Abstract I/O class defines read & write functions to fill in the "myModel" object
    • HDF4 derived class
    • HDF5
    • HDF5 using parallel IO
    • NetCDF
    • etc...

The code should read data in any of these formats, then write out to any of these formats. In the past, I would add an AbstractIO member to myModel and create/destroy this object depending on which I/O scheme I want. In this way, I could do something like:


I have a bit of OOP experience but very little on the Design Patterns front, so I recently acquired the Gang of Four book "Design Patterns: Elements of Reusable Object-Oriented Software". OOP designers: Which pattern(s) would you recommend I use to integrate I/O with the myModel object? I am interested in answering this for two reasons:

  • To learn more about design patterns in general
  • Apply what I learn to help refactor an large old crufty/legacy physics code to be more human-readable & extensible.

I am leaning towards applying the Decerator pattern to myModel, so I can attach the I/O responsibilities dynamically to myModel (i.e. whether to use HDF4, HDF5, etc.). However, I don't feel very confident that this is the best pattern to apply. Reading the Gang of Four book cover-to-cover before I start coding feels like a good way to develop an unhealthy caffeine addiction. What patterns do you recommend?

"Which pattern(s) would you recommend I use to integrate I/O with the myModel object?"

You're asking the wrong question. The question you should be asking is, "How can I separate my model from I/O?"

There's lots of answers. One interesting setup I've seen is Robert C. Martin's use of proxy. Your idea of using decorator also has merit.

I strongly disagree with those telling you not to worry about patterns. It is true that you should let the problem dictate the solution but until you actually try to use patterns you'll never learn to recognize them nor will you be able to use them in architectural discussions; patterns are very important to being able to discuss design and architecture and if you don't have the vocabulary you'll be severely handicapped in such discussions.

Perhaps more important than patterns though is to learn the principles that cause them. Learn the Open/Closed principle (the primary one) and the LSP. Also keep in mind principles like the single responsibility principle and others. Design patterns are born out of following these principles so knowing them intimately will help you recognize when a pattern can be applied and why one particular pattern can help more than another.

I am writing a text based game where I want users to be able to manipulate any item.

I want the user to be able to say, for example, "I throw the bottle of oil at the monster." Now when this happens [throw] will be an action, [bottle of oil] is an inventory item with the property [contains oil], and the monster will be the nearest monster in the room unless specified further.

Code needs to analyze the various properties of all these things and then pick actions that cause those things to interact.

When i write the Game story code it will be like follows

*room.darkroom.1 "wake up" [...] everything appears blurry, the voice sounds strange as if echoing down a long tunnel. From what you can see you can tell [you are in a dark room] your vision blurs from white to dark. [pc is inside very dark room. Inside this room everything is hidden in darkness. The northern wall has a locked thick wooden door. the southern wall has a barrel full of oil containing a bottle of oil. In the eastern side of the room are 2 medium sized crates one crate contains flint and rusty dagger. In the western side of the room a [small window] */room.darkroom.1

The script will take all those words and apply properties to them randomizing certain elements that are left unstated. So if you then say "chair" it will go to the chair properties and randomly assign unstated properties. One property of chair will be material. If its not stated that its an oak chair then the script should pick from any of the material properties and assign them. This new chair will pick up a few properties and be saved for future reference on the database with all properties.

Another property would be an action. A chair would not necessarily have an action .. but it might break. The script needs to know if the chair is breakable. But I am thinking that could be nested into another property like [toughness].

Many things will have many of the same properties: chair, night stand, table would all be similar in many ways. But they would also have different outcomes depending on the actions applied to them.

How do I specify for instance when "broken" contains chair legs and scrap material? The chair legs and the scrap material would both need to inherit the properties of the chair that was destroyed, such as oak / flammable / breakable. Obviously, as stated before, it might not have to inherit flammable or breakable if oak is the part that holds that value.

I want to make it easy to access the array that stores properties and that might include a script that effects behavior and descriptions of things.

I started to just create a keyed array which would be looped through... But now I am thinking that I should utilize the object based element of JavaScript.

Here is what i have started to do but I stopped right away:

var language = {
    // key    currentmodifyers   possible modifyers   action/condition description of item

    item: ";medium,material;;its a thing thats not a person",
    chair: "item,chair_Legs;;pile_of.@scraps.collection.chairlegx3/broken,@[chair ]scraps/destroyed; and someone could sit on it. ",

I have so many definitions to write so it would be a shame to start writing it all and then have to do it over when I discover the best way.

I am looking at various ways to build objects in JavaScript, but would like the best way from someone experienced.

Understanding the complexity of my problem, what is the best way to store and apply properties?

There are actually two good thoughts in your question:

But now I am thinking that I should utilize the object based element of JavaScript.

You definitely need to use objects instead of arrays, the OOP ideas can be directly applied to your descriptions. Some objects are composed of smaller parts (the "composition" in OOP) and some inherit properties of other objects (the "inheritance").

So you could have some base Item class which defines basic operations and properties for all objects (like they have different properties and can do some things).

Then you can add objects like StaticItem (will be base for chairs, night stands, etc) and LiveBeeing (monsters, etc). And now you can actually create the Chair (pseudocode):

StaticItem extends Item
    this.material = oak // oak is an object of OakMaterial

    // is this static item flamable?
    this.isFlamable = function() {
        // we "redirect" flamability detection to the material
        return this.material.flamable();

Chair extends Static
    // break this chair!
    this.break = function() {
        // when it is broken we return a HeapOfCrap, it is a 
        // Static subclass which contains some sub-items
        // In this case the heap contains 4 chair legs of the
        // same material as the chair
        return HeapOfCrap([
            new ChairLeg(this.material), new ChairLeg(this.material),
            new ChairLeg(this.material), new ChairLeg(this.material)

And so on, you need to plan you object structure carefully and there is a good field to apply some of the design patterns.

The example above is just what came in my mind immediately, while actual design should take much more time and thinking.

The second good thought in your question is about the huge amount of work:

I have so many definitions to write so it would be a shame to start writing it all and then have to do it over when I discover the best way.

You absolutely right here, would you select to use objects or arrays, or anything else - don't try to describe all your game right away.

Select few basic elements, like "Room", "Door", "Chair", "Monster", "Player" and try to code the minimal game with only these elements.

Play with the structure to find the good design and once you are sure it is good - go on and add more elements to the game.

I have a dependency factory class, like

class DependencyFactory {
    static Dependency dependency1 = getDependency1FromSomewhere();

    static Dependency dependency2 = getDependency2FromSomewhere();

    public static Dependency getDependency(int arg1) {
        if (arg1 == 1) return dependency1;
        return dependency2;

Now my confusion is on the name of the class DependencyFactory. I think this is not exactly a factory, but a decider class which return a predefined dependency based on the argument. So, is it ok to name is like DependencyFactory, or should it be something else?

Thank you. Please comment for any additional information.

Strictly following definition from GoF book

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

one would have to say: no - your class is not factory, because this pattern gives you a way, to instantiate class.

Maybe what are you looking for is a strategy pattern

From my experience with design patterns often it is impossible to tell definitely which is a proper way to go, without knowing context of your system.

I have a Java system that consumes an API. A few days ago, we started facing the following problem: the remote API was receiving too many requests from my system. Back in the system's early days, it was not a major concern, but little by little the system's performance was getting worse and worse, since my data was growing and I made multiple requests for each entity. I noticed many of the network requests I made were not really necessary, since the data was not updated very frequently. So, I implemented a class that, when my system starts, makes an over-eager loading of all the remote API data. When I create/update an entity, I load it before any request is made. I treat deletion accordingly. And the remote API also notifies me when any change is made so I can stay updated even when this change is made outside my system.

What I really want to know is: is there any name for this practice? Any known design pattern ? I must say I've done a little research and I think it is a proxy pattern but, again, I'm not very sure (in fact, most of the design patterns look very similar), and I'm not really that much into design patterns.

It's not quite a proxy pattern as the proxy pattern falls more under the heading of 'lazy loading'. From the description of the Proxy Pattern specified in Design Patterns (Group of Four Book):

One reason for controlling access to an object is to defer the full cost of its creation and initialization until we actually need to use it

I'm not sure what you'd call it other than over-eager loading

I have a standalone java application in which one function call from the GUI will result in multiple changes in instance variables of different classes.We want to write a transaction manager for this so that if some exception is thrown then changes done in memory prior to execution block are reverted.We can surely do it a naive way by creating a copy of instance variable before the call , and reverting the changes if exception occurs , but i am looking for some sophisticated and a good design to handle this problem.

Please let me know if any one has idea of some framework or generic design that can be used to solve this problem.

You can use the Memento design pattern to store the state of the objects. If everything goes fine, you delete the last stored state. If there is some problem, you restore the last state. Here is a reference (a poor one) Try Google for more details.

The Memento works similarly of what you said, but it formalizes an architecture to provide this feature.

Here is the classical reference:

I have the following code that I am calling using this statement: SQLiteDB *db = [[[SQLiteDB alloc] init] autorelease];

The problem is "sharedSQLiteDB" is not being called, but rather "allocWithZone" is, and therefore "checkIfDatabaseExists" is not being called, which is where the database is created.

I don't understand why... (i.e. what am I doing wrong?)

#import "SQLiteDB.h"

static SQLiteDB *sharedSQLiteDB = nil;  //  makes this a singleton class

@implementation SQLiteDB

@synthesize searchPaths, documentPath, databasePath, cDatabasePath;

#pragma mark Singleton Methods

+ (SQLiteDB *) sharedSQLiteDB  {

    if(!sharedSQLiteDB)  {
        sharedSQLiteDB = [[SQLiteDB alloc] init];
        [sharedSQLiteDB checkIfDatabaseExists];  //  check to see if d/b exists
    return sharedSQLiteDB;

+(id)allocWithZone:(NSZone *)zone  {  //  makes sure another instance is not allocated
    if(!sharedSQLiteDB)  {
        sharedSQLiteDB = [super allocWithZone:zone];
        return  sharedSQLiteDB;
    else {
        return nil;

-(id)copyWithZone:(NSZone *)zone  {
    return self;

-(void) release  {
    //  no-op

In the singleton pattern your use pattern should be:

SQLiteDB* db = [SQLiteDB sharedSQLiteDB];

They way you are calling it doesn't fit the singelton pattern. All access should be through your sharedSQLiteDB message.

In other words you shouldn't be initializing via typical Cocoa patterns (SQLiteDB *db = [[[SQLiteDB alloc] init] autorelease]; is incorrect and full of problems) outside the scope of the class.

In a singleton using the default initialization pattern for the language (alloc/init for ObjC or the default constructor for C++) should generate a compile time error message since the constructor/init method should be protected.

See the Wikipedia entry. consult the Design Pattern C++ bible. There is even a version for Cocoa

Good luck.

I have the following domain, a dossier with documents:


Now there is a new requeriment for a few dossiers which have subjects and each subject has documents, so the new domain would be like this:


For these few dossiers (7%) , I have to change a simple design for a more complex design. My question is: There is a design pattern or any idea which I can use for support the subjects but avoiding to change the initial domain.

There are many things to consider when choosing a pattern

If the design changes dynamically acording to a context which is external to Dossier consoder Delegation pattern (wiki).

If this should be set during a "construction" or "initialization" stage you can consider a pimpl ( or Decorator (wiki) pattern

Or maybye you need something different...

The choosen solution should depend on the exact problem that you need to solve. Two simple rules are:

  1. Favor composition in place of inheritance
  2. Encapsulate the variability

1) Means delegate to work to a components. Each cpmponent should do a "one thing" but do it good.

2) Means if there is a part in your system that is subject to change - encapsulete it in a seperate entity(ies)

For an introduction material in design patterns I could recomend tyou the "gang of four" book" Design Patterns: Elements of Reusable Object-Oriented Software

I'm creating a multiplayer card game. I have two main classes:

  • Player - represents a player in the game.

  • Manager - is the manager of the game.. it is a singleton and holds the the main card deck and all the Players.

My question is what is the best design for the relationship between Manager and Player. I think that Manager should know all the players but the players should not know him... that's because if one day I will want to use the player class for other card games it will be very generic.

In order to use my design I should create many events for the Player class. for example getCardFromTheDeck.

What is the best design?

Design of you game should be decided heavily on your requirements, your question is too confusing this way, and not constructive.

I'll give you an example of what you are asking: I would say that an average game should have a game board, players and game controller (at very least). Board should have a collection of all the cards laid down, not drawn etc... Players should have collection of current cards they possess. Game controller should have methods like start game, determine winner etc...

For game logic you can have something like Strategy patterns, you need some way of expressing rules etc...

... and you continue thinking like this. Be aware of basic OO priciples, like SOLID, most important of all Single Responsibility Principle.

For design patterns guidance that can give you ideas, refer to GoF Design Patterns.For more examples, find some game source codes online and study them. You will get some ideas, and from those, your design will benefit.

I'm currently designing a list widget to add to my widget engine. Since every elements visual aspects are defined outside the code I can reuse most of the code base. For instance tab buttons are actually checkboxes. New templates take time to implement since they should have at least a viewer in design application.

I already have an implementation for a checkbox. It has 2 states (checked/unchecked) and 5 substates: normal, hover/active, mousedown, disabled and in state transition. A checkbox template has text properties, icon (optional), and border (might be resizable). There are also state and substate transitions. Both icons and borders are animatable.

My concern is about list items. They are quite similar to checkboxes. Therefore, Im planning to use checkbox template for listitems. However, I require four modes of a list item: simple (text only), with icon, with a checkbox and with a radio button (a radio button is derived from a checkbox and IRadioButton interface). Here its structure:

   Checkbox       IRadioButton
      \                /

I wish to implement something like this. ListItemBase should be derived from IWidgetObject. Is it logical or are there better alternatives.

  class ListItemBase : public Checkbox {
      void Select() { do something; Checkbox::check(); }

  //This listitem type will have a checkbox without any text
  class ListItemCheckbox : public ListItemBase, private Checkbox {
      check() { update parents checked list; Checkbox::check(); }

  class ListItemRadio : public ListItemBase, private RadioButton, public IRadioButton {
      //here is the problem

ListItemRadio will have 2 distinct checkbox functionality, also I want to hide ListItemBase's check() function (to rename it). Then should I implement it this way?

  class ListItemBase : private Checkbox, public IWidgetObject {
      void Select() { do something; Checkbox::check(); }

      //does this even works? (layer is a variable)
      using Checkbox::layer;

  //This listitem type will have a checkbox without any text
  class ListItemCheckbox : public ListItemBase, private Checkbox {
      check() { update parents checked list; Checkbox::check(); }

  class ListItemRadio : public ListItemBase, private RadioButton, public IRadioButton {
      //here is the problem

But this time I have 2 IWidgetObjects in ListItemRadio, which I should overcome implementing common functions. But ListItemBase will have to map everything of IWidgetObject to Checkbox.

Is it possible to use virtual inheritance to solve these problems, like delegating to sister class (checkbox). There is also one more problem, although IWidgetObject seems like an interface, over the years it picked up some common implementation, but I dont think it will be a problem.

Also there is one more problem. Checkbox class has non-trivial constructor. Is it possible to write something like this:

 ListItemBase(IWidgetContainer &container, CheckboxBP &blueprint) : 
        Checkbox(container, blueprint), IWidgetObject(this) {

This would solve lots of problems. Any idea is welcome.

Thank you for even reading all these

I do not know the details of your "widget engine" and "templates", so maybe you've designed that in a way that now forces your hand (I hope not!), but it seems to me that you're using inheritance where the natural design would, instead, use containment and composition -- a much preferable solution. I.e., you're saying that a list item "IS-A" checkbox, while the natural state of affair is that a list item "HAS-A" checkbox (and similarly for radio buttons).

If you're forced to operate this way by the design of the widget engine, then it's not surprising that you end up with the need for multiple inheritance -- but that can add its own complications, and, in any case, subclassing leads to strong coupling and low flexibility, while containment and composition are better in these regards. I recommend reading the classic Design Patterns, which explains these issues very well.

Anyway, if you are trapped into this kind of design, then, yes, it is possible, as you say, to write:

ListItemBase(IWidgetContainer &container, CheckboxBP &blueprint) : 
        Checkbox(container, blueprint), IWidgetObject(this) {

However this does not imply that the Checkbox base class constructor executes before the IWidgetObject's one: that depends on the order in which you have declared your bases (if you declare IWidgetObject as the first base, its constructor will execute before the other).

I'm looking for more information about dealing with trees of class instances, and how best to go about calling methods on the leaves from the trunk. I have a trunk instance with many branch instances (in a dictionary), and each has many leaf instances (and dicts in the branches). The leaves are where the action really happens, and as such there are methods in the leaves for querying values, restoring values, and many other things.

This leads to what feels like duplication of code, as I might want to do something to all leaves of a branch, so there are methods in the branches for doing something to a leaf, a specified set of leaves, or all leaves known to that branch, though these do reduce the code duplication by simply looping over the leafs and asking them to do said things to themselves (thus the actual code doing the work is in one place in the leaf class).

Then the trunk comes in, where I might want to do something to the entire tree (i.e. all leaves) in one fell swoop, so I have methods there that ask all known objects to run their all-leaf functions. I start to feel pretty removed from the real action in the leaves this way, though it works fine, and the code seems fairly tight - extremely brief, readable, and functioning fine.

Another issue comes in logical groupings. There are bits of data I might want to associate with some, most, or all leaves, to indicate that they're part of some logical group, so currently the leaves themselves are all storing that kind of data. When I want to get a logical group, I have to scan all leaves and gather them back up, rather than having some sort of list at the trunk level. This actually all works fine, and is even pretty logical, yet it feels insane. Is this simply the nature of working with tree-like structures, because of their complexity, or are there other ways of doing these kinds of things? I prefer not to build secondary structures to connect to things from the opposite direction - e.g. making a structure with references to the leaves in a logical group, approaching them then from that more list-like direction. One bonus of keeping things all in a large tree like this is that it can be dumped and loaded in one shot with pickle.

I'd love to hear thoughts - any and all - from anyone else's experience with such things.

What I'm taking away from your question is that "everything works", but that the code is starting to feel unmanagable and difficult to reason about, and: is there a better way to do this?

The one thing your question is missing is a solid context. What sort of problem is your tree structure actually solving? What do these object actually do? Are they all the same type of object, or is there a mix of objects? With some of these specifics you might get more practical responses.

As it stands, I would suggest checking out some resources on design patterns. Specifically the composite and visitor patterns.

On the book end of things you could have a look at Design Patterns and/or Refactoring to Patterns. Neither of these have any Python code in them, but if you don't mind Java, the latter is an excellent introduction to taking hard to reason code structures and using a pattern to better organize things.

You might also have a look at Alex Martelli's talk on Python Design Patterns.

This question has some further resource links regarding patterns and python in general.

Hope that helps.

In PHP, what means: factory, instance and observer?

Thank you!

It's not relative to PHP only. What those words mean are "design patterns" concept, that is, a method of organizing code that achieves a series of properties, such as loose dependency, ease of reuse and test.

I suggest you a book colloquially called Gang of four. It explain basic design patterns and it's a classic in its topic.

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Many patterns imply object-orientation or more generally mutable state, and so may not be as applicable in functional programming languages, in which data is immutable or treated as such.

Gang of Four design patterns

Concurrency patterns

Other patterns

Useful links


In the strategy design pattern, I need to store a reference to the Compositor in the Composition(pp315 GOF). For one of the implementation method, the client will pass a reference of the Compositor to the constructor of Composition, I would like to know which API interface is better from design point of view.

For example:

1> A(boost::shared_ptr<int> ptr) // assume that ptr referring to the Compositor

2> B(int* ptr) // assume that ptr referring to the Compositor

I have given the following example to illustrate the usage of two different interfaces. They are NOT the implementation of strategy design pattern! The code is provided to help me demonstrate the different ways that the client can call the Composition with the pass-in parameter of a reference to Compositor.

#include <boost/shared_ptr.hpp>
using namespace std; // for convenience
class A {
    boost::shared_ptr<int> m_sPtr;
    A(boost::shared_ptr<int> ptr) : m_sPtr(ptr) {}

class B {
    boost::shared_ptr<int> m_sPtr;
    B(int* ptr) : m_sPtr(ptr) {}

int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
    boost::shared_ptr<int> temPtr(new int(100));
    A a(temPtr);

    B b(new int(200));

    return 0;

Thank you

Is the following java implementation of the visitor pattern using generics, general enough to be useful? (I suppose it is).

Could it be improved in some way? It's important to be easily call-able using anonymous classes. Thanks.

(Example of use):

Vector<Number> numbers = new Vector<Number>();

        numbers.add(new Double(1.2));
        numbers.add(new Float(-1.2));
        numbers.add(new Double(4.8));
        numbers.add(new Float(-3.4));
        numbers.add(new Long(123456));
        numbers.add(new Short("14"));

        For.each(numbers, new Visitor<Number>() {
            public void doIt(Double n) {
                System.out.println("doIt() for double: " + n);
            public void doIt(Float n) {
                System.out.println("doIt() for float: " + n);
            public void doIt(Number n) {
                System.out.println("doIt() for Number: " + n);

        Visitor<Number> visi =  new Visitor<Number>() {
            private StringBuffer  all = new StringBuffer ();
            public void doIt(Number n) {
                System.out.println("doIt() for Number: " + n);
                all.append(n.toString() + " ");
            public Object getResult () {
                return all;

        For.each(numbers, visi);

        System.out.println ("all -> " + visi.getResult());


abstract class Visitor<T> {
    public void visit(T n) {
        try {
            this.getClass().getDeclaredMethod("doIt", n.getClass()).invoke(this, n);
        } catch (Exception ex) {
            doIt((T) n);
    public void doIt(T n) {
        System.out.println("doIt() for base " + n);
    public Object getResult() {
        return null;
} // class

class For {
    public static <T> void each (Collection<T> c, Visitor<T> f) {
        for (T v : c) {
    } // ()
} // class

This is not the Visitor Pattern.

Visitor is characterized by the visitee having an accept(Visitor v) method that interacts with an visit method in the visitor taking as parameter the visitee and overloaded for the varying type of the visitee, forming a "double dispatch" mechanism.

Quoting from the "Applicability" section for Visitor in Design Patterns:

Use the Visitor pattern when
  • an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.
  • many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.
  • the classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.

So this pattern is for dealing with similar opertaions on objects of multiple types. In your examples the objects you're calling visitors can only deal with one type.

In your answer revising to use reflection to handle multiple types (which by the way would be better done as an edit to the question or as a separate question), you're avoiding creating an accept(Visitor v) method in the visited classes by using reflection, which is to a degree accomplishing the same goal, but somewhat awkwardly. I still would resist calling it an implementation of Visitor.

If code in the style you've written here is useful to you, by all means use it, but please don't call it a Visitor.

This is more like a Strategy Pattern or a Function Object, and if you rename the generic class in a way that reflects that, it's in fact useful, and your usage is similar to common patterns of list handling in functional languages.

What I would likely do with the code from the question is rename your Visitor<T> to Operation<T> and rename your visit(T t) to execute(T t) or apply(T t), thinking of an Operation as a Function without a return value. I have in fact used exactly this in ways similar to what you're doing, and used similar tactics for collection "mapping" using generic Function<Domain, Range> objects. I'm not sure what pattern name actually fits it, but it's not Visitor. It's bringing functional list-comprehension style to an OO world where functions are not naturally first-class objects.

is there any new design patterns available other than the patterns covered by GoF book and Head First Design Patterns? Have any one of you used your own design patterns in your projects? Please let me know. if possible give some UML Diagrams. Thanks in advance.

The "sequel" to the GoF book is Pattern Hatching by John Vlissides. It does not publish really new patterns, but variations of some included in the original GoF book. Its great value is rather in that it shows the thought and design process involved in applying the patterns.

Although this is not an answer to your question in the strict sense, there are also lots of other kinds of patterns relevant to our field:

I've been programming in ActionScript for a while now even though I barely understand how extending classes exactly work. Most of my projects have been one-file scripts so you can probably imagine trying to work with a 1000+ line file (that's probably too little for some of you :P).

Trying to look through numerous online tutorials have been daunting and or confusing at most, and don't explain how extending actually works. Finding one that describes each essential keyword needed would be nice.

In past projects, I've managed to use two scripts, though not technically extending a class (I believe). For example: (Main file)

package {

    import flash.display.Sprite;

    public class Main extends Sprite {

        public function Main () {
            trace(GLOBAL.version); // "1.0"


} (a helper script in the same directory):

package {

    public class GLOBAL {

        public static var version:String = "1.0";



It appears that even though I hadn't specifically imported the file, it's still accessible.

What I'm asking from the SO community is: How can I better understand how extending a class works, using files in the same directory and another directory, Use the Main file as a simple "includer" and other files as helpers, such as adding a Sprite to the stage. Hopefully I'm not making this more difficult than it is. But for some reason I just can't "get it".

Other note: I've been working with JavaScript a lot more than I have ActionScript, so any guru's out there wanting to give a tutorial on going from JavaScript to ActionScript would be a plus!

Another word for a directory containing scripts is a 'package'. In AS3, files in the same directory or package are automatically available to each other, and so there's no need to explicitly import them. Files in sub-directories are not automatically imported, and neither are files are parent folders.

As far as the structure of your classes and their interactions is concerned, I would recommend becoming familiar with OOP design patterns. The Gang of Four book is an excellent reference although it does not deal specifically with AS3, or alternatively O'Reilly publish a more specific Adobe Developer Library reference.

I want to learn core java design patterns.

Could any one of you suggest good pdf where I could know about the design patters in java with simple examples.

Thanks in advance :-)

The book about design patterns is called Design patterns - elements of reusable object-oriented software.

It is not specifically for Java (written before Java was created), but the object-oriented concepts are clear.

Wikipedia lists and explains all patterns included in that book.

O'Reilly - Head First Design Patterns

I found the approach really interesting and less boring than most design pattern books, examples are really easy to understand... All in all well worth the investment, got the ebook version (you can choose from pdf, mobi and epub) for $15 on sale from O'Reilly site.

I was programming for a while. Starting at school, writing small utility programs as a hobby and now professionally. My problem is I'm getting distracted while writing software (I come up with a new feature and fallow it immediately) so my code is usually disorganized. Now when I’m starting my career as a professional developer I find out that even though my software works pretty well the code doesn’t look pretty. I often find myself creating to many or to little classes – sometimes it just doesn’t feel right. Overall I’m losing precious time when I could earn money doing another project.

I’m looking for a book that will teach me how to design software structure without juggling the code in the middle of the creation process.

If you're looking for Design Patterns, there are two authoritative books to look at:

Head First Design Patterns

alt text

Design Patterns: Elements of Reusable Object-Oriented Software

alt text

I will describe a simplified example of such "dependency hell".

Imagine a video player with "play/pause" and "mute/unmute" buttons. Pausing the video should pause sound but not mute it, so that unpausing the video should unpause audio.

Then imagine we are downloading audio and video in separate files, so we have four success/error callbacks. Imagine video can play without audio but not conversely. Now imagine how many changes should be made to the code if the requirements update so that video and audio should wait for each other.

Currently I'm dealing with this using callbacks and boolean variables. I have a feeling this is stone age, because something like this:

if (videoShouldPlay && audioShouldPlay && isAudioPlaying && isVideoDownloaded && isAudioDownloaded) {

or 4 similar callbacks:

audio.onload = function () {
    if (isVideoDownloaded)
    } else { ...

is neither readable nor maintainable. The number of dependencies grows exponentially with the number of components, but I should not track every dependency when I can define some general rules .

I'm sure computer science has solved this problem already.

It looks like to me you need a state machine. Let's take for example the states "playing" and "paused". The rule for the transition "playing" ➜ "paused" would be what you write: "Pausing the video should pause sound but not mute it", etc. It's hard to tell more about it without seeing the actual problem you have at hand.

I would recommend Chapter 29 State from Agile Software Development, Principles, Patterns, and Practices and Replace State-Altering Conditionals with State from Refactoring to Patterns. I personally find the famous Design Patterns: Elements of Reusable Object-Oriented Software book somewhat difficult to read, nevertheless it is the State pattern in it.

Let´s say I have two classes:

public Foo
   public List<Foo> Childs { get; set; }
   public Bar BarObj { get; set; }
   public int Level { get; set; }

public Bar
   public List<Foo> Childs { get; set; }

Now I want to get the nesting-level from a Collection of "Foo" Objects

my current working Method looks like this:

int currentLevel = 0;
public void ApplyNestingLevel(List<Foo> list)
    foreach(var item in list)
        item.Level = currentLevel;
        if(item.Childs.Count > 0 || item.BarObj.Childs.Count > 0)

how could I make this more "elegant/simple" ?

Store a reference to the parent and make the Level property recursive.

I added an example and a couple other design suggestions in the code sample below. Hope this helps. FYI, this is pretty much straight out of the Gang of Four's design for the Composite Pattern, which should be required reading for anyone who is serious about OOP.

  • DoFactory .NET Composite Pattern
  • Design Patterns: Elements of Reusable Object-Oriented Software, on

        public class Foo
            public Foo(Foo parent = default(Foo))
                this.parent = parent;
                this.children = new List<Foo>();
            private readonly Foo parent;
            private readonly List<Foo> children;
            public int Level { get { return ReferenceEquals(parent,null) ? 0 : parent.Level + 1; } }
            // don't expose the actual list... see below for why
            public IEnumerable<Foo> Children { get { foreach(Foo child in this.children) yield return child; } }
            //  instead of exposing the child object list
            //  declare an explicit method with any parameters 
            //  necessary.  this allows you to enforce the invariant 
            //  condition that all objects in a children collection
            //  will have their parent reference set to their 
            //  actual parent
            public void AddChild()
                Foo newChild = new Foo(parent:this);
            //  if you need the ability to remove items as well, 
            //  you can expose a remove method too.  Just make 
            //  sure that you validate expected preconditions
            public int RemoveChild(Foo childToRemove)
                if(ReferenceEquals(childToRemove,null)) throw new ArgumentNullException("childToRemove");
                if(!ReferenceEquals(this,childToRemove.parent)) throw new ArgumentException("The object cannot be removed because the current object is not the correct parent.","childToRemove"); 
                return children.RemoveAll((Foo existentChild) => existentChild.Equals(childToRemove));

Observer pattern-

  • Out of the 10 items, the observer only wants to be subscribed to 3.
  • Subject calls a function of the observer to let him know that there are some updates.

Now, is it subject's responsibility to send the updates pertaining to only 3 items to the observer?
Subject can simply tell the observer that there are updates - go fetch whichever you want out of 10?

Which is the correct way out? Does it matter?

Now, is it subject's responsibility to send the updates pertaining to only 3 items to the observer?


Subject can simply tell the observer that there are updates - go fetch whichever you want out of 10?

Which is the correct way out? Does it matter?

There is no absolute right answer here.

These are implementation choices, and in fact are mentioned in the implementation section for Observer in Design Patterns:

_6. Avoiding observer-specific update protocols: the push and pull models. Implementations of the Observer pattern often have the subject broadcast additional information about the change. The subject passes this information as an argument to Update. The amount of information may vary widely.

At one extreme, which we call the push model, the subject sends observers detailed information about the change, whether they want it or not. At the other extreme is the pull model; the subject sends nothing but the most minimal notification, and observers ask for details explicitly thereafter.

The pull model emphasizes the subject's ignorance of its observers, whereas the push model assumes subjects know something about their observers' needs. The push model might make observers less reusable, because Subject classes make assumptions about Observer classes that might not always be true. On the other hand, the pull model may be inefficient, because Observer classes must ascertain what changed without help from the Subject.

_7. Specifying modifications of interest explicitly. You can improve update efficiency by extending the subject's registration interface to allow registering observers only for specific events of interest. When such an event occurs, the subject informs only those observers that have registered interest in that event. One way to support this uses the notion of aspects for Subject objects. To register interest in particular events, observers are attached to their subjects using

void Subject::Attach(Observer*, Aspect& interest);

where interest specifies the event of interest. At notification time, the subject supplies the changed aspect to its observers as a parameter to the Update operation. For example:

void Observer::Update(Subject*, Aspect& interest);

If it makes more sense in your situation to use the push model, so the subject has a bit more knowledge of the observers' needs, and to use an aspect model so that the observers can register interest in particular portions of the subject's data, go for it!

I usually prefer to use the pull model and accept that the observer has a bit of detailed knowledge of the subject (it's simpler to implement), but what you're proposing is probably fine in your situation.

Software engineering is concerned with optimising the quality of software projects and the software systems the produce. The process of engineering a software system has many phases and software engineering is the discipline concerned with the whole life-cycle. The life-cycle includes these and potentially other phases:

  • Requirements Engineering: The requirements of the client and other stakeholders are elicited and (usually) documented to provide an specification of what the software should do (and not do). Ideally, requirements are managed throughout the life-cycle to account for change.
  • Design, Architecture and Implementation (Development): Developers decide on high-level architecture and more detailed design to address the challenges of the problem space. The design is implemented in code it using various technologies tools and computer languages; the selection of which is often constrained by stakeholders.
  • Verification & Validation (Quality Control): In this important phase, a high level software validation activity occurs, much of it on a near-complete version of the software system. Testing has become a very important part of software development due to Kent Beck's approach of Test Driven Development
  • Maintenance, Support and Configuration Management: Software needs to be maintained, sometimes to add new features or improve existing ones but often to manage a decaying or unstable execution environment. Configuration management is the practice of managing versions and managing the different components of the software.

Many different scientist have brought many new ways to practice software engineering, like design patterns, and many new approaches to create more robust and powerful software. There is much required reading in the field of design patterns, but the most important texts are:

One of this time's more important software analysts/engineer/architect is Martin Fowler, so his collection of books and bliki are mandatory readings as well.

Another approach is Aspect Oriented software development which looks to separate the program's functions from the Actual business logic.

So I have been writing in c++ for a few weeks now and can't help but feel that I am using too many if statements in my code. I am aware of while, do while, and for loops but when given the scenario I always use if statements. I guess I am not exactly aware of how I could use a different method. I just finished a project and there are if statements everywhere. Could one of you guys please explain to me how I can change some of these if statements into something different but still functional? I am really just looking for guidance in the right direction. Any help will be appreciated. Thank you guys!

If statement #1 that bugs me:

    if (x >= 1)
        cout << "Soldier moves: " <<getx_Position()<<", "<<gety_Position()<< "   ";
        cout << endl;
        cout << "Soldier moves: " <<getx_Position()<<", "<<gety_Position()<< "   ";
        cout << endl;
    return 0;

Second if statement bugging me is :

    if (a >= 0)
        cout << "Soldier fires weapon : Pistol " << "(" << a << " bullets left)" << endl;
    else if (x <= 0)
        cout << "Soldier fires weapon : NO WEAPON FIRED! (DEAD)" << endl;
    return 0;

Both of these just feel lengthy and unnecessary to me. How could I get the same results with a much cleaner look? Or is this the best way to do it?

Well, Turing would be proud for so much loyalty to the behaviour of the original Turing machine but in modern C++ there are other weapons in your arsenal, I suggest to read a book about patterns, maybe this one, there is not such thing as "optimizing" or suggest something starting from your snippets, it's merely pointless because a single if can't really impact on your productive skills, you need a foundation about advanced C++ techniques.


Wow, the initial response to this question was quite negative. I think I might have triggered some pretty strong emotions by using the word "best"; it seems like a few people latched onto that word and decided to dismiss my question right away.

Obviously, there are many, many situations in which no single approach is "best", or at least, what ends up being the best solution to one problem will often not be the best solution for other, even similar, problems. I get that. But now let me try to elaborate on the reasoning behind what I'm actually asking.

I tend to find it easiest to explain myself using analogies, so here goes. In my current job I work almost exclusively in .NET. .NET has a lot of functionality built into the framework. A prime example is the System.Collections.Generic namespace, which has a bunch of collection classes that (almost) no .NET developer in his/her right mind would bother re-developing from scratch, because very good implementations are already there. If I am working on a problem that requires a doubly linked list, I'm not going to decide, "Okay, time to write a doubly linked list class"; I'm just going to use the LinkedList<T> that's already there, or, at most, extend it or wrap it with my own class that adds some extra functionality.

Am I saying the "best" version of a doubly linked list is LinkedList<T> from .NET? Of course not. That would be absurd. But I highly doubt .NET's implementation of LinkedList<T> is drastically different from most other established libraries' implementations of collections that are intended to serve the same purpose (that of a doubly linked list). On the other hand, I am relatively confident that if I were to write my own implementation from scratch, there'd be a considerable number of issues with it, in terms of robustness, performance, flexibility, etc. for one simple reason: not that I'm stupid, or lazy, or don't care about good code--simply that I'm one person, and I'm not an expert on linked lists, and I haven't thought of everything that needs to be taken into consideration when designing one.

But I happen to be a developer who does take an interest in how things are implemented internally. And so it would be nice if I could check out a page where some variant of a well thought-out design for a linked list--or for any fairly established concept for which robust, efficient implementations have been written--were available to view. (By the way, yes I am aware that the source code for .NET's LinkedList<T> is available. I'm just using that as an example; really I am talking about all problems with solutions for which good, working implementations exist.)

Now, I talked about this being something that is open; let me elaborate on that. I am not talking about sites like, or CodePlex, or Google Code. These are all sites for hosting projects, i.e., applications or libraries tailored for some specific industry or field or otherwise categorizable purpose. What I'm talking about is something like this:

Maybe I should have just provided that link in the first place, as it probably illustrates what I'm getting at better than anything I've written so far. But I think the main point that differentiates what I'm asking about from any other site I've seen is that I was specifically wondering if there could be some way to work on a new problem--so, something for which there aren't necessarily any well-known, established implementations, again as in my linked list example--collaboratively, in a wiki-esque fashion, but not tied to any specific open-source project.

So, as a conclusion of sorts, I was kind of envisioning a situation like the following: I find myself faced with a new problem. Maybe it isn't common enough to be something that is addressed in a framework like .NET. But it's common enough that some developers here and there are independently working on it. If a website exists like what I'm imagining, maybe at some point one of those developers working on the problem could post an idea on that website, and over time others might discover it and suggest improvements/modifications, and given enough time and participation, a pretty darn good implementation might result from all this collaboration. And from there, eventually, something like this implementation might be considered fairly "standard", just like a linked list implementation, or a quicksort implementation, or, I don't know, some well-known pseudo-random number generator.

Does this make any more sense to anyone now? I feel quite confident that what I'm talking about is not absurd, but hey, if that's what people think, then maybe it is.

Open source projects are very popular. Some of these are libraries suited for specific purposes, the best of which include some very well-written code.

However, if you're interested in contributing to an open source project, finding a project that is well-suited to your skills can be quite a task. At the same time, if you're interesting in using an open source project in your own work, finding a project that is well-suited to your needs can also be difficult, especially when, for example, open-source library X has a lot of functionality you could use, as does library Y, and these two libraries' capabilities overlap so that integrating both into your code could be messy.

We've all seen questions, here on Stack Overflow and elsewhere on the web, posted by one developer: "How would I implement this idea?" and answered by others, often accompanied by a plethora of example code. Sometimes these answers link to an open source project/library that provides functionality similar to what the poster is asking about.

My question is: are there any well-known websites or other sources that are open in nature and provide "best-known implementations" for common (or even not-so-common) programming problems, but not associated with any particular open source project?

As a generic example, suppose I have a need for some algorithm that does X. I post a question on SO or some other site requesting ideas, asking for suggestions on how best to implement it. One person points me to project P1, which contains some code that performs something very similar to this algorithm. Another person points me to project P2. Someone else writes some sample code and says, "maybe you could do it like this."

It seems to me, if there are all these different versions of this idea floating around out in the world, it would make sense for there to be a site, somewhat in the vein of Wikipedia, where a quasi-"official" implementation ("official" is not the right word; I'm just having trouble thinking of a better one right now) could be published and modified as improvements are developed/discovered.

I feel like I have stumbled across a few different sites like this in the past, but I'm interested to know if anyone else has found any resources like what I'm describing.

Here is something, maybe not the best implementations. But a book called Design Patterns contains what is considered by many programmers some of the best patterns to follow!

There is one page 72 in Springer book "The Future of Software Engineering" A bit confused what was a purpose to include this abstract without actual article/talk and also interested whether it exists in any format for reading ?

Design Patterns –  Past, Present & Future 
    Erich Gamma 

IBM Rational Zurich Research Lab, Switzerland 

Abstract.    Design Patterns are now a 15 year old thought experiment. 
And  today,  for  many,  Design  Patterns  have  become  part  of  the  stan- 
dard  development  lexicon.  This  talk  looks  back  to  the  origin  of  Design 
Patterns and how they evolved since their initial description. I will then 
show patterns in action in the context of the Eclipse and Jazz platforms. 
Finally,  I  will  discuss  how  the  Design  Patterns  from  the  book  can  be 
refactored towards a Design Pattern 2.0 version. 

S. Nanz (ed.), The Future of Software Engineering, 
DOI 10.1007/978-3-642-15187-3_4, © Springer-Verlag Berlin Heidelberg 2011 

The reference to Design Patterns in the abstract is a reference to a book.

Design Patterns: Elements of Reusable Object-Oriented Software

Since the book is 16 years old, you might find it at a library.

This is not a specific question about a certain piece of code and apologies if my current question is not valid on StackOverflow. With Such a big Community I am just curious to find a common approach for best practices.

It's not that I Don't know how to code the OOP way, but while my code keeps growing I am losing track and my code actually bluntly stated gets "ugly". What happens is that it takes a lot of time to rewrite my code to finally have it correct again.

Don't get me wrong. I really take time and dedication to adapt my code the best way I can. I rewrite parts that can be rewritten etc. Actually I want to avoid to rewrite and I know it takes alot of practice. Any Guidelines/Tips regarding taking on a project is highly appreciated.

I Have written Code already in OOP way, but it's small code/project based and now when I am starting to take on bigger projects I lose track.

My question is simply: Am I the only one that has this? And how to keep my coding neat all the way to the end?

Thanks in advance for any tips regarding this situation. I just want to write better and cleaner code.

In practice, you often might need to update your existing code to meet the new requirements. But if this is something you are doing on regular basis, then it is possible that your development process is not good enough.

You may lack a beforehand thinking and planning process. What do you do when you have a new development task? Do you just go on and write some code?

I use the process like this:

1) User story. Describe a user story, it often comes from the customer or users. This can be something like "I want to have a new beautiful chart of the recent data on the dashboard".

2) Requirements specification. Start asking questions and add details. You may need to create a separate document just to describe all the details - what data exactly should be shown, should it be line or bar or other kind of chart, where exactly should the chart be placed, etc, etc...

Result - a detailed requirements specification. It should be clear enough so you can give it to other developer, who should be able to continue with following steps without asking the questions.

Check also this article 10 Typical Mistakes in Specs.

3) Implementation details. Think how to implement the requirements, describe the classes structure and objects interaction, think on extensibility and flexibility, plan the unit tests for your code.

The basic idea is that you start writing and re-writing your code even before you actually write the real code. Imagine how your classes / objects will be used, try to write some tests before actually writing the code.

Here is where SOLID principles, design patterns and UML diagrams can be useful to design your code in a good way.

4) Estimation. If you was good at point (3), it will be trivial to split your implantation into small steps and estimate how much time you will need for every step, like:

  • Database migration - add new tables - 1h
  • Implement ClassA, ClassB, ClassC - 1h
  • Implement ClassD, with a special calculation algorithm - 4h
  • Unit tests - 2h
  • Testing, fixing bugs found - 20% of the above

I usually use this scheme of estimation (along with 20% for unexpected things) and it is possible to get very accurate estimations. Like for a 40 hour task it can be 1-2 hours error, it should never be something like 50% error.

5) Implementation. Here you just go on and do the task. Everything is planned, everything is absolutely clear. No thinking on design and strategy, only local decisions (like do I use for or while loop here?).

This way you minimize the amount of "surprises" during the implementation and reduce the need in re-writing the code later.

Today I got my book "Head First Design Patterns" in the mail. Pretty interesting stuff so far, however I do have a question about it's contents.

I have no Java/C# background nor do I wish to jump into those languages right now (I'm trying to focus on C++ first). In the book is said that java does not have an implementation for interfaces... This would mean that for every change to that interface, you would have to modify all subclasses that implement the interface.

How is this done in C++? What am I missing?

Ok I'll askt he obvious question:

If you want to do design patterns in C++ why would you read anything other than the original Gang of Four Design Patterns book?

And yes a C++ class with pure virtual methods is the equivalent to a Java or C# interface.

We can solve some Design Problems By implementing Factory as well as Command Pattern also. so, according to performance which is the better one?

I am not sure how you can solve some problems by both factory and command pattern. They solve completely different types of problem.

Abstract Factory handles the creation of objects in such a way that you can switch among the families of products easily and you can enforce the consistency of objects (i.e. do not mix different product families by accident). Even if there is only a single product family, it creates a flexible system where the created objects are easier to manage.

A Factory Method defers the creation of object to subclass as the base class do not have the knowledge of which concrete class to instantiate. Here the base class knows when to create the object, but don't know which concrete object to create.

And Command is used to encapsulate a request so that you handle a request just like other objects, for example pass a request as a parameter to another method/object, queue requests, reuse a request etc. It does not deal with the creation of objects.

Unless I am very very wrong, they are separate patters which attack separate problems. You can check Design Patterns by GoF and Head First Design Patters for the details about these patterns.

What’s the issue with the following, and how would I implement it better using OO principles?

My app contains a bunch of shape classes which all inherit from Shape - Circle, Rectangle, Triangle, etc. Some of these need to be displayed on the screen, in which case they need to leverage common screen logic, so there's a ScreenShape superclass which contains the common logic, and ScreenCircle, ScreenTriangle child classes.

About what you posted in response to @DOC:

@DOK the manager is not satisfied...although he gave me a go ahead with the design but still he said you should research on this.

I suppose the reason your manager is not satisfied with the current design is because it's suffering from a code smell called Parallel Inheritance Hierarchies. Basically, it describes what you're experiencing: every time a new subclass is created, you have to create its counterpart subclass in the parallel hierarchy. That would make your design more difficult to change, and thus, maintain.

Current Answers Review

I'd like to comment some things I didn't agree on the current answers. Basically you're suggested to either to:

  1. Inherit from a ScreenShape class
  2. Implement drawing logic in each subclass of Shape

I can see two issues going with option n° 1:

  • It defines Shape as an interface, so you'll have to re-implement it in each subclass (Rectangle, etc.)
  • To overcome the previous you could make ScreenShape implement it, because all kind of shapes will inherit from it. This is bad, and @Perception answer explains why.
  • Suppose you are asked now to export shapes to an XML File (this is another operation on shapes, just as is displaying them). Following this approach you'll need to implement that behavior on an XMLShape class and inherit from it, but you're already inheriting from ScreenShape. See the problem?

Option n° 2 forces you to bloat your domain model with presentation concerns, again just as @Perception said :)

Some Goals to Achieve

From the previous, we can see that:

  • You'll want your classes to change when your domain model changes, but not when the way you display shapes or export them to XML changes.
  • That leads you to the Single Responsibility Principle that states that a class should have only one reason to change.
  • We found that displaying, as well as exporting to XML (in the example I gave you) are operations you'll do on shapes, and you'll want to easily add new operations later without changing your shape classes.

Suggested Solution

First of all, get your Shape hierarchy cleaned out, and leave only things that belongs to your problem domain.

Then, you need different ways to display shapes without implementing that behavior in the Shape hierarchy. If you won't be dealing with nested shapes (shapes that contain other shapes), you can make use of a technique called Double Dispatch. It lets you dispatch a method call based on the receiver's type by encoding that information in the method name dispatched to the argument it receives like this:

public class Circle extends Shape {
    public void DisplayOn(IShapeDisplay aDisplay) {

public class Rectangle extends Shape {
    public void DisplayOn(IShapeDisplay aDisplay) {

interface IShapeDisplay {
    void DisplayCircle(Circle aCircle);
    void DisplayRectangle(Rectangle aRectangle);

Classes implementing IShapeDisplay would be responsible to display each kind of shape. The nice thing about that is you managed to clean out those pesky details from the Shape hierarchy, encapsulating them in their own class. Because of that, now you're able to change that class without modifying Shape subclasses.

Final Comments

You can read more about code smells and Parallel Inheritance Hierarchies in Martin Fowler's book: Refactoring: Improving the Design of Existing Code.

Also, you'd like to check the Design Patterns: Elements of Reusable Object-Oriented Software book if you need dealing with shape nesting: the Composite and Visitor patterns.

Hope it was helpful to you!

When i started to learn and spent 5 day learning nTier Architecture. My Boss is insisting me to learn Factory Pattern.

So some question arises in my mind..

  1. Can we apply nTier in Factory Pattern.

  2. what is benefit of Factory Pattern.

  3. What to choose between Factory Pattern and ntier Pattern

By the way i am c# coder in DOTNET

'N-tier' and 'factory' are not comparable because they apply to different levels of detail. 'N-Tier' is a high-level concept that divides your system into very coarse components: client, application server, database. 'Factory' is a low-level pattern used to structure classes within a component - that a class or method responsible only for creating other classes can be beneficial in some cases. You should not take a single pattern like 'factory' and try to apply it - you should understand a range of patterns and learn when each is useful, because there are pros and cons to every pattern. The classic reference is - now 20 years old but still worth reading as a starting point.

Which is the best tutorial to understand java design patterns? I am not new to java programming, so basics of java need not be required.

you may find these useful :

(but the last two are a bit advanced)

Joshua bloch's book Effective Java is useful even thought its not about design patterns but it's a must read.

You must read Head First Design Pattern.

Though not specific to Java, I seriously recommend you to go for, Design Patterns by Gamma, et al (a.k.a. the Gang of Four, or simply, GoF)

If you are not new to programming you have probably already used a lot of them without realizing it. Design patterns are not language specific, try not to think of them as 'Java' patterns or 'Python' patterns etc. A really good book is Design Patterns: Elements of Reusable Object-Oriented Software.

I have a manager that read objects from a repository. The objects reference other objects of a known base class, based on a stored enumeration property.

What's a good design pattern to know which manager/repository to query on the reference object? A switch block over the stored kind of the object would get out of hand very quickly.

For example:

public class Person
    public Animal Pet { get; set; }
    public AnimalKind PetKind { get; set; }

public enum AnimalKind

public abstract class Animal


public class Dog : Animal


public class Cat : Animal


public class DogManager /**/
public class CatManager /**/

public class PersonManager
    public IList<Person> GetPersons()
        var persons = Repository.GetPersons();
        // Pattern to instantiate person.Pet with the proper class???
        // The Repository is very lightweight and does not load references.

Could someone point me to the right direction? Any recomended book?

Edit: There is a table in the database for each type of Animal.

I think the factory method pattern would be useful here.

Wikipedia Link

the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created

Also, here are a couple of articles on implementing it in C#: Factory Method, Abstract Factory

Edit: Here is a well known book on design patterns - Design Patterns: Elements of Reusable Object-Oriented Software

I'm comfing from the .net world, and want a book that goes over the 'right' way of coding.

Things like dependancy injection, loosely coupling of objects, how to layout your web application properly, unit-testing etc.

Three books that are language-agnostic, but are considered 'classics':

Desing Patterns (by GoF)

Code complete (by Steve McConnell)

Patterns of Enterprise Application Architecture (by Martin Fowler)

Important: don't read them like belles-lettres - read parts of them while practicing.

Right now I'm finished with general things and I do not know what else to learn.

Am learing from

Am new in C++ maybe 2-3 month i learn this all.

I have successfully learned and tested the following:

Basics of C++

  • Structure of a program
  • Variables. Data types.
  • Constants
  • Operators
  • Basic Input/Output

Control Structures

  • Functions (I)
  • Functions (II)

Compound Data Types

  • Arrays
  • Character Sequences
  • Pointers
  • Dynamic Memory
  • Data Structures
  • Other Data Types

Object Oriented Programming

  • Classes (I)
  • Classes (II)
  • Friendship and inheritance
  • Polymorphism

Advanced Concepts

  • Templates
  • Namespaces
  • Exceptions
  • Type Casting
  • Preprocessor directives

And am now confused bcs idk what next to learn. Do you can help me what to do next to start studying to improve my knowledge. I am interested for networking.

Prev. expiriance is 5-6 year in PHP.

Realy thanks.

Next should be learning the STL library, and design patterns

I'm in the middle of making a C++ Text Adventure game and I would love some help. After a lot of research I've discovered the concept of design patterns and would love you implement one into my game. The trouble is I cannot decide which one and I still kind of a beginner C++ programmer. The farthest I have gone is creating a tokenize function that returns the inputted string as a vector of each single word in the sentence. I just need a way to parse the results of that vector and I think using a design pattern, like a said above, would be perfect. Thanks for the help! Oh, and here's the code:

// #Setup

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>

using namespace std;

// #Variables

string input = "";

// #Classes

// Inherited
class Entity {
  void setHealth(int health) {
    this->health = health;

  int getHealth() {
    return health;

  void setAD(int AD) {
    this->AD = AD;

  int getAD() {
    return AD;

  string name;

  int health = 100;
  int AD = 10;

// Players
class Player : public Entity {
  void printAD(Player dummy) {
    cout << dummy.getAD() << endl;

  void printHealth(Player dummy) {
    cout << dummy.getHealth() << endl;



// Enemies
class Enemy : public Entity {



// Items
class Item {
  Item() {
    cout << "Taken" << endl;
    cout << "\n";

  string name = "";
  bool usable = false;


// Locations
class location {
  string currentLocation;
  string north;
  string south;
  string east;
  string west;

// #Functions

// Grabs files contents and returns it into a string
string getFileContents(ifstream &file) {
  string line = "";

  if (file) {
    while (!file.eof()) {
      string tmpString = "";
      getline(file, tmpString);
      tmpString += "\n";
      line += tmpString;
    return line;
  } else {
    return "ERROR: unable to open specified text file";

// Uses getFileContents on help.txt and prints out string
void printHelp() {
  ifstream ifs("txtFiles/help.txt");
  string help = getFileContents(ifs);
  cout << help << endl;

// currently just asks for users name
void intro() {
  cout << "What is your character's name? ";

// splits user input into tokens
vector<string> tokenize(string &query) {
  vector<string> words;
  boost::split(words, query, boost::is_any_of(", !."), boost::token_compress_on);
  return words;
// puts specified string to lowercase
void toLower(string text) {
  for (int i=0;i<input.length();i++) {

// Grabs User input and stores it in vector words
vector<string> grabInput() {
  cout << "> ";
  getline(cin, input);
  vector<string> words = tokenize(input);
  return words;

// Stores grabInput() result into words vector and compares to possible commands
void checkInput() {
  do {
    vector<string> words = grabInput();
    bool answer = false;

    for (int i = 0; i < words.size(); ++i) {
      if (words[i] == "help") {
        answer = true;
      } else if (words[i] == "clear" || words[i] == "cls") {
        cout << string(36, '\n');
        answer = true;
      } else if (words[i] == "exit" || words[i] == "e") {
        cout << "good bye." << endl;
        answer = true;
      } else if(i == words.size() && answer == false) {
        cout << "Pardon me?" << endl;
        cout << "\n";

    }while(input != "exit" && input != "e");

// #Main

int main() {

  return 0;

Design patterns are a long term study that will add to the elegance and art of your projects. The most commonly referenced authority on the subject is this book by the "Gang of Four". There is also plenty of information available on the internet. The Wikipedia reference is another good place to start.

For the tokenizing and processing of commands that you are talking about, I would suggest instead looking at how compilers of programming languages are built. I'm not finding a decent online reference for you, but the main components to investigate are:

  1. The Lexer: Identifies the keywords that carry specific meaning in the language (or command, or script). It also identifies the other chunks which might represent variables or strings or whatever, depending on the context.
  2. The Parser: Processes the tokens identified by the lexer within their context to determine the validity of the statement, and, if valid, interpret the statement.

There are other concepts, details and subtleties to explore, but these are the main ideas to explore which I think will lead you down the right road.

Realated tags