Head First Design Patterns

Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates

Mentioned 140

Provides design patterns to help with software development using the Java programming language.

More on Amazon.com

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

TITLE Cover

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.

K&R

@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.

http://www.amazon.com/Memory-Programming-Concept-C/dp/0521520436

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

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

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

The beauty of the book is the copyright year.

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

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

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

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

Discrete Mathematics For Computer Scientists

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

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

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

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

Solid Code Optimizing the Software Development Life Cycle

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

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

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

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

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

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

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

alt text

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

to get advanced in prolog i like these two books:

The Art of Prolog

The Craft of Prolog

really opens the mind for logic programming and recursion schemes.

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

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

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

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

alt text

The Back of the Napkin, by Dan Roam.

The Back of the Napkin

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

Agile Software Development by Alistair Cockburn

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

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

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

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

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

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

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

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

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

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

Head First Design Patterns

97 Things Every Programmer Should Know

alt text

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

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

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

I hope the second edition will be released soon!

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

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

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

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

I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutions and also with the semantics of the language that allows such a natural flow from thoughts to workable code.

What I would like to know is your answer to a kind of question I have seldom seen in this or other forums. This question seems central to me for anyone on the path to Python improvement but who wonders what his next steps should be.

Let me sum up what I do NOT want to ask first ;)

  • I don't want to know how to QUICKLY learn Python
  • Nor do I want to find out the best way to get acquainted with the language
  • Finally, I don't want to know a 'one trick that does it all' approach.

What I do want to know your opinion about, is:

What are the steps YOU would recommend to a Python journeyman, from apprenticeship to guru status (feel free to stop wherever your expertise dictates it), in order that one IMPROVES CONSTANTLY, becoming a better and better Python coder, one step at a time. Some of the people on SO almost seem worthy of worship for their Python prowess, please enlighten us :)

The kind of answers I would enjoy (but feel free to surprise the readership :P ), is formatted more or less like this:

  • Read this (eg: python tutorial), pay attention to that kind of details
  • Code for so manytime/problems/lines of code
  • Then, read this (eg: this or that book), but this time, pay attention to this
  • Tackle a few real-life problems
  • Then, proceed to reading Y.
  • Be sure to grasp these concepts
  • Code for X time
  • Come back to such and such basics or move further to...
  • (you get the point :)

I really care about knowing your opinion on what exactly one should pay attention to, at various stages, in order to progress CONSTANTLY (with due efforts, of course). If you come from a specific field of expertise, discuss the path you see as appropriate in this field.

EDIT: Thanks to your great input, I'm back on the Python improvement track! I really appreciate!

I thought the process of Python mastery went something like:

  1. Discover list comprehensions
  2. Discover generators
  3. Incorporate map, reduce, filter, iter, range, xrange often into your code
  4. Discover Decorators
  5. Write recursive functions, a lot
  6. Discover itertools and functools
  7. Read Real World Haskell (read free online)
  8. Rewrite all your old Python code with tons of higher order functions, recursion, and whatnot.
  9. Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as a dictionary plus some functions. Embrace functional programming.
  10. Rediscover the Strategy pattern and then all those things from imperative code you tried so hard to forget after Haskell.
  11. Find a balance.

I was looking at the Proxy Pattern, and to me it seems an awful lot like the Decorator, Adapter, and Bridge patterns. Am I misunderstanding something? What's the difference? Why would I use the Proxy pattern versus the others? How have you used them in the past in real world projects?

This is quote from Head First Design Patterns

Definitions belongs to book. Examples belongs to me.

Decorator - Doesn’t alter the interface, but adds responsibility. Assume you have a car interface, when you implement this for different model of the car (s, sv, sl) you may need to add more responsibility for some models. Like has sunroof, airbag etc..

Adapter - Converts one interface to another. You have a car interface and you would like it to act like jeep. So you take the car, modify it and turn into a jeep. Since it is not a real jeep. But acts like a jeep.

Facade - Makes an interface simpler. Assume you have car, airplane, ship interfaces. Actually all you need is a class which sends people from one location to another. You want facade to decide what vehicle to use. Then you collect all those interface references under 1 umbrella and let it decide/delegate to keep it simple.

Head First: "A facade not only simplifies an interface, it decouples a client from a subsystem of components. Facades and adapters may wrap multiple classes, but a facade’s intent is to simplify, while an adapter’s is to convert the interface to something different."

There's a great deal of overlap in many of the GoF patterns. They're all built on the power of polymorphism and sometimes only really differ in intent. (strategy vs. state)

My understanding of patterns increased 100 fold after reading Head First Design Patterns.

I highly recommend it!

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.

Books
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.

C

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.
Books
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.

C++

Online Tutorials
The tutorial on cplusplus.com 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/.

Books
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

Books
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.

Java

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?
Books
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

Python

Online Tutorials
Python.org - 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.

Perl

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.
Books
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.

Ruby

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.
Books
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.

PHP

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.

JavaScript

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.

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

C#

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#
Books
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth

ocaml

Books
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

Haskell

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

LISP/Scheme

Books
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.

Haskell:

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.

C++

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#

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:

For SQL/MySQL:

  • 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'm working on a large project (for me) which will have many classes and will need to be extensible, but I'm not sure how to plan out my program and how the classes need to interact.

I took an OOD course a few semesters back and learned a lot from it; like writing UML, and translating requirements documents into objects and classes. We learned sequence diagrams too but somehow I missed the lecture or something, they didn't really stick with me.

With previous projects I've tried using methods I learned from the course but usually end up with code that as soon as I can say "yeah that looks something like what I had in mind" i have no desire to dig through the muck to add new features.

I've got a copy of Steve McConnell's Code Complete which I continually hear is amazing, here and elsewhere. I read the chapter on design and didn't seem to come out with the information I'm looking for. I know he says that it's not a cut and dried process, that it's mostly based on heuristics, but I can't seem to take all his information and apply it to my projects.

So what are things you do during the high level design phase (before you begin programming) to determine what are the classes you need (especially ones not based on any 'real world objects') and how will they interact with each other?

Specifically I'm interested in what are the methods you use? What is the process you follow that usually yeilds a good, clean design that will closely represent the final product?

You asked question that lots of authors use to write a book. There is number of methodologies and you should pick one that seems "prettiest" to you.
I can recommend book "Domain Driven Design" by Eric Evans. Also, check site dddcommunity.org.

Learn design patterns. It has been my personal revolution the past two years regarding OOP. Get a book. I would recommend you this one:

Head First Design Patterns

It is in Java but it can be extensible to any language.

Note: Questions are at the end of the post.

I have read the other stackoverflow threads regarding Abstract Factory vs Factory Method. I understand the intent of each pattern. However, I am not clear on the definition.

Factory Method defines an interface for creating an object, but lets subclasses decide which of those to instantiate. A factory method lets classes defer instantiation to subclasses.

By contrast, an Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

-John Feminella

The Abstract Factory looks very similar to the Factory Method. I have drawn a few UML classes to illustrate my point.

Note:

  • The diagram are from www.yuml.com so they are not perfectly oriented. But its a free service :).
  • The diagrams may not be perfect. I am still learning the GoF design patterns.

Factory Method:

Factory Method

Abstract Factory (only 1 member):

Abstract Factory (only 1 member)

Abstract Factory (more members):

alt text

Questions:

  1. If the Abstract Factory has only one creator and one product, is it still the Abstract Factory pattern? (an interface for creating familes)
  2. Can the Factory Method concrete creator be created from an Interface or does it have to be from a class? (classes defer instantiations to subclasses)
  3. If the Abstract Factory can have only one creator and one product, is the only difference between the Abstract Factory and the Factory Method that the creator for the former is an Interface and the creator for the latter is a Class?

Hope this helps. It describes the various types of factories. I used Head First Design Patterns as my reference. I used yuml.me to diagram.

Static Factory

Is a class with a Static Method to product various sub types of Product.

Static Factory

Simple Factory

Is a class that can produce various sub types of Product. (It is better than the Static Factory. When new types are added the base Product class does not need to be changed only the Simple Factory Class)

Simple Factoryt

Factory Method

Contains one method to produce one type of product related to its type. (It is better than a Simple Factory because the type is deferred to a sub-class.)

Factory Method

Abstract Factory

Produces a Family of Types that are related. It is noticeably different than a Factory Method as it has more than one method of types it produces. (This is complicated refer to next diagram for better real-life example).

Abstract Factory

Example From The .NET Framework

DbFactoriesProvider is a Simple Factory as it has no sub-types. The DbFactoryProvider is an abstract factory as it can create various related database objects such as connection and command objects.

Abstract Factory From .NET Framework

A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

A complement to Spoike's post, Refactoring to Patterns is a good read.

It is simple ... avoid Design Patterns that are not clear to you or those that you do not feel comfortable in.

To name some ...

there are some unpractical patterns, like e.g.:

  • Interpreter
  • Flyweight

there are also some harder to grasp, like e.g.:

  • Abstract Factory - Full abstract factory pattern with families of created objects is not such a breeze as it seems to be
  • Bridge - Can get too abstract, if abstraction and implementation are divided to subtrees, but is very usable pattern in some cases
  • Visitor - Double dispatch mechanism understanding is really a MUST

and there are some patterns that look terribly simple, but are not so clear choice because of various reasons related to their principle or implementation:

  • Singleton - not really totally bad pattern, just TOO overused (often there, where it is not suitable)
  • Observer - great pattern ... just makes code much harder to read and debug
  • Prototype - trades compiler checks for dynamism (which can be good or bad ... depends)
  • Chain of responsibility - too often just forcedly/artificially pushed into the design

For those "unpractical ones", one should really think about before using them, because there is usually more elegant solution somewhere.

For the "harder to grasp" ones ... they are really great help, when they are used at suitable places and when they are implemented well ... but they are nightmare, when improperly used.

Now, what's next ...

We need to implement a simple state machine in C.
Is a standard switch statement the best way to go?
We have a current state (state) and a trigger for the transition.


switch(state)
{
  case STATE_1:
     state = DoState1(transition);
     break;
  case STATE_2:
     state = DoState2(transition);
     break;
}
...
DoState2(int transition)
{
   // Do State Work
   ...
   if(transition == FROM_STATE_2) {
     // New state when doing STATE 2 -> STATE 2
   }
   if(transition == FROM_STATE_1) {
    // New State when moving STATE 1 -> STATE 2
   }
   return new_state;
}

Is there a better way for simple state machines

EDIT: For C++, I think the Boost Statechart library might be the way to go. However, it does not help with C. Lets concentrate on the C use case.

This article is a good one for the state pattern (though it is C++, not specifically C).

If you can put your hands on the book "Head First Design Patterns", the explanation and example are very clear.

There is a book titled Practical Statecharts in C/C++. However, it is way too heavyweight for what we need.

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) http://dofactory.com/Patterns/Patterns.aspx (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.

I've been reading about the OCP principal and how to use the strategy pattern to accomplish this.

I was going to try and explain this to a couple of people, but the only example I can think of is using different validation classes based on what status an "order" is.

I've read a couple of articles online, but these don't usually describe a real like reason to use the strategy, like generating reports/bills/validation etc...

Are there any real world examples where you think a strategy pattern is common?

Are you sure that the status of an "order" is not a State pattern? I have a hunch that an order will not be handled differently depending on its status.

Take for example the method Ship on the Order:

order.Ship();
  • If the shipping method varies in function of its status, then you've got a strategy pattern.
  • If however the Ship() method succeeds only when the order has been paid, and the order has not been shipped yet, you've got a state pattern.

The best example of the state pattern (and other patterns) I found was in the book "Head First Design Patterns", which is amazing. A close second will be David Cumps' blogging series of patterns.

One of the design patterns which I find most difficult to get a real grasp of in "real SWING life" is the MVC pattern. I've been through quite a few of the posts at this site which discuss the pattern, but I still do not feel that i have a clear understanding of how to take advantage of the pattern in my (Java SWING) application.

Let's say that I have a JFrame which contains a table, a couple of text fields and a few buttons. I would probably use a TableModel to "bridge" the JTable with an underlying data model. However, all functions responsible for clearing fields, validating fields, locking fields along with button actions would usually go directly in the JFrame. However, doesn't that mix the Controller and View of the pattern?

As far as I can see, I manage to get the MVC pattern "correctly" implemented when looking at the JTable (and the model), but things get muddy when I look at the entire JFrame as a whole.

I'd really like to hear how others go about with regard to this. How do you go about when you need to display a table, a couple of fields and some buttons to a user (using the MVC pattern)?

A book i'd highly recommend to you for MVC in swing would be Head First Design Patterns by Freeman and Freeman. They have a highly comprehensive explanation of MVC.

Brief Summary

  1. You’re the user — you interact with the view. The controller takes your actions and interprets them. If you click on a button, it’s the controller’s job to figure out what that means and how the model should be manipulated based on that action.
  2. The controller asks the model to change its state. When the controller receives an action from the view, it may need to tell the view to change as a result. For example, the controller could enable or disable certain buttons or menu items in the interface.
  3. The controller may also ask the view to change. When something changes in the model, based either on some action you took (like clicking a button) or some other internal change (like the next song in the playlist has started), the model notifies the view that its state has changed.
  4. The model notifies the view when its state has changed. When something changes in the model, based either on some action you took (like clicking a button) or some other internal change (like the next song in the playlist has started), the model notifies the view that its state has changed.
  5. The view asks the model for state. The view gets the state it displays directly from the model. For instance, when the model notifies the view that a new song has started playing, the view requests the song name from the model and displays it. The view might also ask the model for state as the result of the controller requesting some change in the view.

enter image description here Source (In case you're wondering what a "creamy controller" is, think of an Oreo cookie, with the controller being the creamy center, the view being the top biscuit and the model being the bottom biscuit.)

Um, in case you're interested, you could download a fairly entertaining song about the MVC pattern from here!

One issue you may face with Swing programming involves amalgamating the SwingWorker and EventDispatch thread with the MVC pattern. Depending on your program, your view or controller might have to extend the SwingWorker and override the doInBackground() method where resource intensive logic is placed. This can be easily fused with the typical MVC pattern, and is typical of Swing applications.

EDIT #1:

Additionally, it is important to consider MVC as a sort of composite of various patterns. For example, your model could be implemented using the Observer pattern (requiring the View to be registered as an observer to the model) while your controller might use the Strategy pattern.

EDIT #2:

I would additionally like to answer specifically your question. You should display your table buttons, etc in the View, which would obviously implement an ActionListener. In your actionPerformed() method, you detect the event and send it to a related method in the controller (remember- the view holds a reference to the controller). So when a button is clicked, the event is detected by the view, sent to the controller's method, the controller might directly ask the view to disable the button or something. Next, the controller will interact with and modify the model (which will mostly have getter and setter methods, and some other ones to register and notify observers and so on). As soon as the model is modified, it will call an update on registered observers (this will be the view in your case). Hence, the view will now update itself.

I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.

I think you need to get a good understand of design patterns so see there power.

Check out Head First Design Patterns

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 have been using factory method creation pattern for awhile now. I was just recently told that this:

public static class ScheduleTypeFactory
{
    public static IScheduleItem GetScheduleItem(ScheduleTypeEnum scheduleType)
    {
        IScheduleItem scheduleItem = null;

        switch (scheduleType)
        {
            case ScheduleTypeEnum.CableOnDemandScheduleTypeID:
                {
                    scheduleItem = new VODScheduleItem();
                    break;
                }
            case ScheduleTypeEnum.BroadbandScheduleTypeID:
                {
                    scheduleItem = new VODScheduleItem();
                    break;
                }
            case ScheduleTypeEnum.LinearCableScheduleTypeID:
                {
                    scheduleItem = new LinearScheduleItem();
                    break;
                }
            case ScheduleTypeEnum.MobileLinearScheduleTypeID:
                {
                    scheduleItem = new LinearScheduleItem();
                    break;
                }
        }

        return scheduleItem;
    }
}

is not a factory method creation pattern by my "Tech" lead without telling me why or giving me her interpretation. I kindly asked for an explanation and she told me she didn't have time. I was told to just rename it. If I am wrong, then I will no doubt accept that I have implemented this incorrectly for years. Is this how YOU would implement the factory method creation pattern? Thanks in advance.

Your code fragment is what in Head First Design Patterns is called "The Simple Factory" (p. 117).
The main difference to the Factory Method Pattern is the ConcreteCreator (compare the diagram in the upper right corner), which is a simple class in your case.
In the "real pattern" the factory class is abstract with an abstract factory class. So, there is one more abstraction level. However, for many use cases, your Simple Factory is enough.

Simple Factory Simple Factory Factory Method Pattern Factory Method Pattern

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.

In the 2009 Wikipedia entry for the Strategy Pattern, there's a example written in PHP.

Most other code samples do something like:

a = Context.new(StrategyA.new)
a.execute #=> Doing the task the normal way

b = Context.new(StrategyB.new)
b.execute #=> Doing the task alternatively

c = Context.new(StrategyC.new)
c.execute #=> Doing the task even more alternative

In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.

Update: Can it be shorter using first-class functions in Python?

I've tried to convert the 'Duck' example from the 1st chapter (covering Strategy Pattern) of Head First Design Pattern in Python:

class FlyWithRocket():
    def __init__(self):
        pass
    def fly(self):
        print 'FLying with rocket'

class FlyWithWings():
    def __init__(self):
        pass
    def fly(self):
        print 'FLying with wings'

class CantFly():
    def __init__(self):
        pass
    def fly(self):
        print 'I Cant fly'

class SuperDuck:
    def __init__(self):
        pass
    def setFlyingBehaviour(self, fly_obj):
        self.fly_obj = fly_obj
    def perform_fly(self):
        self.fly_obj.fly()

if __name__ == '__main__':
    duck = SuperDuck()
    fly_behaviour = FlyWithRocket()
    #fly_behaviour = FlyWithWings()
    duck.setFlyingBehaviour(fly_behaviour)
    duck.perform_fly()

(In the context of .NET for what its worth)

I tend to not use inheritance and rarely use interfaces. I came across someone who thinks interfaces are the best thing since spit. He uses them everywhere. I don't understand this and hence the questions that follow. I just want a check on my understanding of interfaces.

If you are using interfaces everywhere, I'm assuming you can predict the future, your app requirements are nailed down and nothing will ever change in your app. For me, during early development especially, interfaces become a drag. The app is very dynamic through its life. If you need to subtract or add members to the interface, lots of stuff will break. The guy above says he creates another interface to handle the new member(s). Nothing breaks.

Isn't that composition? Why not use composition without interfaces? More flexible.

How does he handle the case where a member must be subtracted from the interface? Basically he doesn't. Things just break and that is great because now you can see all of the affected areas and fix them. Instead of figuring out more elegantly where all of the related code paths are, we should just rip out parts of classes through brute force?

I think of a software application as a graph. A complete graph is the worst case, having n(n-1)/2. This means every class talks to every class. A confusing spider web. n-1 is the best, in which their is a strict hierarchy of communication. Adding another interface just to compensate for a new needed member adds a vertici to the graph, which means more edges and a stronger realization of the n(n-1)/2 equation. Composition without interfaces is more like mixins. Only select classes use particular methods. With an interface, all classes are forced to use members, even if they don't need them. The composition/mixin approach doesn't add new unneeded edges.

If you want to understand when to use interfaces, and what is their use, I think you should take a look at the book: Head First Desing Patterns.

This is the book that really helped me understand what is so cool about interfaces.

Before reading this book, I knew what an interface was, but I had absolutely no idea about when should I use them.

Recently I heard that there are 9 rules for OOP(Java). I know only four as Abstraction, Polymorphism, Inheritance and Encapsulation. Are there any more rules for OOP?

Seems like what you're looking for are the Principles of Object-Oriented Design.

Summarized from Agile Software Development Principles, Patterns, and Practices. These principles are the hard-won product of decades of experience in software engineering. They are not the product of a single mind, but they represent the integration and writings of a large number of software developers and researchers. Although they are presented here as principles of object-oriented design, they are really special cases of long-standing principles of software engineering.

SRP The Single Responsibility Principle A class should have only one reason to change.

OCP The Open-Closed Principle Software entities (classes, packages, methods, etc.) should be open for extension, but closed for modification.

LSP The Liskov Substition Principle Subtypes must be substitutable for their base types.

DIP The Dependency Inversion Principle Abstractions should not depend upon details. Details should depend upons abstractions.

ISP The Interface Segregation Principle Clients shold not be forced to depend upon methods that they do not use. Interfaces belong to clients, not to hierarchies.

REP The Release-Reuse Equivalency Principle The granule of reuse is the granule of release.

CCP The Common Closure Principle The classes in a package should be closed together against the same kinds of changes. A change that affects a closed package affects all the classes in that package and no other packages.

CRP The Common Reuse Principle The classes in a package are reused together. If you reuse one of the classes in a package, you reuse them all.

ADP The Acylcic Dependencies Principle Allow no cycles in the dependency graph.

SDP The Stable Dependencies Principle Depend in the direction of stability.

SAP The Stable Abstractions Principle A package should be as abstract as it is stable.

These OO principles are straight from Head First Design Patterns:

  • Encapsulate what Varies
  • Program to an Interface, rather than an Implementation
  • Favour Composition over Inheritance
  • A Class should have only one reason to Change (Single Responsibility Principle)
  • Sub-Types must be substitutable for their Base (Liskov Substitition Principle)
  • Classes shoule be Open for extension, but Closed for Modification (Open-Closed Principle)

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 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

and

  • 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.

Currently, my level of understanding is below all the coding examples on the web about the Observer Pattern. I understand it simply as being almost a subscription that updates all other events when a change is made that the delegate registers. However, I'm very unstable in my true comprehension of the benefits and uses. I've done some googling, but most are above my level of understanding.

I'm trying to implement this pattern with my current homework assignment, and to truly make sense on my project need a better understanding of the pattern itself and perhaps an example to see what its use. I don't want to force this pattern into something just to submit, I need to understand the purpose and develop my methods accordingly so that it actually serves a good purpose. My text doesn't really go into it, just mentions it in one sentence. MSDN was hard for me to understand, as I'm a beginner on this, and it seems more of an advanced topic.

How would you describe this Observer pattern and its uses in C# to a beginner? For an example, please keep code very simple so I can understand the purpose more than complex code snippets. I'm trying to use it effectively with some simple textbox string manipulations and using delegates for my assignment, so a pointer would help!

Check out "Head First: Design Patterns" for some really, smack-your-forehead easy to follow descriptions of the major patterns.

For Observer it is important to understand that it describes a one-to-many relationship and uses a subscription model for telling other classes when there has been a change. RSS, Atom, and Twitter work along these lines.

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 not that good at programming. I finished my masters degree in electronics. I want to learn C#, the .NET Framework, and SQL. How much time do you think it would take (if I have 5 hours a day to devote to it)? Also, what order do I learn them in? I have Visual Web Developer 2008, is that enough to begin?

Copied from a new question by the same user:
I should have specified that I wish to make a career out .NET Development. I'd like to give myself 2 months to get the 'basics' down. As a developer, what is expected out of you in IT companies? What skillset do they require and what are the responsibilities as a junior or mid-level developer? I don't have any industry experience, will I be able to get a feel of the job duties while at home?

All "relativity" aside, not fast. Based on the fact that you said you never programmed before...to become a basic programmer, a few years.

And to become a good to outstanding (using design patterns and industry recognized standards that relate to common standards as defined by ISO/IEC 9126 Standard such as testability, maintainability, etc.) programmer, it takes years of experience and coding often.. you do not become "Sr." or an "Architect" overnight and the same thing is true for a mid-level developer who doesn't code slop.

It's always a process where you improve. So learning is relative. But to learn the basics, seems simple until you start to design classes and interfaces. And even Leads stumble on the basics..doing things wrong. Everyone does. There is so much to be aware of.

If you're just going to be adding features (using classes your Lead or Architect has stubbed out for the team) and not really adding new classes, etc. it's easier....but you should take care in coding using standards and you still have to know complex areas of OOP. But that's not really OOP. When you start to creating classes, interfaces and knowing about inheritance, heap, references, etc. yada yada...and REALLY understanding it takes time no matter how smart you are or think you may be.

So, for a new programmer. Not easy. Be prepared to code a lot. And if you are not, find a job where you are. It's all about coding as much possible so you can get better.

Read these books FIRST. Do not dive into any others out there because they are not geared toward teaching you the language in a way you can get up to speed fast:

http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=pd_bbs_sr_4?ie=UTF8&s=books&qid=1231280335&sr=8-4

http://www.amazon.com/Head-First-SQL-Brain-Learners/dp/0596526849/ref=pd_bbs_sr_7?ie=UTF8&s=books&qid=1231280335&sr=8-7

http://www.amazon.com/Head-First-C-Brain-Friendly-Guides/dp/0596514824/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1231280393&sr=8-1

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=pd_bbs_sr_3?ie=UTF8&s=books&qid=1231280393&sr=8-3

they will get you the fasted jump start into understanding, better than any books out there.

Also for these lame type of responses, ignore them:

"Then again, plenty of people (most normal people, non-programmers) never learn those subjects, so if you're like "most" people then the answer would be "it would take forever" or "it will never happen"."

Those come from developers (typically leads) who have some Ego trip that DON'T want you to learn. Everyone learns differently and at different paces and eventually you will become "fast". I get very tired of hearing Sr. developers say statements like this when their sh** also stinks many times no matter how good they are. Instead they should be helping the team to succeed and learn as long as their team is working hard to keep abreast and doing what they can on their own as well (not leachers).

Make sure you try to get a Jr. Level Developer position first...

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.

Anyone please suggest a good design and architecture book for .Net.

Is there any book I can refer to which has case studies, examples, etc. so that I can update my knowledge well in this field?

In case it's not available for .Net, please suggest in Java also.

Thanks in advance Swapna MC

Here's are a few good enterprise architecture books (based on Java, but the general concepts still apply):

A few of these patterns are a little old, but still useful to know.

If you're interested in WCF for a service-oriented architecture:

Or for framework design:

I would recommend this book: .NET: Architecting Applications for the Enterprise

Not a .net book, but the classic book here is Patterns of Enterprise Application Architecture

I enjoyed Head First Design Patterns:

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124

More design than architecture (obviously) but it makes heavy use of examples. Examples are in Java, btw.

Architectural approaches can vary greatly depending on what you're trying to build. I.e.- Architecting a specific software's internal's, or architecting a distributed system, etc.

For a given software program's internals, I like Patterns of Enterprise Application Architecture as a good reference.

I have also used the SEDA architectural style for some high throughput event-driven applications. The SEDA homepage has the original paper and references to other projects using this style. You might have heard of the Java Open Source projects: MULE and Apache Camel.

Also check out Enterprise Integration Patterns, which is a great companion book to PoEAA. This one pretty much helps you architect the interconnection between distributed systems. Lots of tools in this area... from XMPP to AMQP, to MULE, to JMS, etc.

And I have to suggest reviewing the REST Architectural Style since it is important in today's web software. There is a lot of material about REST, but primarily read (and reread) Roy Fielding's dissertation.

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 a .NET windows app, I have a class named EmployeeManager. On instantiation, this class loads employees into a List from the database that haven't completed registration. I'd like to use EmployeeManager in unit test. However, I don't want to involve the database.

From what I understand about this scenario, I need an IEmployeeManager interface, which is only used for testing purposes. This doesn't seem right since the interface has no other use. However, it will allow me to create some EmployeeManager test class that loads employees without involving the database. This way, I can assign values that would have otherwise come from the database.

Is the above correct and do I need to Mock it? Mocking (Moq framework) seems to use lots of code just to do simple things such as assigning a property. I don't get the point. Why mock when I can just create a simple test class from IEmployeeManager that will provide what I need?

By making your classes implement Interfaces you are not only making them more testable, you're making your application more flexible and maintainable. When you say "This doesn't seem right since the interface has no other use", is flawed since it allows you to loosely couple your classes.

If I could suggest a couple of books Head First Design Patterns and Head First Software Development will do a much better job of explaining the concepts then I could in a SO answer.

If you don't want to use a mocking framework like Moq, it's simple enough to roll your own mock/stubs, here is a quick blog post on it Rolling your own Mock Objects

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'm trying to get into OOP lately and I'm having trouble with SOLID principles and Design Patterns. I see why people use them and I really want to use them too, but I can't wrap my head around developing my classes to the specifications. I would really appreciate anything that would help my understanding of such. Thanks.

I've taken a class on college that spent two weeks around design patters, and read the Gang of Four book to no avail. Understanding what each pattern served for and how to use them to fit my problems was very hard for me, a developer that didn't have much experience on OO programing.

The book that really made it click for me was Head First Design Patterns. It starts by showing a problem, different approaches the developers considered, and then how they ended up using a design pattern in order to fix it. It uses a very simple language and keeps the book very engaging.

Design patterns end up being a way to describe a solution but you don't have to adapt your classes to the solution. Think of them more as a guide that suggest a good solution to a wide array of problems.

Let's talk about solid:

  1. Single responsibility. A class should have only one responsibility. That means that for example, a Person class should only worry about the domain problem regarding the person itself, and not for example, its persistence on the database. For that, you may want to use a PersonDAO for example. A Person class may want to keep its responsibilities the shortest it can. If a class is using too many external dependencies (that is, other classes), that's a symptom that the class is having too many responsibilities. This problem often comes when developers try to model the real world using objects and take it too far. Loosely coupled applications often are not very easy to navigate and do not exactly model how the real world works.
  2. Open Closed. Classes should be extendible, but not modificable. That means that adding a new field to a class is fine, but changing existing things are not. Other components on the program may depend on said field.
  3. Liskov substitution. A class that expects an object of type animal should work if a subclass dog and a subclass cat are passed. That means that Animal should NOT have a method called bark for example, since subclasses of type cat won't be able to bark. Classes that use the Animal class, also shouldn't depend on methods that belong to a class Dog. Don't do things like "If this animal is a dog, then (casts animal to dog) bark. If animal is a cat then (casts animal to cat) meow".
  4. Interface segregation principle. Keep your interfaces the smallest you can. A teacher that also is a student should implement both the IStudent and ITeacher interfaces, instead of a single big interface called IStudentAndTeacher.
  5. Dependency inversion principle. Objects should not instantiate their dependencies, but they should be passed to them. For example, a Car that has an Engine object inside should not do engine = new DieselEngine(), but rather said engine should be passed to it on the constructor. This way the car class will not be coupled to the DieselEngine class.

I've been programming a software version of a board game. Thus far I have written the classes which will correspond to physical objects on the game board. I'm well into writing the program logic, however I've found that many of the logic classes require access to the same objects.

At first I was passing the appropriate objects to methods as they were called, but this was getting very tedious, particularly when the methods required many objects to perform their tasks. To solve this, I created a class which initialises and stores all the objects I need. This allows me to access an object from any class by calling Assets.dice(), for example.

But now that I've thought about it, this doesn't seem right. This is why I'm here, I fear that I've created some sort of god class. Is this fear unfounded, or have I created a recipe for disaster?

It sounds like you're asking about a general philosophy of Object-Oriented Programming. In general, you'll find that modelling real-world objects to classes doesn't always make the best sense for your code.

One guideline that's helped me figure this stuff out is a dialogue between two anthropomorphic classes (if someone knows the original source of this quote, I'd appreciate a link!):

Class A says to Class B: "Give me the value of x."

Class B: "Why do you want the value of x?"

Class A: "So I can flange it."

Class B: "Ask me, and I'll flange it for you."

This helps drive home the point that a class is meant to encapsulate the data and perform manipulations on it. In general, this is a parable that's helped me organize my code better.

Another thing you may want to look at are some common Object-Oriented Design Patterns. Something like game dice might make more sense as a Singleton, since you don't need more than one instance of it.

If you'd like a good introduction to Design Patterns, I'd recommend picking up the excellent Head First Design Patterns book.

When doing large projects my code seems to get all over the place. How do you guys organize your code?

You should be using a design pattern; consider starting with MVC.

Strictly following a design pattern will improve the readability of your code base immensely (among other benefits).

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'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?
Thanks.

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"

Enjoy!

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.

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: http://martinfowler.com/articles.html. 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.

Thanks for your valuable time.

I want to learn c++ design patterns. I searched on web but I was not getting documents which gives me better details about design patterns. I was getting good details but those were in different URL's, I required all the information in one place only so that it will be better to know what all things are there under c++ design patterns.

Below are my necessary things while learning design patterns :

  • Why we need c++ design patterns
  • What is design patterns
  • How they are categorized ( I mean overview we can say)
  • Good approach while implementation of these patterns
  • Pros and cons of design patterns
  • New features in design patterns.

Please folks suggest me good stuff which consist of above mentioned points. Also suggest me , is there any good forum available for design patterns.

Thanks for your suggestions !!!

-Pravin

Why is java.io.OutputStream not modeled as an interface instead of abstract class?

An interface can prove useful for example unit testing, I thought.

In fact, java.io.OutputStream (the same to java.io.InputStream) uses the Decorator pattern. Relate to the question, here is the response taken from (Head First Design Patterns page 93):

The point is that it’s vital that the decorators have the same type as the objects they are going to decorate. So here we’re using inheritance to achieve the type matching, but we aren’t using inheritance to get behavior.

So that's why we prefer Inheritance (AbstracClass) over Interface (Polymophism) in this case. But note that, in most of the other cases, the principe is inverse: "Favor composition (interface) over inheritance (abstract class)".

enter image description here

A friend of mine is talking about these design techniques regarding state transitions of an object (he's a Java guru, btw), performed without having a boolean myState member, but rather declaring the myState member as an object that implements the same interface of the "owner" one.

Ok, I've been too much cryptic, so you can find the discussion here, with code samples.

Personally, I'm excited with the approach, as my friend explained me the philosophy behind it; I also think it is pretty coherent, from a design perspective. My concerns, by the way, are mainly about performance and memory usage, as maybe compile-time and run-time optimizations enter the game. Since I don't know JIT compiler and JVM internals, I'm curious to have a wider opinion.

What do you think about?

It sounds like you're asking whether there's a "concretely useful" benefit to using the state design pattern, to which I'd say definitely yes, particularly if your app actually relies heavily on the "state" of its objects. A popular canonical example is that of the video player, which is always in one state, and can only transition into different states depending on the state it's currently in (e.g., it can't stop if it's already stopped, but it can play, and it can rewind, and so on).

While that particular example can be managed relatively easily with a handful of if/else/switch-type conditions (if (isStopped()), play(), etc.) because there aren't that many states to deal with, when states or their transition rules start to become more numerous or complicated, the state pattern absolutely becomes quite valuable, as without it, your code tends to accumulate elseifs like crazy, and things become less and less readable and manageable over time.

So yes, in general, if you find your objects' behaviors varying according to their states (if isStopped() play() / elseif isPlaying() stop() / elseif (isBroken() fix()), etc.), then yes, do consider using the State pattern. It's a bit more work up front, but generally well worth the effort, and done right I doubt you'd notice any significant overhead simply for the using of it.

Head First Design Patterns offers a great description of its hows and whys, too -- I highly recommend picking up that book to pretty much anyone writing object-oriented code.

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?

Cheers

Try this book, it is funny and gives you not only how to implement the pattern, also when to do it.

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124

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 got an assignment to make a Desktop application using C#. It has to be done using MVC design pattern, but I can't find any tutorial which can show how to do it with Desktop based application. All the tutorials which I can find show how to do it for web (asp.net).

So I was wondering if someone can suggest me a book or online tutorial which is doing this?

There are a few different avenues you might look at.

  • You might consider implementing the pattern yourself. In order to implement the pattern from scratch, you really would need to understand what MVC is trying to solve.
    • Consider reading about Design Patterns. I know that Head First Design Patterns includes an introduction to the MVC pattern.
    • You may consider exploring ASP.NET MVC. Even though it is for the web and not the desktop, understanding what problems ASP.NET MVC is solving by using the MVC pattern will help you to understand how to best implement a solution for the desktop.
  • See if anyone has implemented MVC with WinForms
  • You also might consider looking for suggestions on implementing the MVC Pattern with WPF or Silverlight.
    • Although the common buzzword pattern surrounding WPF and Silverlight is MVVM (Model-View-ViewModel), some people still prefer to use an MVC implementation with these technologies.
    • In fact, if you consciously create View Models to accompany your views even when using the MVC pattern, you've essentially an "M-V-VM-C" pattern that ensures that your views only know about data from the model that pertains to that particular view.

I'm trying to nut out a highlevel tech spec for a game I'm tinkering with as a personal project. It's a turn based adventure game that's probably closest to Archon in terms of what I'm trying to do.

What I'm having trouble with is conceptualising the best way to develop a combat system that I can implement simply at first, but that will allow expansion and complexity to be added in the future.

Specifically I'm having trouble trying to figure out how to handle combat special effects, that is, bonuses or negatives that may be applied or removed by an actor, an item or an environment.

  • Do I have the actor handle all effects that are in play for/against them should the game itself check each weapon, armour, actor and location each time it tries to make a decisive roll.
  • Are effects handled in individual objects or is there an 'effect' object or a bit of both?

I may well have not explained myself at all well here, and I'm more than happy to try and expand the question if my request is simply too broad and airy. But my intial thinking is that smarter people than me have spent the time and effort in figuring things like this out and frankly I don't want to taint the conversation with the cul-de-sac of my own stupidity too early.

The language in question is javascript, although at this point I don't imagine it makes a great difference.

Take a look at the book, Head First Design Patterns, by Elisabeth Freeman. Specifically, read up on the Decorator and Factory patterns and the method of programming to interfaces, not implementations. I found that book to be hugely effective in illustrating some of the complex concepts that may get you going on this.

Hope this helps to point you in the right direction.

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'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.

If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.

Perhaps a good example, as pointed out in the Head First Design Patterns too, is the JAVA Swing API which implements the Observer pattern. More specifically, the JButton (or the superclass AbstractButton) is the Observable class and provides methods to add and remove "Observers", or "Listeners" as they are called in Swing.

I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.

How can I do this?

You are looking for the Singleton pattern. Read the wikipedia article and you will find examples of how it can be implemented in Java.

Perhaps you'd also care to learn more about Design Patterns, then I'd suggest you read the book "Head First Design Patterns" or the original Design Patterns book by Erich Gamma et al (the former provides Java examples, the latter doesn't)

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.

This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.

  1. A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
    How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?

  2. What approach do you experts follow with singletons?

    // Approach A
    public class Test{
        public static final Test TestInstance = new Test();
        private Test(){ ... }
        .
        .
        .
    }
    
    
    // Approach B
    public class Test{
        private static final Test TestInstance = new Test();
        private Test(){ ... }
        public static Test getInstance() { return TestInstance; }
        .
        .
        .
    }
    

    Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?

  3. What if I try to clone the class/object?

  4. a single-element enum type is the best way to implement a singleton.
    Why? How?

Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."

For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.

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

and

Design Patterns By Cameron Childress

Update:

Stumbled upon cfdesignpatterns.com, 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

I have a hard time explaining code or different development paradigms such as design patterns, etc. In my mind, I know what I am talking about, but when I am explaining something I did to a senior or a peer, I feel I am not being as articulate and therefore not doing justice to them. Sometimes, I feel as if I am trying to hard to explain something or making something more difficult that what it actually is. How do you approach explaining code or other practices to someone or a group of people? What are ways you have improved your articulation of code and practices? Does confidence have anything to do with this?

My personal experience about this:

  • Use diagram more than words, or talking. A good diagram worth thousands of words. Although others may not understand the detail, a diagram can give them a high level idea of how things work.
  • Start with something that the audience can understand, and evolve your solution. My favourite Design Pattern book, 'Head First Design Patterns', is a typical example about this.
  • Make sure everyone is on the same page. Make sure everyone understand the problem before you go into the solution. This sounds really stupid but you cannot imagine how often that people start the discussion with 'OK, let's do something like this ... ' without clarify the problem beforehand.
  • Seeking feedback. Everyone has its own problem about presenting ideas to others. You have to ask your audience about their feelings - too fast? need some check point in the middle to clarify questions? etc.

This is a great question. I don't think computer science majors get enough experience at public speaking and defending their code in college. At least the ones I have interviewed haven't. Here are my thoughts on this.

  1. Listen to what your co-workers are saying, and work hard to make sure they know that you understand their point of view. You can't change anybody's opinion if they think you don't understand their starting point.
  2. Read design patterns book, such as Design Patterns in Java . How they explain theories will help you learn to articulate your own.
  3. Take a public speaking course. Getting passed the nervousness is a big one.
  4. White-board out your ideas, visual aids are an immense help.

I have a need to create a "transactional" process using an external API that does not support COM+ or .NET transactions (Sharepoint to be exact)

What I need to do is to be able to perform a number of processes in a sequence, but any failure in that sequence means that I will have to manually undo all of the previous steps. In my case there are only 2 types of step, both af which are fairly easy to undo/roll back.

Does anyony have any suggestions for design patterns or structures that could be usefull for this ?

If your changes are done to the SharePoint object model, you can use the fact that changes are not committed until you call the Update() method of the modified object, such as SPList.Update() or SPWeb.Update().

Otherwise, I would use the Command Design Pattern. Chapter 6 in Head First Design Patterns even has an example that implements the undo functionality.

I like reading open-source code to see how particular problems have been solved, or simply to study how to create nice and clean code.

I was wondering if there actually was any good book out there that goes through excerpts of different (preferably in Java) open-source projects to show how patterns have been used and implemented, some nifty tricks, etc.?

Update: I took design patterns as an example, but it’s not really what I am after. I read a lot of open-source code, and I often find interesting ways of doing things which I didn’t think of before – my question is whether there is a book that shows some “cool” open-source code, a bit like how Clean Code uses FitNesse code to illustrate refactoring and other points.

Well, you can read just book about open source project, and authors can show what and how. E.g. I read Pro Spring 2.5 and there is even chapter called "Spring Patterns" with explanation of why and how they call files, directories, design patterns they use and invite you to use etc. Probably take a look at the books about open source projects you investigate.

UPDATE (just that paragraph insert to extend answer:) : as I told previously, you can look through the books about open source projects and find there information how this project is developed, architectural issues etc. Once I looked for real good example of "Open/Closed Principle" using, theory is nice but I would not say that it is so clear how to use it. The only book which helped me was Expert Spring MVC and Web Flow (I already pointed you to google books with that chapter I read). I didn't read the whole book, but I am sure it contains a lot of such things (what and how was used to make Spring done). From book Clean Code: A Handbook of Agile Software Craftsmanship I remember that there is a chapter, when they take a code from one open source project and make it better (unfortunately open source does not mean that it is good enough); that book also contain reference to how some other projects where written (e.g. jUnit). I don't know any book, which is completely dedicated to any project, there are just books where is "theory", and books about project which can have some explanation of what is inside. I would recommend books from APress (Pro and Expert series, afaik "beginning" books does not contain such explanation), and Packt Publishing - their main topic is open source.

UPDATE 2 (just can't stop :) Just remembered new series of books from OReilly "Beautiful ...." - I never read it, but I looked through. It actually consists of different stories behind development, real stories from life. I see there is also Beautiful Code: Leading Programmers Explain How They Think - I should contain what you need. Other "beautiful" books can be worth of your time too.

About patterns in general there are a lot of good books, and it depends on what exactly are you looking for. E.g. Head First Design Patterns is quite good to explain common patterns in fun way. If you need more, you can take a look at Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions to see how different applications, systems etc. can be integrated (and how open source projects do it too). Etc. Just specify what patterns or tricks do you want to read about, community will make its suggestion ;)

Some web links out of my bookmarks:

  1. Anti Patterns Catalog - know what you are not going to do!
  2. Design Patterns and Martin Fowler's Catalog - that's shortly about what is good to use and know about
  3. SOA patterns - community site for SOA patterns (integration etc.)

And few more books to take a look at:

  1. Head First Object-Oriented Analysis and Design
  2. Agile Software Development, Principles, Patterns, and Practices
  3. Code Complete - this book is just a bible of how to write code...

people, who develop open source definitely know what are those books about ;)

Hope that helps

UPDATE (25-05-2011) Just found one book, which I definitely going to buy, and I think it perfectly fits your question:

The Architecture of Open Source Applications
enter image description here

Architects look at thousands of buildings during their training, and study critiques of those buildings written by masters. In contrast, most software developers only ever get to know a handful of large programs well — usually programs they wrote themselves — and never study the great programs of history. As a result, they repeat one another’s mistakes rather than building on one another’s successes. This book’s goal is to change that. In it, the authors of twenty-five open source applications explain how their software is structured, and why. What are each program's major components? How do they interact? And what did their builders learn during their development? In answering these questions, the contributors to this book provide unique insights into how they think. Electronic versions of The Architecture of Open Source Applications for e-readers will be available for download soon.

I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.

My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.

I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)

The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.

I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.

In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.

Any suggestions would be appreciated.

Not a direct answer to your question but O'Reilly's Head First Object-Oriented Analysis and Design is an excellent place to start.

Followed by Head First Design Patterns

Inspired by the Question on Python-Progression Path -

I know the basic OOP-related topics, RTTI, Templates. Reverting back from Java' Collection Framework, I tried to find such collections in C++ and found STL, and am trying to use it in my projects (although I don't know them in and out). I searched and found recommendations for books like Accelerated C++, Effective and More Effective C++. But I am not sure what should be my progression path, so I am looking for something like -

def apprentice():
  read(diveintopython)
  experiment(interpreter)
  read(python_tutorial)
  experiment(interpreter, modules/files)
  watch(pycon)

def master():
  refer(python-essential-reference)
  refer(PEPs/language reference)
  experiment()
  read(good_python_code) # Eg. twisted, other libraries
  write(basic_library)   # reinvent wheel and compare to existing wheels
  if have_interesting_ideas:
     give_talk(pycon)

def guru():
  pass # Not qualified to comment. Fix the GIL perhaps?
  1. Discover list comprehensions
  2. Discover generators
  3. Incorporate map, reduce, filter, iter, range, xrange often into your code
  4. Discover Decorators
  5. Write recursive functions, a lot
  6. Discover itertools and functools
  7. Read Real World Haskell
  8. Rewrite all your old Python code with tons of higher order functions, recursion, and whatnot.
  9. Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as a dictionary plus some functions. Embrace functional programming.
  10. Rediscover the Strategy pattern and then all those things from imperative code you tried so hard to forget after Haskell.
  11. Find a balance.

It's a tough question, because what you really need is becoming good at what you do, and thus no authoritative list exists.

That being said...

  • Read Effective C++ by Meyers and C++ Coding Standards by Sutter, you're not likely to understand everything if you're a beginner, so re-read them from time to time (it's also a good vaccine)
  • Time to introduce the STL (it's an amazing little pearl), learn to use its algorithms instead of hand-crafting everything, if possible jump straight to the C++0x version
  • Incorporate Boost into the mix, softly at first: boost::optional, boost::variant, boost::lexical_cast, boost::numeric_cast make your code safer and more idiomatic. Also poke the Boost String Algorithms library.
  • Template Meta Programming and Boost.MPL are next: C++ Template Meta Programming by Abrahams Gurtovoy will help there. You might have to leverage Boost.Preprocessor for some template stuff.
  • Learn more Boost Libraries, it's a gigormous repository and it's amazing all the libraries there are.

I am still at that last part myself, so cannot comment on going further :)

At each step, you should write a lot of code, reading isn't sufficient, you need to experiment. Programming is not just technic, the architectural part of the program is extremely important in the field.

Oh and try and join (if only to read) an open-source project, nothing beats writing code and it's better when someone else reviews it :)

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?

Thanks.

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 ?!

Thanks

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.

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

http://martinfowler.com/eaaCatalog/

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 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.

Can we use stub methods for implementing interfaces ? i.e., suppose I get a message that says I must implement ServletRequestAttributeListener and HttpSessionListener - what do I need to do? Can I simply put the method signature, and use dummy values?

You should consider investing some time into looking at design patterns. I think what you are looking for is The Template Method Pattern. A good book for exploring design patterns is Head First Design Patterns. It's an easy read and has some great info.

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....

Thanks.

Design Patterns, Gang of Four.

In a language agnostic point of view, you should buy definitely this (easy to learn through examples):
http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124

or Refactoring To Patterns for a more cause-and-effect approach:
http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351

I am a java programmer with 2 years experience, I really like programming, especially OO programming, and if I have a project, I start with programming directly, without any system analysis operations, so my code is not sorted as it should be, I want to learn how to write and design a good code, should I start learning UML or I can go directly through Design patterns ? and what are the best books for learning UML and Design Patterns.

Thanks a lot for your time

UML is a means to an end, and by no means the only one. Try it and see if you like it, personally I'm not too fond of it. You need to discover yourself how you want to think about and design your applications. Personally I like drawing boxes on a whiteboard.

Design patterns can be useful but they describe solutions to more specific problems. A pitfall here is that people that start off with design patterns try to apply them everywhere. They try to match a design pattern with a problem, but it should be other way around. UML and Design Patterns are in no way mutually exclusive and they don't (necessarily) serve the same purpose.

As far as design patterns are concerned, I found Head First Design Patterns to be a nice and easy to read book, although this is terribly subjective as I know a lot of people who really hate the writing style of the Head First books.

I am looking for a book which can teach OOP concepts using c++ . Could you guys please suggest me some books.

The best way of learning OOP is by learning Design Patterns. I started out with the book Design Patterns Explained. However, many people recommend Head First Design Patterns, so that's probably a good choice too, even though it illustrates the concepts using the Java programming language.

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 projecteuler.net)** 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 a little experience in C++ and Java, but I want to be professional with them. Also, when i want to develop a secure application, what is the recommended way?

I don't know how much experience you have in C++, but assuming you've got a pretty good grasp of that language as well as object-oriented concepts, I recommend reading Head First Java - it's a really easy read and will catch you up with an overview of the language (including basic threading and sockets).

For information on building data structures or implementing algorithms using the Java language, I recommend Data Structures & Algorithms In Java. The books presentation is okay - some of the code is crunched on some pages, but the material is solid.

Lastly, the Java API is a great resource, in my opinion. I can't think of a time when I didn't find what I was looking for on that site. Personally, I think that if you read through Head First and then work on some personal projects and keep the Java API by your side you'll be good to go.

Although this question was asked by someone who wanted to improve java skills, I think the answers posted there are good for learning Java for the first time, as well. Like I said to answer the other question, it's all about Effective Java.

I have a method in my static state machine that is only used once when my application is first fired up. The method needs to be public, but I still want it hidden. Is there a way to use an annotation or something that will hide the method from the rest of the project?

If a method is public, it can't be hidden. What you may really be looking for is just a way to restrict access to calling a method. There are other ways to achieve a similar effect.

If there are some things that your state machine does that are "only used once when my application is first fired up" it sounds a lot like those are things that could happen in the constructor. Although it depends on how complex those tasks are, you may not want to do that at construction time.

Since you said your state machine is static, is it also a Singleton? You could maybe use the Singleton Pattern.

public class SimpleStateMachine {

  private static SimpleStateMachine instance = new SimpleStateMachine();

  private SimpleStateMachine() {
      super();
      System.out.println("Welcome to the machine");  // prints 1st
  }

  public static SimpleStateMachine getInstance() {
      return instance;
  }

  public void doUsefulThings() {
      System.out.println("Doing useful things");  // prints 3rd
  }
}

Here's some code for a client of this Singleton:

public class MachineCaller {

    static SimpleStateMachine machine = SimpleStateMachine.getInstance();

    public static void main(String... args) {
        System.out.println("Start at the very beginning");  // prints 2nd
        machine.doUsefulThings();
    }
}

Note that the SimpleStateMachine instance isn't built until the first time your class is accessed. Because it's declared as static in the MachineCaller client, that counts as a "first access" and creates the instance. Keep this tidbit in mind if you definitely want your state machine to perform some of those initialization tasks at the time your application starts up.

So, if you don't want to turn your state machine class into a true singleton... you can use a static initialization block do your one-time tasks the first time the class is accessed. That would look something like this:

public class SimpleStateMachine {

    static {
        System.out.println("First time tasks #1");
        System.out.println("First time tasks #2");
    }

    public SimpleStateMachine() {
        super();
        System.out.println("Welcome to the machine");
    }

    public void doUsefulThings() {
        System.out.println("Doing useful things");
    }
}

While we're at it, since you mentioned that it's a state machine... the Head First Design Patterns book does a nice, easily understandable treatment of the State Pattern. I recommend reading it if you haven't already.

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.

Cars
 - 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?

Thanks!

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 read books, articles, tutorials and all that kind of stuff about the n-tier architecture and I'm trying to apply the famous 3-tier (DAL, BLL, PL) and I just got into the game, actually I've read a lot about how bad is to load the whole database into memory (which the dataset do) specially when I'm going to need to view details about an item which will have to be retrieved from 5 tables or something, so it will be a lot and I want just ONE RECORD! and the only case where I'll need many records It won't be much at a time and it will retrieve very simple information (id, name, address) something like this!

Do you think it's better to find another way to create my DAL and BLL without datasets ? or dataset is better ? if dataset is not good for performance and so on, do you have any material to teach me how to do so ?

Most of what's been said is solid advice. I would agree that if you're looking into investing the time to build an N-Tier application, you should consider looking into an ORM solution. If you're building on .NET technologies, EF4 is a very good approach to building your DAL.

There is definite confusion on your understanding of what your DAL/BLL should be returning. DataSets are a bit antiquated now in .NET 3 and 4, though not uncommon. You should read up on the Repository design pattern when building your DAL. Depending on the implementation, your repository will typically return a generic List<T> or IQueryable<T>. IQueryable is my preference, however, it's been argued that it blurs the lines between your BLL and DAL.

Some implementations also call for every aggregate to have its own repository. (ie CustomerRepository, EmployeeRepository) I've found it simplest and best to create a generic Repository where the type has a constraint.

So for example:

Repository<TEntity> : IRepository<TEntity> where TEntity : ITrackable

To see an great approach to designing your DAL, take a look at nCommon. Tony Sneed has an excellent blog series on using Entity Framework with POCOs: http://blog.tonysneed.com/2010/02/19/trackable-dtos-taking-n-tier-a-step-further-with-ef4/

The time spent designing your DAL and Domain layer is critical.

My advice is subjective and shouldn't be taken as correct or incorrect. I don't know the requirements of your application. The return on investment might be greater for you if you can hammer out some code quicker with simple datasets and sqldatareaders. If you're looking to build a maintainable design, spend the extra time reading about EF4 and N-Layer architecture patterns like the others have suggested.


[EDIT]

In response to your comment below I thought I could share some valuable resources I've found in learning architecture.

First off be prepared to put in countless hours of reading and re-reading. Using your current knowledge and with constant practice, applying what you learn. The most important thing to realize is: your design will never be perfect because there's no such thing, and just because you apply a pattern does not necessarily make it best.

Having your own personal projects is invaluable to moving forward in OOP. In Malcolm Gladwell's book Outliers, he theorizes that it takes an average 10,000 hrs of practice before you can master something. So keep coding and learning. :)

One of the best books you can pick up is Head First - Design Patterns. It's highly regarded as a phenomenal introductory book to OOD and changes the way you think about code. I remember reading through several chapters and instantly realizing, "Wow! I've been writing code like this all along, but never knew there were names for it!" It helped me realize how familiar design problems are; that there are common solutions for them, and how important it is to be able to communicate them with fellow developers. That book will seriously knock you on your ass (in a good way).

Note, however, that architecture and design books will give you a scenario in which the design applies as well as an implementation of the pattern. It took me a little while to realize there can be many ways to implement the pattern ... especially in .NET. You'll see that when you start reading books by Martin Fowler, Robert C. Martin, Eric Evans, Dino Esposito.

There are many excellent resources for free online such as Microsoft's Application Architecture Guide. Some of the best ways of learning techniques are simply reading blogs.

For Entity Framework, it's hard to beat Julia Lerman's Programming EF4. As to clarify the role of an ORM - it facilitates communication with your database and allows you to "query" it as if it were object oriented. So for example some pseudocode:

With a SqlDataReader, you would normally run a query like

"SELECT * FROM Users WHERE Users.UserId = 1"

With an ORM, you're not actually writing the SQL. The ORM maps your database tables to actual class objects, thus allowing you to query against a strongly typed object. So you would write something like:

User user = EFContext.Users.Where(u => u.UserId == 1).SingleOrDefault();

The ORM is responsible for translating this into SQL and executing the query. This abstraction also allows the ORM to work with multiple databases (MSSQL, Oracle, MySql) through provider extensibility.

When you start involving a layered architecture, your Repository is responsible for communicating with the ORM or database and returning your results to your BLL. For instance a basic example would look something like:

using (var repository = new Repository<User>()) { User user = repository.Where(u => u.UserId == 1).SingleOrDefault(); }

This is a very rudimentary definition of an ORM and how it's used. Once you start learning patterns: how to recognize them, when to use them (not always, as they can over complicate something simple) and refactor your own code, then start reading into domain-driven design.

Hope this helps.


[EDIT 2]

Sure, let me clear up what's actually being returned by each layer. Depending upon your repository implementation and your design decisions:

From your Infrastructure layer which is where the ORM sits, you would typically return either a generic List<T> or an IQueryable<T> where T represents your object. Whether its an Entity Object or POCO is up to you. A POCO is simply a class that represents your data, however it's not just bags of getters and setters. It should contain validation at least. Read up on anemic domain models and how to avoid them.

From your Domain layer, which contains your business logic, depending on how loose coupling you're trying to achieve, you'd either return a List<T>, BindingList<T>, or you will use a mapping technique of returning a collection of DTOs to your presentation and service layers.

DTOs add another series of complications, but are essential to some scenarios. DTOs are immutable objects. They should be built like such:

[DataContract]
public sealed class UserSummary : IDto
{
[DataMember]
public String FirstName { get; private set; }

[DataMember]
public String LastName { get; private set; }

[DataMember]
public UserProfile Profile { get; private set; }

public UserSummary(String firstName, String lastName, UserProfile profile)
{
    FirstName = firstName;
    LastName = lastName;
    Profile = profile;
}

}

They are only bags of getters and setters. Your POCOs should be able to easily map to them and there's an excellent piece of software to make this process simple: AutoMapper. They do not have to represent exact tables in your database or or POCO objects, but can comprise several parts of them like seen above.

There is one catch. Sometimes DTO's are not enough information to return to your services or web UI. You'd also typically need to return validation results, error handling information, maybe a boolean to express the result of the transaction.

There's not an exact name for this object, but I've gone on to call it a Response Transfer Object which composes a List<IDto>, ValidationResults from Microsoft's enterprise library, and anything else I would need to know.

This a lot of information to consume. When learning NLayer development, break it up as you would each layer. Tackle learning one thing at a time and write down every question that pops into your head. Make sure to seek out those answers.

Since there's no complete BPM framework/solution in ColdFusion as of yet, how would you model a workflow into a ColdFusion app that can be easily extensible and maintainable?

A business workflow is more then a flowchart that maps nicely into a programming language. For example:

How do you model a task X that follows by multiple tasks Y0,Y1,Y2 that happen in parallel, where Y0 is a human process (need to wait for inputs) and Y1 is a web service that might go wrong and might need auto retry, and Y2 is an automated process; follows by a task Z that only should be carried out when all Y's are completed?

My thoughts...

  • Seems like I need to do a whole lot of storing / managing / keeping track of states, and frequent checking with cfscheuler.
  • cfthread ain't going to help much since some tasks can take days (e.g. wait for user's confirmation).
  • I can already image the flow is going to be spread around in multiple UDFs, DB, and CFCs
  • any opensource workflow engine in other language that maybe we can port over to CF?

Thank you for your brain power. :)

Off the top of my head I'm thinking about the State design pattern with state persisted to a database. Check out the Head First Design Patterns's Gumball Machine example.

Generally this will work if you have something (like a client / order / etc.) going through a number of changes of state.

Different things will happen to your object depending on what state you are in, and that might mean sitting in a database table waiting for a flag to be updated by a user manually.

In terms of other languages I know Grails has a workflow module available. I don't know if you would be better off porting to CF or jumping ship to Grails (right tool for the job and all that).

It's just a thought, hope it helps.

The Model View Controller concept is expressed all over the place as an important thing to keep in mind when developing an application. But when developing applications, I struggle to distinguish whether or not I'm using the MVC model and whether or not that is hurting my application. Why is the MVC concept important in application development and how does it help developers make better programs?

You are separating software components and creating a design that is loosely coupled. This will allow for easier maintenance, easier to read and shorter code, flexibility, and expand-ability. Many things follow this design patter (websites, mobile apps, ect.)

I can promise you learning it is well worth your time. I would suggest jumping in and starting with something simple like (CodeIgniter, PHPBlueprint) just to get your feet wet and see an MVC work.

A good book to checkout would be Head First Design Patterns.

Why do we need both accept and visit functions in the visitor DP? if we take the typical example:

class Visitor {
  visit(A a) { }
  visit(B b) { }
}

interface Element {
  accept(Visitor v);
}

class A implements Element {
  accept(Visitor v) {
    v.visit(this); // will call visit(A)
  }
}

class B implements Element {
  accept(Visitor v) {
    v.visit(this); // will call visit(B)
  }
}

To use the visitor DP, somewhere we have an instance v of Visitor, and an instance e of Element, and we do:

e.visit(v)

which simply calls

v.visit(e)

so why can't we simply do the second call and bypass the mediator function? Since I think the GoF are not dumb, I guess I'm missing something. What is it?

Here is an excellent reference for the Visitor pattern, in which they mention the following:

When the accept() method is called in the program, its implementation is chosen based on both:

  • The dynamic type of the element.
  • The static type of the visitor.

When the associated visit() method is called, its implementation is chosen based on both:

  • The dynamic type of the visitor.
  • The static type of the element as known from within the implementation of the accept() method, which is the same as the dynamic type of the element. (As a bonus, if the visitor can't handle an argument of the given element's type, then the compiler will catch the error.)

Consequently, the implementation of the visit() method is chosen based on both:

  • The dynamic type of the element.
  • The dynamic type of the visitor.

Then they go on to mention the following:

This effectively implements double dispatch...

In this way, a single algorithm can be written for traversing a graph of elements, and many different kinds of operations can be performed during that traversal by supplying different kinds of visitors to interact with the elements based on the dynamic types of both the elements and the visitors.

Which can be seen in the Java car example:

class Car implements CarElement {
    CarElement[] elements;
    // ...
    public void accept(CarElementVisitor visitor) {     
        for(CarElement elem : elements) {
            elem.accept(visitor);
        }
        visitor.visit(this); 
    }
}

So, to summarize, in your example, you wont get much benefit from the original DP implementation, but if the example is more complex, for example its a Composite with several internal implementations of Element (like the Java car example above), then it can apply the visitor behavior to some or all of its internal elements.

Based on the comments to your original question, there are 2 parts to this pattern:

  1. The original motivation for the pattern: which is to visit a complex structure of objects and perform operations on them without changing the class interfaces being visited.
  2. How the pattern is implemented: which is with the double dispatch as you mention.

I highly recommend the following design patterns book, as it really simplifies many of the concepts. The GoF book is sometimes too academic.

Head First Design Patterns

According to this book, here are the pros and cons to using the Visitor:

(In the context of the example used)

PROs

  • Allows you to add operations to a Composite structure without changing the structure itself
  • Adding new operations is relatively easy
  • The code for operations performed by the Visitor is centralized

CONs

  • The Composite classes' encapsulation is broken when the Visitor is used.
  • Because the traversal function is involved, changes to the Composite structure are more difficult

Are there any C# GOF design pattern examples? I Keep finding this site which does have examples, but the "C# Optimised" examples are only available when you purchase one of their products.

I really recommend Head-First Design Patterns.

It is technically Java, but I've never looked at Java before and was completely readable for a C# developer. I checked it out from the library, only to find out that many of the .NET developers I know own it themselves already.

Development environment is C# 3.5 with a SQL Server 2008 database and Entity Framework.

Imagine you have a class and a table called Sign which represents a physical electronic sign created by a third party which your software needs to control. You also have a class called SignDriver which takes care of actually communicating with the signs. The properties/columns of Sign represent configurable information needed by the Sign Driver to properly talk to the signs.

Everything is great and you’ve patted yourself on the back quite thoroughly. Then the need arises to talk to a different sign. However this sign works differently to the previous one and requires your Sign class and table to store additional information. Let’s say 5 new things (columns/properties) need to be stored, but, unfortunately the first type of sign does not need these 5 things. You then find when you want to control 10 of each type of sign, you have many NULL values in your table.

Your domain model grows until you have more classes like Sign, each representing a different part of your problem domain and each with a corresponding table in your database. Each class suffers the same issue of collecting the common information of its type well, but NOT catering for the specialisations of each type well at all.

You realise that the nature of your problem means that there are going to be more types of signs to control, as well as more types of your other entities to cater for. You need a more extensible model.

What would be the best way forward for a system like this??

I have discussed this at length with my collegues and would really like to know what the best way to approach a problem like this is. Especially because it seems like a problem MANY people would have faced in the past.

Below are the options we’ve come up with and some points about each:

  • Create n number of ‘type’ classes and table for each entity to share a 1 to 1 relationship with.
    • Very inheritance-y.
    • Most time consuming when extending.
    • Many tables.
  • Create one ‘extended properties’ table for each entity to hold key-value pairs.
    • Referential integrity.
    • Extensible.
  • Create one global ‘extended properties’ table to store properties for ANY entity. (schema: entityType, entityId, key, value, dataType)
    • Super extensible.
    • Cannot have referential integrity with existing tables.
    • Doesn’t look like Entity Framework will be able to handle this well.

What would you do and why??

Any help greatly appreciated. Cheers.

This question touches on multiple issues of software design.

Your main issue seems to be with mapping an inheritance hierarchy to your database tables. This has been extensively analysed - see the work of Martin Fowler in his book "Patterns of Enterprise Architecture". You can get some brief overviews here, but the book is better and should be on every OO developers shelf. Compare the "Table per subclass" and "Table per class hierarchy" patterns.

Some general advice: be careful of too much inheritance - favour composition over inheritance. You can almost always refactor to avoid inheritance. Basically you end up with your 'specialisations' decoupled from the Sign class, which then gives you a way forward in terms of creating a table hierarchy. As mentioned, the Head First Design Patterns book is a good place to start.

Also, don't be afraid to have heaps of classes and heaps of tables. Generally flexible designs favour lots of classes and tables (although of course there are downsides to doing this too - it's up to you to decide the best compromise).

Good morning everyone,

I hope I'm not posting this in the wrong place; I've been programming web projects, mostly in MVC and ASP.NET for consulting companies, but I always pick-up unfinished projects, so I gotta say, my experience in web development isn't as good as I'd like it to be. To improve my experience, I decided to accept building a project for a veterinarian clinic and I'm going to build the project in MVC. There are a few things I'd like to know to make my project well structured and to avoid feeling lost in the process because I don't have as much time to research as I'd like to. So the main questions I'd like to ask are:

  • When beginning a new project, where should I begin? Making the stylesheets? Should I go straight for the code? If I make some planning, how should I go about it then?

  • When building up the Media folder in my project, if I decide I'll use
    jQuery and the like, what files
    should I really get? What's the best way to implement jQuery in a MVC
    project without having to mention it in every page?

  • To make a sort of planning for
    myself, complete with deadlines I
    have to respect, what structure
    should I use?

  • Well, I'm not good at designing at
    all, and I often have to rely on
    other people's CSS to make things
    look decent, so how could I use this project to improve that and still
    make it look good?

I hope we can all share some experience in the matter at hand and make this topic help others who might be feeling the same weaknesses as I do.

When you start building your code I suggest you start with register, login and authentication. After that: Internationalization and localization (see: http://en.wikipedia.org/wiki/Internationalization_and_localization)

Then create your CRUD's and so on..

EDIT: Some other resources you might wanna have a look at:

Good luck!!

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 creating a client side swing app that will have data provided by/from one of many data providers(brokers). The data providers however, have varying ways of perfoming same things e.g.

broker1's login method

public boolean doLogin(String username, String password);

broker2's login method

public int login(String username, String password,String sessionId);

For all providers the set of required actions is the same e.g

login, getstatus, sendRequest, getData, logOff
(but they have different params and return types)

I took a look at the adapter pattern but am unfortunately not able to use it well as the required methods have different parameters.

Is the adapter pattern usable in this case? if so how?
If not what would be the best way of doing this?

Thanks.

My first thought was looking into the facade pattern, which, in my 'Head First Design Patterns' book, is explained in the same chapter as Adapter and compared with a remoted control for home theatre components.

This facade would sit between the client app and the various brokers. So the client wouldn't have to care, which and how many brokers are part of the 'theatre', it just have to 'press the login button' and 'all broker connections are switched on'.

I am looking for OpenSource Java Projects to study and understand how certain design patterns are applied in real world.

To that goal, Which are the best opensource projects to study applications of software design patterns?

To study design patterns I would recommend going first with the book Head First Design Patterns and try to build simple examples yourself. Once you do that you will start recognizing patters everywhere you look :). Once you know what they look like you can pick up any popular open source project and you will find ton of examples there.

Actually you don't even have to look much as there are many examples of design patterns in jdk you are using already: Examples of GoF Design Patterns

I can't figure this out, I'm a pretty novis Eclipse user. I'm a .NET/C# Guy by trade, and playing with Java in my spare time.

I have a .NET WCF Service hosted with basicHttpBinding -- I'm successfully calling this service from another .NET application, I've used the Visual Studio SvcUtil to generate the proxy class (via Add Service Reference).

I'm wondering how I can achieve the same result for Java using Eclipse? I've downloaded the latest version of Eclipse, but I can't seem to get it working.

If you take a look at Head First's Design Patterns there is a nice example of the proxy pattern with a tutorial on how to get it working. All the code is in Java and you get to learn about other types of proxy patterns too.

i got this interview question about how to represent a Zoo in OOP and my answer was that the Zoo will have property set animals, where Animal is an abstract class and all the animals in the zoo will extend it, it will contain the species,city properties. and Zoo will extend the abstract class Agricultural_land, which contains the space,place properties.

and i got a question about if i have different types of birds, how to represent them in OOP and i said i will make another class for birds and different types of birds will extend it.

please give me your ideas.

Any object is a combination of state (field values) and behaviour (methods logic). I think if you have to represent something as an object you better specify the context first. If you develop some land trading application then your Zoo should have fields like cost, owner, lastSoldDate and methods like sell, changeOwner, calculateTax. If you work on game then your Zoo will have animals, trees and so on. Clear context allows you to decide what is important for your object and what's not.

As for birds I suggest you to read first chapter of Head First Design Patterns book. There is very fun and clear explanation of how to design ducks hierarchy and how to avoid common pitfalls. They explain the composition over inheritance principal which become kind of enlightenment for me. Now I'm trying to avoid inheritance and design my objects as a set of components responsible for behaviour. And now no over 9000 classes for different birds, no complex classes hierarchy where you scratch your head if you need to add a new bird. That's really nice book :)

I hope this is the right place to ask.

I am fairly new to .NET and I am having some problems regarding implementing OOP concepts. I have followed a couple of books about c# and here is he problem.

By now, I know the OOP concepts theoretically, but I donot know 'How and When' to use these concepts in real world scenario. e.g. i know the DEFINITION of abstract, sealed, public classes and so on but i donot know WHEN to use them.

every books talks about person class or car class examples. but all those examples doesnt seem to work if i think of creating a for example simple inventory system. how would i define classes, methods, properties about an inventory system. this is where i alwys get stuck.

If possible please tell me of some book or resource to follow.

Thanks

You might like to read Ron Jeffries' Extreme Programming Adventures in C#. It's rather outdated in terms of C# versions, but it's a good read. It is essentially his diary of learning C# by writing an XML editor. It is also focused on XP methodologies, as indicated by the title, especially test-driven development.

By presenting the material in the form of a journal or diary, the author gives interesting insights into his thought processes; the flow of the narrative depicts his problem-solving process (pursuing a solution, then realizing it's no good, abandoning it for another solution, etc.).

That aspect is usually absent from programming books, which generally lay out ready-made solutions, sometimes without adequately explaining the problem being solved. In real life, problems come before solutions, not the other way around.

I'm writing a web application that can get good results and grow up in the future. If it happens, a team will program it and not only me. So, I'd like to find some design patterns for my programming.

I don't know if I should write method names in my language or in English, how should I name my databases, etc, etc.

Someone knows about a good guide for that purpose?

@sll's answer will probably prove the most resourceful for you, but I love your strive to get better. We make our interns read Head First Design Patterns: http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124 (or it's included if you have a Safari Online account).

That book is a pretty rock solid overview and a pretty decent foundation for design patterns. All the code is technically in Java, but it translates well to any of the OO languages.

As to your question about what language to use (again, as it's not really a design pattern as a cultural paradigm IMO), I would simply do your best to consider your time to develop the software with what you anticipate your audience to be. The industry norm is to try to program in the same language that the CLR is written in (typically this is English) but I will simply offer this point/counterpoint:

  • If you intend to open source or outsource your code it could make it very limiting to the developers that could continue a Portuguese paradigm.

  • A code base that is created quickly and elegantly in your language is better than a code base that languishes in English (and takes way too long to release) just to conform to the industry.

As a final comment, if it was written mostly in English, but you named the few methods that you mentioned in Portuguese, no decent developer should mind working on that (or refactoring later) so long as you comment what the method does adequately.

Granted this link is the Microsoft way, but it should be helpful to your question also: http://msdn.microsoft.com/en-us/library/ms229042.aspx

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

I need to create a new website, I have the database modeling done and I need to start it, I also want to use MVC and LinqToSql.

My boss said that I'll might need to create an app for Windows Phone 7.

I never follow any good practice or pattern when I'm working on this, what I mean is, when a user clicks a Register button in a web page, I create an instance of my DataContext, validate the input and etc all inside the event handler for that button click.

So, what about when I need to make the WP7 app? I'll have to copy and paste the code again? I know that I should reuse it, but I don't know actually how, where should I place the business rules, data access etc...

I was reading about Enterprise Patterns, but I found it too complicated for me as I don't have much experience yet.

Please advice me on this.

Also, if you can point me to a good sample project that I can check its source code and follow the same architecture, would be great!

thanks!

You should look at moving to N-tier design, separate your UI from the Biz from the Dal. This also allows reuse of your biz logic and Dal in the phone app, or any where else you might need to.

Here is a blog post that kind of covers what you are going to need to do N-Tier Design revisit this is the first of 5 posts covering N-Tier design, I include some code samples and have some projects to look at in the repository.

Another suggestion is to get a copy of Head First Design Patters to learn design patterns, and start looking at learning best practices. Good design is technology agnostic, you should spend as much time learning how to design something as you do what you're building it in.

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.

Trying to improve my OOPS skills. Is there a site or book where can I find OOPS problems like CoffeeBrewerDesign problem? Or somebody can give me some problems on which I can work?

I personally have this book and I find it pretty well written and easy to read. They give you specific problems that you need to solve and show you different ways of solving them.

Head First Design Patterns

FOLLOW UP TO MARC GRAVELLS SUGGESTION IN THIS QUESTION

I now have something like this repeated several times in my code:

using (var conn = CreateConnection())
using (var dataCommand = conn.CreateCommand()) 
{
        conn.Open();
        [...]                        
} 

Is the following correct for the factory method CreateConnection()? Or will it be error prone? (note: I'm only ever going to call it from a using directive)

SqlConnection CreateConnection()
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
    return conn;
}

Or would there be a case for amending this method and having the Open in it as well?

Your code is the typical example of static factory method.

Factory Pattern is a part of Software Design Patterns, which are general reusable solutions to a commonly occurring problem within a given context in software design. I can suggest you to read Head First Design Patterns which is a very good starter book to understand design patterns.

Couple of suggestions about your code:

  1. Make the factory method static, it doesn't use any instance variables etc.
  2. Not related but, you don't need to use a local variable in your factory method, you can directly return the connection.

Now your method looks like this:

static SqlConnection CreateConnection(){
    return new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
}

You might wanna check if the ConnectionStrings["IMS"] is null before calling the constructor of SqlConnection. No further error handling is required in this class because it doesn't initiate the connection.

Let's say you want to return an open connection and handle connection errors in the same method:

static SqlConnection CreateConnection()
{

    if (ConfigurationManager.ConnectionStrings["IMS"] == null)
    {
        throw new Exception("Connection string not found in the configuration file.");
    }
    var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
    try
    {
        sqlConnection.Open();
    }
    catch (Exception exception)
    {
        throw new Exception("An error occured while connecting to the database. See innerException for details.", exception);
    }
    return sqlConnection;
}

If you want, you can create your own exception classes to handle these exceptions later. See ASP MVC N-Tier Exception handling. You can also return null if an exception occurs, but check "Is returning null bad design?" first.

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#

thanks

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

Can you please tell what are the types of patterns that affect programming?

There are design patterns that simplify the design of programs, offering turnkey solutions. However, due to programming testing, analysis, documentation and so on. That patterns of these areas I'm interested.

Looking ahead at the moment I have identified:
1) architectural
2) design patterns
3) analysis
4) test
5) documentation
6) implementation

UPD:
I am interested in all types of global patterns associated with the programming. An example of such patterns - architecture, design patterns, testing.

On this page is a list of patterns. Can you please tell which of these patterns can be attributed to global, and which are part of the global?

Looking ahead, we dare say that Threading Patterns, Parallel Programming Patterns and Ajax Design Patterns can be attributed to the design patterns

This gives a good list of all the patterns. (scroll about halfway down)

http://en.wikipedia.org/wiki/Software_design_pattern

Also, if you want to read about design patters, I highly suggest Head First Design Patters. You can learn all about them, and how they function, and when to use them. I used this book in my web development classes and loved it.

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124

Hope that answered your question!

I am looking for the correct design pattern to use in the following situation:

I have a process which runs and during this process I need to attach several properties to an object in the system. The object is of the same type but at runtime it might exhibit slightly different behaviour and therefore the way the properties are set can be different depending on the type.

Regardless of the type and behaviour of these objects I want to set the same properties on each.

I then need an object to parse these properties at another point in the process

What is the best way to approach this?

I would suggest you not try to pick a design pattern before coding. First, write the code. Then, start abstracting any redundant code, or code that varies. To understand abstracting code that varies, read Head First Design Patterns. At the very beginning of that book is an example of abstracting what varies, using the strategy pattern. The SimUDuck example there is one of the best-explained examples I've ever seen of the strategy pattern. It sounds like that's what you're asking about. However, your question doesn't have a concrete example of what you're trying to do, so giving a concrete example is difficult here.

Having said that, it sounds like you need good, ol' fashioned polymorphism here: you need to treat all objects the same way, and set the same properties, just with different values. To do this, create an interface and have all of your different types implement that interface. Then, in the calling/consuming code, deal with each of those concrete types as the interface.

If you try to pick a design pattern first, many times you'll end up finding that things change based on the details of the implementation, and your original guess at a design pattern ends up being the wrong fit. Then you end up coding to meet a design pattern and not solving the real problem. Write the code first, even if it's ugly. Get it working. Then find areas to abstract and it will naturally evolve into a design pattern on its own.

I am new to Coldfusion and using ColdFusion MX (7) and I am interested in to implement Strategy Pattern. But I don't know what will be the best possible way to start the implementation.

I recommend head First Design Patterns book. It covers the strategy pattern as well as a bunch of others, it's well written and will help you again and again when designing applications.

I am often facing design patterns, and I find most articles explaining them a bit hard to understand, especially since I don't speak English fluently. I would very much appreciate if someone could explain simply and in basic English the following design patterns: Builder, Prototype, Bridge, Composite, Decorator, Facade, Flyweight, Proxy and Observer.

Or if you have any links to good resources, I'm willing to spend the time to try to understand it.

G'day,

The GoF book has been translated into many other languages. In fact the first time I saw it was in French, In fact, Wikipedia says into thirteen other languages.

BTW I also vote for looking at the Head First Design Patterns book.

HTH

cheers,

I am trying to build an object to represent a ridiculously large form for a project I am working on. http://www.flickr.com/photos/namtax/5351091239/

I didnt want to build all the fields into one large object as I didnt think this was a good way to do things, so I have structured the model as so -

One contact object.

  • One work object - linked to the contact one to one.

  • One travel object - linked to the contact one to one.

  • One address object - linked to the contact one to many.

  • One emergency contact object - linked to the contact one to many.

Here is the sample code for one of these relationships - written in CF9 ORM

    property name="work"
             fieldtype="one-to-one"   
             cfc="work"     
             mappedby="contact";

The issue here is that it causes the saveContact function in my controller to be large and code smelly due to all the possible options you can choose in the form. Here is a rough translation of the code

VARIABLES.contact = contactService.getContact(form.iContactId);
contactService.set(contact:contact,argumentCollection:form);
contact = contactService.save(contact);

if(_emergencyContactService.userIsSubmittingAnEmergencyContact(form)){
  VARIABLES.emergencyContact = _emergencyContactService.getEmergencyContact(contact);

   emergencyContactService.setEmergencyContact(emergencyContact,form);

        if(! contact.hasEmergencyContact()){
            contact.setEmergencyContact(emergencyContact);
            emergencyContact.addarrContacts(contact);
        }

        _emergencyContactService.save(emergencyContact);
    }
// Repeat this logic to check if work object, travel object or address object have been selected in the form also, get and set accordingly.

I then repeat the if statement shown above for emergency contact, to check whether the work object, travel object or address object have been selected in the form also. If so, get and set the object, then link the contact object where necessary.

This doesnt seem efficient to me, especially as I need to repeat all this logic on another controller method as well. Is there a better way to structure my objects, or a better way to handle my controller code?

Thanks.

My initial thoughts are to move any repeating logic from your controller to a service object that you can call from many places.

Bringing that along: you could break up the form into sub-forms - each represented by a 'sub-form' object. Each of these objects should be able to deal with information related to it's part of the form, and it should know what to save to the database. You could compose these form objects into a service object that you call from your controller.

One other thing I noticed is the way you actually pass your entire FORM scope into some functions. I tend to avoid this as you really are not describing what the function needs to do the job, and of course this scope can change when you don't expect it. I would suggest you specify the arguments required by each sub-form object and pass them to the service.

Example psuedocode:

// Controller code
travelSubFrm = new TravelForm(name, dob, address ...); // etc
workSubFrm = new WorkForm(position, dept ...); // etc

// Create service and save details - the service knows the logic
contactFormService.setTravelSubFrm(travelSubFrm);
contactFormService.setWorkSubFrm(workSubFrm);
contactFormService.process();

Just some quick thoughts.

Hope that helps!

EDIT: If you want to start looking into how to architect object-orientated code then I suggest you check out Head First Design Patterns. It's a great introduction to the topic and will help you organise code problem like the one you posted.

I'm an 18 year old apprentice in c# programming (specificly in OOP 'structure')

I'm currently trying to learn the use/usefullness of Interfaces, but.. I have a VERY hard time trying to actually use Interfaces, I've decided to start working on problems from Project Euler. What I want to do with these problems is to try and implement Interfaces or anything I need to learn so that I get some experience with it.

I'm currently at Problem 2 but I can't think of a way to implement Interfaces.

So in general what I would like to ask is, what and how can I do this (please don't give me the final result, I am only looking for an idea or help to get started)

I feel like I'm stuck in a hole, unable to continue, so I would love some inspiration, examples or litteraly anything where I can get good and concise information! :)

In advance, thank you very much for your help/constructive criticism.

-Kindest Regards, Niklas

Interfaces are, in my opinion, a software engineering tool. Can you use them on things like Project Euler questions? Absolutely! They are a tool, after all.... But the usefulness of them are minimal and very debatable.

If you want to learn how interfaces apply to the real world, I strongly recommend that you study Design Patterns.

Some resources to get you started:

  • Wikipedia - Free resource but you are left to your devices
  • Head First Design Patterns - Best software engineering book I've read... Covers design patterns well and shows actual usages of Interfaces. Note that book's programming language is Java but this truly does not matter. OOP is OOP no matter the language.

This is not all there is to say about Interfaces, mind you, but it's a common real world scenario that you see interfaces used.

I'm just getting into how to write a good architecture of a good software system, and I'm learning how to separate high level components into Layers. In this case, I'm trying to use Tiers, so as to model each Layer as a black box.

There are 4 tiers in my architecture: Presentation, Application Services, Business Logic, and Domain/Persistence. For the purposes of my question, we really only need to focus on the Presentation and Application Services.

The Application Services Layer will contain a Service that allows tracking of a certain event. The Presentation will have several views that should update dynamically as the tracking model of the events change. Inherently, it seems that I need a one-way change-propagation mechanism.

Since I'm trying to model these Layers as Tiers, I'd like to restrict communication between Facade objects for each Tier, and when necessary, allow a Tier to aggregate an object from one Tier lower, though only known by interface.

I'm programming this application in Java, so the obvious thing to use is Observable/Observer. However, I don't like that the update method for the Observer interface forces you to cast object arguments. I want to work around this by defining my own interface and class for this mechanism. The problem, then, is that the Application Logic will depend on an interface from the Presentation Tier, a certain no-no for this architecture. Is this a sign that I should try modeling with MVC fore-most and Layer the Model? Or would it be a better idea to model each of the views with an interface known in the Application Services Layer. It seems like a bad place to put it, and I'm stuck. Also, I'm using the View-Handler design pattern to handle the multiple views.

It seems to me that your question is less about Publish/Subscribe than it is how to get the layers to communicate.

Short answer:

Use MVC/MVP. Look up blog posts about them, download source code, and remember: if all you have is a hammer, everything looks like a nail. Meaning don't apply patterns because you have them, apply them because you need them.

Long answer:

If you're working in Java, I suggest Head First Design Patterns which will get you oriented to the way of thinking in patterns. After you have your head around design patterns, which I think you're on your way to now, you can look at Patterns of Enterprise Application Architecture. Feel free to skip Head First, but it is a very good book that I highly recommend if you're getting into architecture.

Once you've digested the Fowler book, or at least have a basic understanding of N-Tiered Enterprise Architecture, you should be well on your way.

I'm reading the Head First Design Patterns book when a doubt came into my head.

In the very first chapter, studying the Strategy Pattern they taught to make interchangeable classes. According to the picture below:

Strategy Pattern

My question: What if I want to make a desktop application with a visual interface and let some users have more privileges than others to administrate the Ducks and its behaviors? So, they could for example create the FlyRocketPowered behavior at runtime. How can I achieve this?

I mean, these behaviors look weird to me to be represented as classes, because I can't see how to make them editable at the user level, every time a FlyBehavior, a QuackBehavior or a Duck subclass needs to be created/deleted/changed the users will have to ask me to modify the source code by creating/deleting/changing the classes, however this not what we want, we need something more developer-independent.

EDIT

Say I want to make a screen Add Fly Behavior (just add, not edit, not remove), there would have two fields, the first would be the Behavior Name, the second would be the content to be printed when the fly() method is called.

By editing the source code I could do this by creating a class like this:

public class FlyRocketPowered implements FlyBehavior {
   public void fly() {
      System.out.println("I’m fl ying with a rocket!");
   }
}

What would I need to do to make this at the user level?

Firstly i'd like to say I love this book. It's my favourite programming book.

To your question: I think you missunderstood the strategy pattern a little bit ;) The goal is not to enable your users to create new behaviors at runtime. But with this pattern, you can give your 'admins' some panel to give any Duck any available behavior. So the behaviors are still generated at compiletime. But you can interchange the behaviors at runtime

Additionally, just as a funfact: It is totally possible to let your 'admin' create new Behaviors at runtime. Take a look at the Java compiler api. But if you think about doing so, remember how big the security hole is and also how unimaginable stupid the worst case customer is.

I'm working on a game with finding objects on the screen which has also implemented the parallax effect. For certain reasons I've added my objects as CCMenuItems to the parallax layers

I'd like to know which will be the best design pattern suitable to me in order to handle my objects;

I've found that are six (maybe more of this but this is what I've found so far)

  1. Model-View-Controller
  2. Delegation
  3. Target action
  4. Notifications
  5. Block model
  6. Managed memory model

Any tutorial for the best one would be great! ;)

My answer: None of these at this time.

Because a) your question is too broad and not specific enough. and b) this indicates you need more general knowledge about patterns first to be able to use them meaningful. I think if you had this knowledge already you would have put the question differently.

I suggest you read up on patterns and software design more, first. Book Tip: Head First Design Patterns by O'Reilly.

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=sr_1_1?ie=UTF8&qid=1328729374&sr=8-1

I'm working on a project with a contractor we hired to do some VB.Net programming. I used to program for this project, but I have more recently become primarily the project manager so I can work on other issues I have. His method of programming differs greatly from what I was taught in school. The only time he uses classes is basically in the form of a sort of dataset (not an actual dataset, as I learned how to use in school). As an example, there's the cEmployee class, where he creates a class for an Employee, and in that he defines all the fields an employee has.

All functions are put in Modules. So if he has several functions to populate a combo box, they all go in the combo box module. My understanding on this though is that when the program is run, the modules are treated as global functions and included regardless of whether or not they are actually used on a form. To me this sounds like it would increase the resource requirements to run such a program, since the large amount of module code has to be included for every form.

The way I learned was to put functions with specific purposes in namespaces and classes, then import the appropriate namespace and class when needed. Then only the necessary code to run a form is loaded, and the extra code for functions that are not needed isn't loaded until imported on a form. I never used modules myself, but I can see their utility, I just think he is severely mis-using modules in this case. Am I correct?

It's hard to answer without seeing the code. From the information in your question it seemed that your contractor was writing procedural structured code, which is old-fashioned, but not necessarily a huge problem, although many programmers who are used to OO won't enjoy looking at the code.

From your last comment on Dan's answer it sounds like he is writing a module for each functional area, with routines that can act on any object. The routines accept Object or Variant arguments, detect the type of object passed with case/if statements, then branch to the appropriate code for that object. Is that right? That is quite eccentric and hard to maintain. Usually, a better way is to declare interfaces for the functional areas, and have the classes implement the interfaces.

I've seen code like this from self-taught programmers. To be fair to them, they are bright people who were stumbling towards inventing OO programming from scratch! It can be a slow process though, and it's better to learn about other people's conclusions first! I might recommend a course on OO programming, or if he is a reader a book like Head First Design Patterns or even Code Complete 2, which has some good chapters on design. If you can get him hooked on Code Complete, that would be a good thing.

I recently read an article on Wikipedia about Design Pattern

So far I've done this, but it returns Fatal error: Maximum function nesting level of '100' reached, aborting!

Logically I know, it will return nesting error, But, I don't understand how is the best step.

class Main {
    $this->Aa = new Aa;
    $this->Bb = new Bb;
    $this->Cc = new Cc;
    }
class Aa extends Main {
    function blahA() {
        // blah blah
        }
    function testA() {
        $ret[] = $this->blahA(); // Call inside class
        $ret[] = $this->Bb->blahB(); // Call outside class
        $ret[] = $this->Cc->blahC(); // Call outside class
        return $ret;
        }
    }
class Bb extends Main {
    function blahB() {
        // blah blah
        }
    function testB() {
        $ret[] = $this->blahB(); // Call inside class
        $ret[] = $this->Aa->blahA(); // Call outside class
        $ret[] = $this->Cc->blahC(); // Call outside class
        return $ret;
        }
    }
class Cc extends Main {
    function blahC() {
        // blah blah
        }
    function testC() {
        $ret[] = $this->blahC(); // Call inside class
        $ret[] = $this->Aa->blahA(); // Call outside class
        $ret[] = $this->Bb->blahB(); // Call outside class
        return $ret;
        }
    }

Basically i want to manage my classes design, in order the method in Aa class is also reusable in Bb class and vice versa. I curious, how to build the relationship like my classes above, How to extends the class to get above pattern? And what is the name of this pattern? please also give me a link that i can learn from.

Many Thanks,

Consider creating Aa and Bb separately and using Dependency Injection so each class will have a reference to the other. You should make sure the two classes are not too tightly coupled though.

The Gang of Four (GoF) Design patterns book mentioned in the comments is a good one, but the Head First Design Patterns is a bit easier (also very enjoyable) for beginners.

Here is an example. Notice there are better ways to set a property in PHP, I put a setter function just to be explicit. Refer to this question for more info.

class Main {
    $this->Aa = new Aa;
    $this->Bb = new Bb;
    $this->Cc = new Cc;

    // Can use properties instead of setters
    $this->Aa->setB(Bb);
    $this->Aa->setC(Cc);

    $this->Bb->setA(Aa);
    $this->Bb->setC(Cc);

    $this->Bb->setA(Aa);
    $this->Bb->setC(Bb);
    }

class Aa {                // No need to extend Main, right?
    function blahA() {
        // blah blah
        }
    // Dependency injection, Bb is now a member of this class
    // Consider doing this with PHP properties instead
    // Using setter function to be more explicit
    function setB(Bb b) {
        this->Bb = b;
        }
    // Dependency injection, Cc is now a member of this class
    // Consider doing this with PHP properties instead
    // Using setter function to be more explicit
    function setC(Cc c) {
        this->Cc = c;
        }
    function testA() {
        $ret[] = $this->blahA(); // Call inside class
        $ret[] = $this->Bb->blahB(); // Call outside class
        $ret[] = $this->Cc->blahC(); // Call outside class
        return $ret;
        }
    }
// Class Bb ...
// Class Cc ...

I saw AsP.NET Design Patterns Here how can i understand which Design Pattern is Appropriate for our Projects? most of our projects are Office Automation Projects. I Had Never Used Any ASP.NET Design pattern In my projects. just i used microsoft nettiers Thanks.

I dont think any one can tell you which design pattern would be the best for your project. Because each design pattern solves some particular problem. And, you just have to choose a design pattern depending on the problem you want to solve in your project. You can also use combinations of design patterns to solve some particular problems.

Design patterns are efficient solutions for commonly faced problems and are generally used so that you dont reinvent the wheel. As you say you dont know much about design patterns I would suggest you to pick up some book to learn about design patterns. Head first design patterns was the first book I read about design patterns.You can start with that book. It will help you understand a number of commonly used design patterns and which pattern to use and when.

I've been looking to improve my programming habits and I heard that OO is the way to go. Also I'd much prefer online tutorials over books.

Learning how to use classes, methods, and attributes is not sufficient for making you a good object oriented programmer. The other (and usually much more difficult) part is understanding how to solve problems in an object-oriented way.

It's a bit like chess: Even if you have memorized the rules perfectly, it does not mean you automatically are a good chess player. You still need to learn a about strategy and gather a lot of experience.

I haven't found a good web tutorial on how to become a good object-oriented programmer. The topic is too large to be covered within just a few web pages. You are probably better off reading a book on the subject. It doesn't even have to be specific to php, most OO pricinples can be applied to many different OO languages.

Once you have learned the basics of OO programming, I'd also recommend reading a book on design patterns such as the classic Design Patterns by Gamma et al. or the more casual Head-First Design patterns.

Some recommend "PHP in action" by Manning.

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 http://www.php.net/ 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 http://www.amazon.com/PHP-5-Objects-Patterns-Practice/dp/1590593804). 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.

Please see code below. I cannot see where I am going wrong. I am also very confused! Much obliged for any help!

package code;

public class Client {

 public static void main(String[] args){

     proxyPlane plane = new proxyPlane(new Pilot(18));
        plane.flyPlane();

        plane = new proxyPlane(new Pilot(25));
        plane.flyPlane();

        DecoratedPilot decPilot = new Pilot(35);

        System.out.println("Experienced Pilot of age " + Pilot.Age() + " " + decPilot.getDecotation());   
    }

}


package code;

public interface DecoratedPilot {

public String getDecotation();
}


package code;

public class Decoration extends PilotDecorator {

public Decoration(Pilot pilot) {
    super(pilot);
    // TODO Auto-generated constructor stub
}

@Override
public String getDecotation() {
    return "Pilot has earned his Commercial Wings";
}
}


package code;

public abstract class PilotDecorator implements DecoratedPilot {

public PilotDecorator(Pilot pilot)
{
    apilot = pilot;
}
}


package code;

public class Pilot implements DecoratedPilot {

private static int age;

public static int Age() {

    return age;  
}

public Pilot(int age){

    Pilot.age = age;
}

public String getDecotation() {
    // TODO Auto-generated method stub
    return null;
}
}

The problem is you're not actually decorating anything. That is, you're not "wrapping" a Component with a Decorator.

Here's an example of the Decorator pattern.

An excellent example of this pattern is in the book: Head First Design Patterns. I really like this book and highly recommend it if you dont already have it.

We define interface as below:

interface IMyInterface
{
    void MethodToImplement();
}

And impliments as below:

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

instead of creating a interface , why can we use the function directly like below :-)

class InterfaceImplementer
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

Any thoughts?

You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer

EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.

There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx

If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link

Do you have good literature recommendation for Design Patterns, especially for Data Access layers.

I'm searching for patterns like Repository and Unit of Work. I need those for implementing WebServices, MVC web applications and MVVM desktop applications.

If you are searching specifically for Repository and Unit Of Work patterns then i suggest that you don't read full books because they discuss them i a generic way and you will get overwhelmed, instead look for specific implementations for those patterns in the technology area you are working in.
With that being sad, the two authors that stand behind Repostiory and UnitOfWork patterns are Martin Fowler and Eric Evans with their books Patterns of Enterprise Architecture and Domain Driven Design: Tackling Complexity at the Heart of Software respectively, the latter book is followed by a great book called Applying Domain Driven Design and Patterns with Examples in C# and .NET.
Regarding design patterns in general the authoritative reference is The GoF (Gang of Four) book Design Patterns: Elements of Reusable Object Oriented Software System and a very great book that focuses on the most common patterns in an entertaining manner is Head First Design Patterns.

(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 {
public:
    void render() {
        // do some common stuff here
        doRender();
        // do some more common stuff here
    }

    virtual void doRender() = 0;
    ....
};

class TagA : public TagBase {
public:
    virtual void doRender() {
        // do your specific stuff here
    }
};

Here are a few good books:

I am learning Design Pattern and I have a question.

For example, here is the first design.
Shape
Shape->Red Circle
Shape->Blue Circle
Shape->Red Square
Shape->Blue Square
...

Second design
Shape
Shape->Circle
Shape->Square
Shape->Circle->Red Circle
Shape->Circle->Blue Circle
Shape->Square->Red Square
Shape->Square->BlueSquare
...

Thanks to Tony, I come up with a situation. In first design, the Shape class is abstract, and now I have a function for "Red Square" and "Blue Square" only. That means I cannot define the function in the Shape class but I need to do it one by one in "Red Square" and "Blue Square". The same situation for second design, I can put the new function in "Square" class.
Now, my question is am I correct and is there any other design I can use?

Your question is not specific enough to give a solid answer. After discussing in the comments it is clear you are actively trying to learn design patterns so it may not be clear to you the best way to ask the question. I am providing this as an answer so I have room to type.

Resources

dofactory - I use this as my reference source when looking for a pattern that matches my need.

Head First Design Patterns - I used this book to get a good introduction into design patterns and how to use them. Learning design patterns was a pivotal point for my understanding development. It shows you how to truly use interfaces and abstractions to achieve common problems in software development.

Beginner Guide to Design Patterns - Nice article to get you started with design patterns.

Javascript Design Patterns - (BONUS) This site was incredible for learning javascript design patterns. I am including to illustrate a point I make below about looking up design patterns for any language you use.

When looking at dofactory you can see there are three areas the patterns fall into; Creational, Structural, Behavioral. When looking for a pattern know what you are trying to achieve.

Few Tips

  • Don't force a pattern if it does not naturally fit the problem.
  • Don't over engineer the solution by trying to force patterns into every line of code you write, they are useful but not always needed.
  • Do use multiple patterns when necessary, it is perfectly 'Ok' to have multiple patterns playing close together, again.. if it is a natural fit.
  • Do learn a few common patterns, this small list is my own but a google search will reveal others personal list of commonly used patterns;
    • Strategy
    • [Abstract] Factory
    • Singleton
    • Command
    • Decorator
    • Observer
  • Do look up design patterns for any language you attempt to learn, it will give you a better understanding how to better utilize the language. (see bonus link above)
  • Do spread your wings after you get a decent understanding of the GoF patterns and look into the Enterprise Design Patterns.

I hope this answer helps guide you on the path to learning the design patterns. I know it does not exactly answer your question but hopefully it will help you understand a little better and enable you to return with a more specific question about design patterns and the usage for your code.

I am learning the decorator pattern from the Head First Design Patterns book , and here's what I've coded (C++) to get the pattern to work:

#include <iostream>


class AbstractType
{
public: 
    virtual double value() const = 0;
};


class FirstConcreteType
    :
    public AbstractType
{
public: 
    double value() const 
    {
        return 1; 
    }
};

class SecondConcreteType
    : 
    public AbstractType
{
public:
    double value() const
    {
        return 2;
    }
};

class DecoratorType
    :
    public AbstractType
{
    const AbstractType* decoratedObject_; 

public:

    DecoratorType(const AbstractType& abstractObject)
        :
    decoratedObject_(&abstractObject)
    {}

    DecoratorType(const DecoratorType& decoratorObject)
        :
    decoratedObject_(&decoratorObject)
    {}

    virtual double value() const = 0; 

    const AbstractType& getObject() const
    {
        return *decoratedObject_; 
    }
};

class FirstDecoratorType
    :
    public DecoratorType
{
public:
    FirstDecoratorType(const AbstractType& abstractObject)
        :
    DecoratorType(abstractObject)
    {}

    FirstDecoratorType(const DecoratorType& decoratorObject)
        :
    DecoratorType(decoratorObject)
    {}

    double value() const
    {
        const AbstractType& object = getObject(); 

        return 1 + object.value(); 
    }
};

class SecondDecoratorType
    :
    public DecoratorType
{
public:
    SecondDecoratorType(const AbstractType& abstractObject)
        :
    DecoratorType(abstractObject)
    {}

    SecondDecoratorType(const DecoratorType& decoratorObject)
        :
    DecoratorType(decoratorObject)
    {}

    double value() const
    {
        const AbstractType& object = getObject(); 

        return 2 + object.value(); 
    }
};

using namespace std;

int main()
{
    // When I decorate sequentially, it works fine

    SecondConcreteType secondConc;

    FirstDecoratorType firstDec(secondConc); 
    cout << firstDec.value() << endl;

    SecondDecoratorType secondDec(firstDec); 
    cout << secondDec.value() << endl;

    FirstDecoratorType firstDecSecond (secondDec); 
    cout << firstDecSecond.value() << endl; 

    // Decorating in a single line, messes things up, since there is no
    // constructor taking the value argument defined.  
    //FirstDecoratorType firstDynamicDec (SecondConcreteType()); 
    //cout << firstDynamicDec.value() << endl;

    return 0;
};

In the main program, the object of theh ConcreteType must be created first, and then it is decorated using composition of the pointer to the AbstractType (within the DecoratorType). It works fine, if I create the concrete objects, and create the new decorated objects one after another..

What do I need to do in order for the DecoratorType to be able to decorate objects using composition in a single line of code (commented out line in the example code)? Would something like this be useful at all in the "real world"? I (obviously) don't have a lot of experience in using design patterns.. so it's difficult for me to see what functionality I should aim at.

EDIT:

Here's a version working with basic pointers (valgrind shows no memory leaks, and states that no memory leaks are possible):

#include <iostream>


class AbstractType
{
    public: 
        virtual double value() const = 0;

        virtual ~AbstractType() {}; 
};

class FirstConcreteType
:
    public AbstractType
{
    public: 
        double value() const 
        {
            return 1; 
        }
};

class SecondConcreteType
: 
    public AbstractType
{
    public:
        double value() const
        {
            return 2;
        }
};

class DecoratorType
:
    public AbstractType
{
    const AbstractType* decoratedObject_; 
    bool own_;

    public:

        DecoratorType(const AbstractType& abstractObject)
            :
                decoratedObject_(&abstractObject), 
                own_(false)
        {}

        DecoratorType(const DecoratorType& decoratorObject)
            :
                decoratedObject_(&decoratorObject), 
                own_(false)

        {}

        DecoratorType (AbstractType* abstractPtr)
            : 
                decoratedObject_(abstractPtr), 
                own_(true)
        {}

        DecoratorType (DecoratorType* decoratorPtr)
            :
                decoratedObject_(decoratorPtr), 
                own_(true)
        {}

        virtual ~DecoratorType()
        {
            if (own_)
            {
                delete decoratedObject_; 
                decoratedObject_ = 0;
            }
        }

        virtual double value() const = 0; 

        const AbstractType& getObject() const
        {
            return *decoratedObject_; 
        }
};

class FirstDecoratorType
:
    public DecoratorType
{
    public:
        FirstDecoratorType(const AbstractType& abstractObject)
            :
                DecoratorType(abstractObject)
        {}

        FirstDecoratorType(const DecoratorType& decoratorObject)
            :
                DecoratorType(decoratorObject)
        {}

        FirstDecoratorType (AbstractType* abstractPtr)
            :
                DecoratorType(abstractPtr)
        {}

        FirstDecoratorType (FirstDecoratorType* decoratorPtr)
            :
                DecoratorType(decoratorPtr)
        {}


        double value() const
        {
            const AbstractType& object = getObject(); 

            return 1 + object.value(); 
        }
};

class SecondDecoratorType
:
    public DecoratorType
{
    public:
        SecondDecoratorType(const AbstractType& abstractObject)
            :
                DecoratorType(abstractObject)
        {}

        SecondDecoratorType(const DecoratorType& decoratorObject)
            :
                DecoratorType(decoratorObject)
        {}

        SecondDecoratorType (AbstractType* abstractPtr)
            :
                DecoratorType(abstractPtr)
        {}

        SecondDecoratorType (SecondDecoratorType* decoratorPtr)
            :
                DecoratorType(decoratorPtr)
        {}

        double value() const
        {
            const AbstractType& object = getObject(); 

            return 2 + object.value(); 
        }
};

using namespace std;

int main()
{
    // When I decorate sequentially, it works fine

    SecondConcreteType secondConc;

    FirstDecoratorType firstDec(secondConc); 
    cout << firstDec.value() << endl;

    SecondDecoratorType secondDec(firstDec); 
    cout << secondDec.value() << endl;

    FirstDecoratorType firstDecSecond (secondDec); 
    cout << firstDecSecond.value() << endl; 

    // Decorating in a single line, messes things up, since there is no
    // constructor taking the value argument defined.  
    FirstDecoratorType firstDynamicDec (new SecondDecoratorType (
           new FirstDecoratorType (new SecondConcreteType()))); 

    cout << firstDynamicDec.value() << endl;

    return 0;
};
FirstDecoratorType firstDynamicDec (SecondConcreteType()); 

The problem with this is that it does NOT define an object. Instead, it declares a function. Look for most-vexing-parse in C++ on this site, you will get lots of topics on it.

Short explanation : the function name is firstDynamicDec whose return type is FirstDecoratorType and it takes parameter which is again a function returning SecondConcreteType and taking no argument.

I am new on Java, and its kind of difficult to me to get into the concepts of Java, I am working with Maven, and Ive read some books but in some give an structure and in others give other structure, the problem of all is that according what Ive read (I want to use Spring) there is a MVC structure, my problem is that I dont know where each thing has to be.. where to set my getters and setters, where my view, where my controllers.. and how to connect them... I am lost.. any reference you could give me or any clue? Id be very glad.

My structure now is

src/test/java
src/test/resources
src/main/resources
src/main/resources/META-INF

Thanks

For you, I would highly recommend the excellent "Headfirst Design Patterns" book by headfirst

I am relatively new in Java. In one of my project I have three jframes. They are Menuframe,that has list of menus; LoadDatafromExcelframe, that is use to select and read data from Excel file; and ShowDataFrame, that is use to display data that I read in LoadDatafromExcelframe. Actually its part of a big project. not the whole project! At the beginning of my project I am reading Excel file and load all the data in arraylist. Till this point I am good. Now I want to click the ShowDataFrame from the menulist to display the data that I have read in the LoadDatafromExcelframe. If I can access the arraylist then I think I can move forward. My question is "How can I access arraylist from one jframe (ShowDataFrame) to another frame(LoadDatafromExcelframe)?"I am using Netbeans IDE.

private void jMenuItemShowDataActionPerformed(java.awt.event.ActionEvent evt) {                                                   
            showDataFrame.setVisible(true);
}

The key issue has little to do with JFrames or Swing in fact, but is simply one of passing information from one object to another. The only way Swing gets involved is if you want to pass this information in response to an event of one sort or another.

The solution is usually one of simply giving your classes appropriate getter and setter methods, of separating out your "model", the logical portion of your program, from your "view", the GUI portion of your program, and of using some sort of listener or observer type interface (such as can be obtained via Swing event listeners) to notify one class when the other is ready to push or pull information.

More general recommendations:

  • Avoid making anything static that does not need to be static. That is a quick solution that usually causes more pain in the long run as it makes your code very hard to enhance later and to test.
  • Avoid using lots of JFrames. Most professional GUI's have but one master window, one "JFrame" if you will. Often it is better to swap views in this JFrame such as with a CardLayout or with tabbed panes if needed. Also information that needs to be obtained in another window in a modal fashion can be displayed in a modal dialog.
  • Get a good book on OOPs basics as it applies to Java programming, such as Bruce Eckel's "Thinking in Java".
  • And get a good book on use of design patterns with Java such as Head First Design Patterns. These two concepts are key to moving ahead in Java.
  • Avoid using code generation utilities such as NetBean's form creation utility as it shields you from learning Swing specifics, and hinders your ability to learn to create complex Swing GUI's. Sure, use these tools once your a Swing journeyman, but until then, use the Swing tutorials to learn the library and code by hand.

For more specific advice, you will need to provide more details and provide more code.


Edit 2

More advice based on your post:

In one of my project I have three jframes. They are Menuframe,that has list of menus; LoadDatafromExcelframe, that is use to select and read data from Excel file; and ShowDataFrame, that is use to display data that I read in LoadDatafromExcelframe.

This looks to be better implemented creating 3 JPanels and not 3 JFrames. Then you could display the JPanels as needed in a single JFrame using a CardLayout to help you swap them.

Actually its part of a big project. not the whole project! At the beginning of my project I am reading Excel file and load all the data in arraylist.

This ArrayList should not be "read into a JFrame" but rather the data belongs in a non-GUI class, one of your "model" classes to be exact. Then the view classes, your GUI code can ask the model for this data whenever necessary. Read up on Model-View-Control program design on this site to learn more about this useful pattern.

Till this point I am good. Now I want to click the ShowDataFrame from the menulist to display the data that I have read in the LoadDatafromExcelframe.

Here using MVC structure, one of your "view" classes, the one holding the "menulist" should notify the "control" class that your code needs the ArrayList data held by the "model" class. This could all be done by having the Control class hold references to both "model" and "view" and having the "view" class hold references to the control thus allowing communication between classes.

I am writing a log file decoder which should be capable of reading many different structures of files. My question is how best to represent this data. I am using C#, but am new to OOP.

An example: The log files have a range of sensor values. One sensor reading can be called A, another B. Obviously, there are many more than 2 entry types. In different log files, they could be stored either as ABABABABAB or AAAAABBBBB.

I was thinking of describing this as blocks of entries. So in the first case, a block would be 'AB', with 5 blocks. In the second case, the first block is 'A', read 5 times. This is followed by a block of 'B', read 5 times.

This is quite a simplification (there are actually 40 different types of log file, each with up to 40 sensor values in a block). No log has more than 300 blocks.

At the moment, I store all of this in a datatable. I have a column for each entry, with a property of how many to read. If this is set to -1, it continues to the next column in the block. If not, it will assume that it has reached the end of the block.

This all seems quite clumsy. Can anyone suggest a better way of doing this?

In addition to what Bob has offered, I highly recommend Head First Design Patterns as a gentle, but robust introduction to OO for a C# programmer. The samples are in Java, which translate easily to C#.

I come from C Background and have knowledge on C++(at least I know virtual functions, INheritance, Code -reuse and some OOPS concept), But still I am having hard time understanding the Design Patterns in C++/Java.I guess Binders Design Patterns are based on C++ Design pattern(correct me). DO i have to understand UML as well to understand them. Plz explain or direct a link with test source code on the above.

PS: I am trying to understand this blog by Tetsuyuki Kobayashi and i am in no way related to him.

I wouldnt say that C++ Binders are a design pattern. I put a link here explaining them.

I would also say that Design patterns arent really language specific, they can basically be implemented in any (most) programming languages. Languages that support OOP typically make implementing design patterns easier, but that could be argued.

The Gang of Four design patterns book uses UML to explain design patterns, but I wouldnt say you would have to be a UML expert to understand design patterns. If UML is bothering you, try the Head First Design Patterns book, its much easier to understand.

I have been researching and looking for answers here to a problem that I suspect might be solved by a better understanding of design patterns. I think the problem is that I am a self-taught coder and people seem to tend to assume familiarity with a lot of esoteric terminology; I have ended up in Wikipedia spirals trying to determine what some phrases mean. That said - on to the coding/structural problem.

Actually, just before I start, I should point out that I may well be making unknown presumptions in the way the code is structured in my question. If this is the case, could folks suggest alternatives to what I'm suggesting? I'd really appreciate learning how to better code as opposed to simply being told I'm doing it wrong. OK...

Let's say we have a Room class, which has 4 Walls, a Ceiling and a Floor. These are instantiated 'inside' the Room. The Room also has a Table which has 4 TableLegs, again instantiated inside the Table, inside the Room. (This, I believe, is Composition, but please correct me if I've got that wrong!).

Finally, the problem: If someone, somehow, pushes the Table, the TableLeg(s) will need to check the type of Floor they're standing on to trigger the appropriate sound. This, currently would be my solution:

The Table dispatches an event. The Room listens for that 'table pushed' event, quizes the Floor to determine its type, then passes that type to a method on Table, which in turn passes it to the TableLegs. This, to me, seems fairly inelegant; hence my suspicion that knowledge of design patterns might be useful. Is there something fundamentally wrong about the structure I've described that I'm not appreciating? If so, what is the alternative?

Finally, I have heard of the Gang of Four book. If that's my first port of call, is it written in an accessible style or will I have to have studied computer science to grasp it? Sorry for the long, design-pattern-beginner's question.

The Floor could listen for objects Events. The Event interface could expose information about object geometry, material, etc. Then the Floor could check for collisions and play a sound.

I recommend the book Head First Design Patterns

I have to create an itinerary object which is essentially made of other components.

These components need to be added in a particular order. I need to make sure when things are added out of order, an exception/error needs to be thrown.

Quick walkthrough:

Itinerary Build-itinerary():

- AddSegment()
- AddBaggagePolicy()
- AddMisc()

Segment AddSegment(...)

- add departure airport
- add arrival airport
- add departure time
- add arrival time
- add duration (total duration)
- add airline

where airport and airline are object types.

Once segments are done, I need to consolidate the segments to yield starting departure to final arrival destination (since there can be multiple hop points from one point to other).

What kind of a pattern can I refer to building this itinerary ?

Cannot agree with @Arafangion, I belive that ordering of some procedure invocations is sometimes necessary. I would recommend looking into a Factory Method design pattern, from what I remember there is a nice example in Head First Design Patterns book when preparing pizza stuff :)

I'm importing products and so I have an product import class. It has around 4000 lines so I want to break it up. I've started to break it up but I have difficulty deciding what should be a class and what should not. I think all my methods use three of the same instance variables, so if I separated the methods, I would be passing in these instance variables to each separate class in it's constructor. One way I started breaking this up was by looking at groups of methods that dealt with the same type of product data. For example, some methods worked with product descriptions and some worked with product categories and so I started splitting them into separate classes but then someone told me if these different classes are all using the same three instance variables, they probably should be combined into one class. So, how do I do this? I don't really understand proper class design and was only splitting them up because it was hard to find code in the big class.

If the question here is lost, what are some tips to re-factor a large class. Is what I've purposed above a good solution and should I be re-factoring a class where all the methods use the same three instance variables.

This app is an asp.net app that takes product data from one system A's database and, based on a plethora of settings and configuration the user can choose from, saves the product data to system B's database. For example....

public class ProductImporter
{
    ProductA productA;
    ProductB productB;
    ImportSettings settings;

    public void GetProductADescription()
    {
        //look at the settings and add productB description to productA
        productA.Desc = productB.Desc;
        //....
     }

     //.... tons of methods that all deal with product moving one product to the other

     public void AddProduct()
     {
           //go through all the settings
           productA.Save();
      }

}

Your goal to refactor classes is a good one. Smaller classes are usually better than bigger classes. However, a bad refactor could put you in a worse place than where you started.

I suggest you spend some time reading about good Java design patterns. You can learn a lot from Head First Design Patterns (http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124 ) among others...

I'm learning AS3 and creating a simple 'Asteroids' game. I have written a simple class of linear movement:

package  {

import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;

public class lin extends MovieClip {

    private var vx:Number=0;
    private var vy:Number=0;

    public function lin(x:Number,y:Number,sr:Number,spd:Number) 
    {

        this.rotation=sr;
        vy+=Math.sin(degToRad(sr))*spd;
        vx+=Math.cos(degToRad(sr))*spd;

        this.x=x+vx;
        this.y=y+vy;

        addEventListener(Event.ENTER_FRAME,loop,false,0,true); 
    }

    public function loop(evt:Event)
    {
        y+=vy;
        x+=vx;

        if (outOfBounds())
            kill();
    }

    public function outOfBounds():Boolean
    {
        return (x>stage.stageWidth || x<0 || y>stage.stageHeight || y<0);
    }

    public function kill():void 
    {
        if(parent)
            parent.removeChild(this);

        removeEventListener(Event.ENTER_FRAME,loop);
    }

    public function degToRad (deg:Number)
    {
        return deg * Math.PI / 180;
    }

}

}

And I need to set this behaviour of movement to several objects (LaserBeam, Asteroids) I created a new MovieClip with class 'LaserBeam' and wrote this:

package  {

import flash.display.MovieClip;
import flash.display.Stage;
import lin;


public class LaserBeam extends MovieClip {

    public var LaserBeamInstance:lin;
    public var LaserSPD=15;     

    public function LaserBeam(x,y,r) {
        LaserBeamInstance=new lin(x,y,r,LaserSPD);

    }
}

}

But when I try to run my game, it says:

Line 1  1203: No default constructor found in base class lin.

What should I do to make many different MovieClips share one behaviour?

Thanks in advance!

UPD: all project files is here

In answer to your question:

What should I do to make many different MovieClips share one behaviour?

You should read about OOP patterns. This book is a great introduction.

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124

In response to your error, I think you are not giving us the whole picture. The error refers to class lin being extended, but in the code there are no classes extending lin.

I'm QA engineer and at the university we studied design patterns. I was wondering if where this patterns are used and where they putting into practice?

I hope that somebody can help me with examples, url and demos. I appreciate any help.

Regards

Buy and read the book "Head first design patterns". That should answer your question.

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=sr_1_1?ie=UTF8&qid=1331827403&sr=8-1

I'm trying to learn how to make my application has the same "face" in all files, the same pattern, but I do not know if this is the right thing to do.

I want know if the more correct in software development, is to limit the application to only one type of pattern.

For example, that's how my application looks like (just a piece)

Api.js:

'use strict'
var Server = require('./server');
var Api = {
 init: function() {
   Server.init('start');
 }
};

Server.js:

'use strict'
var Server = {
 init: function(command) {
  this.command = command;

  if (command === 'start') {
    this.start();
  }
 }
};

I'm using the "initializer object pattern" in all my application. So i'm avoiding decorator pattern, facade, everything.

Should i avoid or i can use more than one? If the right answer is use several, depending on the needs, i have other question. This doesn't make the maintenance more difficult? Is not make the code like a spaghetti?

Thanks.


Update.

I'm going to try explain again, this time with a bounty.

i already try to ask but seems that no one really can give me a concise answer.

I would like to know what are the secrets from making a good app, a good web app, talking about code appearance. I want know if I should maintain the same standard code throughout my hole application, if this is GOOD, or really doesn't matter.

For example, i have two EXAMPLES files

app.js:

var server = require('./server');

var app = {
 init: function() {
   server.init('DEVELOPMENT');
 }
};

module.exports = app;

server.js:

var server = {
 init: function(env) {
  if (env === 'DEVELOPMENT') {
    // CODE
  } else {
    // CODE
  }
 }
}

module.exports = server;

In this case, i'm using one object with method init, which is the pattern that i'm using in my hole app..

Or it doesn't matter, i should write anything:

first object:

var server = require('./server');

var app = {
 init: function() {
   server('DEVELOPMENT');
 }
};

module.exports = app;

than server as a function:

var server =function(env) {
  if (env === 'DEVELOPMENT') {
    // CODE
  } else {
    // CODE
  }
}

module.exports = server;

I can give 100 of my points. it's incredible how i can't find a good answer for this particular issue.

Thanks.

Should I using other patterns?

No, you should not insist on a single pattern.

No design pattern books will ever advise you to use a single pattern. Just like you cannot chop all ingredients in one single way (are you going to dice the spaghetti?), you cannot organise all logic in one single pattern.

Sure, you can make all your Objects use the initialiser pattern, and don't use constructors at all. This is ok. Been there, done that. I like it.

But these objects can be used with Builder or Abstract Factory (if it make things simpler). As long as the builders/factories themselves have initialiser, and that they properly initialise the created objects, then your use of the initialiser pattern will be consistent. Outside of creational patterns, it is usually good to organise objects with structural and behavioural patterns. They do not conflict with initialiser at all.

For example, look at DOM. All nodes are created by the Document object - elements, text nodes, comments, even events. This is the Factory pattern.

Yet the Document object is also a Facade! From it you access the whole system's status, objects, data, you can even write to it! Every DOM operation starts from the Document, it is the Facade of the DOM system.

DOM nodes also implements multiple patterns. They are organised in Composite, let you listen to events with Observer and Command, and handle events in a Chain of Responsibility. They are certainly parsed by an Interpreter, DocumentFragment is a Proxy, svg elements are implemented as Decorators, and createNodeIterator obviously gives you an Iterator.

The point is, good object-oriented design will yield multiple design patterns as a result, intentional or not.


What are the secrets for good code appearance

I think the best looking code is the one that is easiest to understand to you, and the way you read code changes as you gain more experience.

For example my style is too condensed for most programmers, but to me it strikes a good balance. So do develop your own style - you are not me, and you are not yesterday's you either.

Remember this as we go through the styles.

At the lowest level we have coding style - most importantly indent and bracket.

This one is simple, pick the one you like and stick with it. There are language specific styles, and they are often good starting points. Configure your IDE's formatter so that you can format all your code with hotkey.

Above the code syntax we have comment style and naming convention.

Setting rules on comment is fine, sometimes it is necessary for documenting tools. Avoid too much comment in practice. You may also want to decide your namespace and your stand on naming function expressions.

Above these structures, we have logic conventions.

The same code logic can often be done in many ways, some more 'beautiful' than the others in your eyes. Look at this example.

I picked the second style on first sight: no duplicate, logic is sectioned cleanly, format is not my style but reasonable. But many programmers would prefer the first style: logic is plain as day, a few duplications is worth it. While abstract, this level is quite deep - present your logic the wrong way actually increase the chance an experienced programmer read it wrong.

Finally, we arrives at the level of design pattern, about as far as code beauty goes.

The key to keep your code structure beautiful, is using the right patterns at right level to consistently accomplish loose coupling and code reuse, while avoiding pitfalls and over-design.

There are quite some books about beautiful code, and then there are even more books about designing and implementing beautiful software. (Decide for yourself which are beyond your level.) Knowledge is as important as experience, and you can gain them only by spending your time to study, to write, and to revise/refactor your apps.

Feel free to change your mind as you explore and experiment with your code. Changing your mind is a good sign of learning.

But first, familiarise yourself with design patterns. Just don't forget, they are the generic result of applying object-oriented principals to common tasks. It is still up to you to do the design.

Design Patterns Are Not Silver Bullets.

I'm trying to use the Strategy Pattern to include different behaviours for different sizes of a simulation.

I came across this implementation from the first example of the book Head First Design Patterns.

However, I don't understand where and how should I access my data initialised in my simulation.

from abc import ABCMeta, abstractmethod
###########################################################################    #####
# Abstract Simulation class and concrete Simulation type classes.
################################################################################

class Simulation:
    def __init__(self, run, plot):
        self._run_behavior = run
        self._plot_behavior = plot

    def run(self):
        return self._run_behavior.run()

    def plot(self):
        return self._plot_behavior.plot()        

class SmallSimulation(Simulation):
    def __init__(self):
        Simulation.__init__(self, Run(), Plot())
        print "I'm a small simulation"
        self.data = 'Small Data'

class BigSimulation(Simulation):
    def __init__(self):
        Simulation.__init__(self, Run(), Plot())
        print "I'm a big simulation"
        self.data = 'Big Data'

class LargeSimulation(Simulation):
    def __init__(self):
        Simulation.__init__(self, RunLarge(), Plot())
        print "I'm a large simulation"
        self.data = 'Large Data'

################################################################################
# Run behavior interface and behavior implementation classes.
################################################################################

class RunBehavior:
    __metaclass__ = ABCMeta
    @abstractmethod 
    def run(self):
        pass

class Run(RunBehavior):
    def run(self):
        print "I'm running standard"
        print self.data

class RunLarge(RunBehavior):
    def run(self):
        print "I'm running multilevel"


################################################################################
# Plot behavior interface and behavior implementation classes.
################################################################################

class PlotBehavior:
    __metaclass__ = ABCMeta
    @abstractmethod 
    def plot(self):
        pass

class Plot(PlotBehavior):
    def plot(self):
        print "I'm plotting results"

################################################################################
# Test Code.
################################################################################

if __name__ == '__main__':
    smallSimulation = SmallSimulation()
    bigSimulation = BigSimulation()
    largeSimulation = LargeSimulation()

    print('='*20)
    print('Execution')
    smallSimulation.run()
    bigSimulation.run()
    largeSimulation.run()

    print('='*20)
    print('Plotting')
    smallSimulation.plot()
    bigSimulation.plot()
    largeSimulation.plot()

The output is

I'm a small simulation
I'm a big simulation
I'm a large simulation
====================
Execution
I'm running standard
Traceback (most recent call last):
  File "strategy.py", line 84, in <module>
    smallSimulation.run()
  File "strategy.py", line 16, in run
    return self._run_behavior.run()
  File "strategy.py", line 52, in run
    print self.data
AttributeError: 'Run' object has no attribute 'data'

How should I initialise and access my data?

Your run class doesn't have a data attribute, hence the exception.

class Run(RunBehavior):
# This class does NOT have a data attribute
    def run(self):
        print "I'm running standard"
        print self.data

To access simulation's data within Run, you can pass it in Run's init():

class Run(RunBehavior):
    def __init__(self, data):
       self.data = data
    def run(self):
       print "I'm running standard"
       print self.data

I read somewhere that C++ OOPS way to program is "Build the objects in factory, Wire them in logic".

I am facing a application design problem. Consider there are several inheritance hierarchies as (with or without virtual functions):-

      Engine
        /\
       /  \
   Diesel Petrol
     /\      /\
    /  \    /  \
 2Cyl 4Cyl 2Cyl 4Cyl


       Audio
        /\
       /  \
 2Deck    4Deck



            Tyres
              /\
             /  \
        15Inch   17Inch
          /\       /\
         /  \     /  \
  tubeless Tube Tube Tubeless                     

  and more.... (System is scalable and new hierarchy may be added later on)

Now I have this application interface where 'Car' object is constructed in pick and choose style, like what Engine type ? What type of seats ? What type of Audio ? etc.

Any ideas, how do I design this system so that the 'Car' Object created is:-

  1. Not tightly coupled to all parts hierarchies Supports addition of new hierarchies to already created cars: Say I have created a 'Car' object with tyres as tubeless and later in the Tyres hierarchy there is a new inheritance, I should be able to configure existing 'Car' object with new tyre type.

In other words, I like to leave the object hierarchy to class design, object creation to factory layer and wiring to logic layer.

Any suggestions.

For starters, this looks like it could become what is commonly referred to as a Class Explosion. These can become a mainenance night-mare in no time at all.

From looking at your diagrams, several classes seem like they should be attributes, instead of actual classes. In the Tyre hierarchy, for example, why do you need 15Inch and 17Inch classes? What state or behavior do those classes offer? Why not put a size attribute on the Tyre class? Maybe even make it an enum. The same could probably be said for the 2Cyl, 4Cyl and 2Deck, 4Deck classes, although its hard to tell from the info presented.

In situations like this, its commonly good practice to prefer inclusion over inheritance when ever possible, which is commonly referred to as: prefer has-a relationships over is-a relationships. This is discussed in the Strategy design pattern, and you can find an excellent example in the Head First Design Patterns book.

I would suggest taking this advice into consideration and rethink your design.

I've been working on a small game off and on related to words for Windows using XNA 4.0 and C#. Words can be edited through a separate Windows Form editor (NOT XNA).

The Word class (which is serializable) contains the following objects:

    String WordName
    HashSet<String> PictureFilenames_Set; // this is a list of png file names for what the picture looks like
    HashSet<String> AudioFilenames_Set; // this is a list of wav file names for pronounciation

However, in the game, the pictures are loaded into Texture2D and the audio is loaded into SoundEffect objects.

I'm trying to design nice modular code by making sure that the Word class does not contain anything that does not intrinsically tie itself to XNA or how the graphics are displayed. That being said, I'm wondering how to go about creating the XNA specific portion.

Do you think something like this would be a good idea?

base class SpriteEntity
-- Position x, y
-- Scale
-- Display(gametime)
-- Logic(gametime)

base class SpriteEntity_2D : SpriteEntity
-- Int32 ActiveFrame
-- List<Texture2D> Textures;
-- override Display(gametime) { show the Texture2D }
-- override Logic(gametime) { ... }

NOTE: Do you think this is strange, having SpriteEntity and SpriteEntity_2D? I only did this so I could also have SpriteEntity_3D for 3d models.

class WordSprite : SpriteEntity_2D
-- ctor WordSprite (Word word)

So, for example, if there was an instance of a Word called `AppleWord` in which:
Word.WordName = "apple"
WordSprite apple = new WordSprite( AppleWord )

Then I can just set position and display it.
apple.X = ..., apple.Y = ...

In the WordSprite constructor it could check the Word.PictureFilenames_Set and use Texture2D.FromStream() to load them all in, but I feel like this is bad for two reasons:

  1. Loading exactly at the time of use could result in lag??
  2. Could end up loading more than one time.

I really want WordSprite to go check a custom ResourceManager, which contains a Dictionary class of the resource file names, would that be better?

But ideally, all of the possible resources should be loaded at the beginning.

Maybe I should have a method called LoadResourcesFromWordList( List<Word> wordlist ) which looks at the list of Words available in the game, and at that time, it should run through the files and call:

ResourceManager.LoadTexture2DResource( filename )
ResourceManager.LoadWaveFileResource( filename )

which loads everything into a Dictionary<object> Resources.

Than I can overload the [ ] index operator so that the user can just call:

ResourceManager[ name_of_resource ]

Then when you create a new WordSprite it will just do something like this in the ctor:

    foreach( string pictfile in Word.PictureFilenames_Set ) 
    { 
        WordTextureList.add( ResourceManager[pictfile] ) 
    }

Sorry about the HUGE LENGTH of this post, it was kind of a running train of thought. I'm really poor at creating nice modular designed code, and I always second guess myself. Does this seem okay from a OO design standpoint or am I overcomplicating things?

Thanks very much for your assistance!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

-- zoombini

P.S. Can anyone recommend a good book which addresses things like modularity, design, OO from a game designer's perspective? It doesn't necessarily have to be related to C# or XNA.

I wouldn't worry about having SpriteEntity_2D and SpriteEntity_3d as separate classes. I think your overall design is pretty good but it is hard to say without knowing the full extent of the project. If you haven't already, you should read about component based systems for games. There is some good stuff here: Component based game engine design

Also, a good book on design(not specifically related to gaming) is http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=sr_1_sc_1?s=books&ie=UTF8&qid=1326855704&sr=1-1-spell

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

Let me start by saying that I got this program working, so all I'm looking for is an explanation of why it works. It was one of those, "Well, maybe this will do it..." moments.

This was a homework assignment, to show method overriding. The three files are at [Pastebin] (http://pastebin.com/u/Stephonovich). UseCarRental is the main class, LuxuryCarRental is the one overriding CarRental.

Currently, in main(), I have this block:

rentalCar.setName(name);
rentalCar.setZip(zip);
rentalCar.setCarSize(carSize);
rentalCar.setRentalLength(rentalLength);

    if (carSize.toUpperCase().charAt(0) == 'L') // Send the below to LuxuryCarRental 
    {
        luxuryRentalCar.setName(name);
        luxuryRentalCar.setCarSize(carSize);
        luxuryRentalCar.setRentalLength(rentalLength);
        luxuryRentalCar.setZip(zip);
        luxuryRentalCar.display();
    }
else rentalCar.display();

Previously, I only had this:

rentalCar.setName(name);
rentalCar.setZip(zip);
rentalCar.setCarSize(carSize);
rentalCar.setRentalLength(rentalLength);

    if (carSize.toUpperCase().charAt(0) == 'L')
    {
        luxuryRentalCar.display();
    }

else rentalCar.display();

My thought was that since LuxuryCarRental was just using the same gets as UseCarRental, the same values should be there. The display() portion of LuxuryCarRental is shown here:

void display()
{
    chauffeurSelect(); 
    setCarSize("Luxury"); // Seems easier to do it directly here

    totalFee = dailyFee * getRentalLength();
    System.out.println("\nRental summary");
    System.out.println("\n" + getName());
    System.out.println("ZIP code " + getZip());
    System.out.println(getCarSize() + 
            " at $" + getDailyFee() + 
            " for " + getRentalLength() + " days" + 
            " for a total of $" + getTotalFee()); 
}

When I ran this with the older portion of main() as shown above, I would get null name, 0 ZIP, Luxury car size, $79.99 daily fee, 0 rental length, 0 total fee. I understand why I was getting those values; the only thing that was being locally declared was the daily fee, and the car size. I don't understand why LuxuryCarRental couldn't pull in the name and other values without the dedicated set. Unless I'm horribly off (very possible), the second block will go through line by line, sending the values to the respective variables, and then as it gets to the if block, it would be true if Luxury was selected, and therefore go to the display() block of that file. That block, listed above, references the same gets that CarRentalUse does.

Any help in understanding / other critiques is appreciated.

As @bennyvnq stated, there are two different references to two different objects declared in your main method (i.e. rentalCar and luxuryRentalCar). Classes are different to objects and you can declare as many objects as you want from a class and they will be completely separate from each other except for any static members which will be shared between all the objects of the class (including derived classes).

Read up on polymorphism and design patterns (http://www.amazon.com/Head-First-Design-Patterns-Freeman/dp/0596007124) and see if you can change the design of your program. A hint would be to have a RentalCar class that instead of having other classes derive from it, it has fields that are using inheritance and polymorphism to differ behaviour. For example, the RentalCar class might have a DriverType field with DriverType being an interface. You would then have other classes which implement this interface like ChauffeurDriven and SelfDriven that define the differences between the different types of cars. This way, you only have one RentalCar class, and many derived DriverType classes and the design becomes much more robust. In your program you would then have only one RentalCar object which is declared at the beginning of the program and instantiated along with the correct DriverType after user input.

I hope this isn't too confusing but if you can get your head around it and start to use principles like this life becomes much easier!

My team would like to spend some time at lunch learning design patterns. Previously, we watched some videos on Javascript which we found very useful as a way to start discussions. We would like to do the same thing with design patterns so that we don't have to spend a lot of time (outside of work) researching individual patterns in order to give a presentation.

I did a little searching and came up fairly empty handed. Any help would be appreciated. It doesn't even have to be a video, even something that we can listen to (maybe a book on tape even).

Well, it is a book... but it is great. Head First Design Patterns

Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim json = js.Deserialize(Of jsonTest)(e.Result)
With json
'do stuff with object
End With



Private Class jsonTest
    Public Artist As String
    Public Album As String
    Public Track As String
    Public Duration As String
End Class

I managed to get this to work. However, I can't get it to work for multiple results.

Here's an example of my JSON output. How would I return multiple sets? "album" : "Move Along", "albumpos" : 1, "artist" : "The All American Rejects", "bitrate" : 128, "duration" : 195, "playing" : true, "position" : 101, "resolvedBy" : "DatabaseResolver", "score" : 1.0, "track" : "Track 01"

Ok, "multiple results" can mean a bunch of things. That's why nobody has given you a straight answer yet.

I THINK - you are asking about the idea of collections and sets on the server side. In other words, how do I return a json result set that looks like this (a json array):

[
{"Artist": "AMR", Album:"I Have No Idea", "Track": "Track 01", Duration: 195},
{"Artist": "AMR", Album:"I Have No Idea", "Track": "Track 02", Duration: 500},
{"Artist": "AMR", Album:"I Have No Idea", "Track": "Track 03", Duration: 400},
...
]

Then, If I'd REALLY like to return these various tracks grouped by album (or search phrase or some other arbitrary group), how do I return a result set that looks like this (an array of objects):

[
{"The All-American Rejects": [{"Artist":"AMR", ...}, {Artist:"AMR", ...}]}
{"Move Along": [{"Artist":"AMR", ...}, {Artist:"AMR", ...}]}
{"When the Work Comes Down": [{"Artist":"AMR", ...}, {Artist:"AMR", ...}]}
...
]

If that's NOT the intent of your question, then stop reading here. If it is, then you are looking for 2 objects in your VB code: a LIST and a DICTIONARY. Your class will hold the data for one and only one track. LIST and DICTIONARY are both standard collections within the language (a smarter sexier version of an array).

Let's rearrange, rename some of your code so that we use a List (and some names that make sense)...

Private Class Track
    Public Property Artist As String
    Public Property Album As String
    Public Property Track As String
    Public Property Duration As String
End Class

'CREATE MY LIST OF OBJECTS HERE
dim Album1 as new List(of Track)
Album1.Add(New Track() with {
    .Artist = "AMR",
    .Album = "The All American Rejects",
    .Track = "Track 01",
    .Duration = 910
})
Album1.Add(New Track() with {
    ... add track info again...
})
... add yet more track info ...

Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim json = js.Deserialize(Of List(of Track))(Album1)
... do whatever you'd like next ...

See how we messed with your Deserialize code?

js.Deserialize(Of List(of Track))(Album1)

Now, instead of deserializing 1 result, we are deserializing a LIST OF results. That code will give you the first result set (more or less). OK. Cool. So how do we return multiple albums? For that little trick, use a dictionary.

To create a list of tracks, the vb.net code is similar, but we use a dictionary AND a list:

'CREATE MY LIST OF OBJECTS HERE

dim results as new Dictionary(of string, of List(of Track))

dim Album1 as new List(of Track)
Album1.Add(New Track() with {
    .Artist = "AMR",
    .Album = "The All American Rejects",
    .Track = "Track 01",
    .Duration = 910
})
Album1.Add(New Track() with {
    ... add track info again...
})
... add yet more track info ...

results.Add("The All American Rejects", Album1)

... do the same thing with the next album ...
results.Add("MoveAlong", Album2)

Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim json = js.Deserialize(Of Dictionary(of string, List(of Track)))(results)
... do whatever you'd like next ...

That code will return that second set of json data that we outlined, like, 10,000 words ago.

IF this is the direction you wanted to head, then take a look at all the collections available at the server level, and maybe take a look at how to create properties from those collections. Those objects are where most of your "real" server code is going to live. And, if you code them correctly, serializing them (to json, to the database, to XML, etc) will be almost trivial!

Start by building on your Track class. Create an album class that looks like the one below and then populate it, serialize it and see what the result set looks like:

Public class Album
    Public Property Name as String,
    Public Property ReleaseDt as DateTime,
    Public Property Tracks as List(of Track) = New List(of Track)
End Class

Hope that's what you were looking for. If it is, then stop right here. Go no further. Take one half-step backward and read a decent intro to Design Patterns. It'll get you used to working with Interfaces and objects and inheritance. And THAT will make any server-side code you write stunningly beautiful. Like ... drop dead sexy. Trust me. It's worth the time.

Good luck with the project.

Should a class implement an interface always in order to enforce a sort of 'contract' on the class?

When shouldn't a class implement an interface?

Edit: Meaning, when is it worthwhile to have a class implement an interface? Why not have a class just have public members and private members with various accessor/setter functions?

(Note: Not talking about COM)

You may not always want an interface. Consider you can accomplish similar tasks with a delegate. In Java I used the Runnable Interface for multithreaded applications. Now that I program in .NET I rely a lot on delegates to accomplish my mulithreaded applications. This article helps explains the need for an Delegate vs an Interface.

When to Use Delegates Instead of Interfaces (C# Programming Guide)

Delegates provide a little more flexibility as in Java I found that any task that I accomplished in C with a function pointer now required incasulation with an an Interface.

Although, there are lots of circumstances for an Interface. Consider IEnumerable, it is designed to allow you to iterate over various collection without needing to understand how the underlying code works. Interfaces are great for when you need need to exchange one class for another but require a similar Interface. ICollection and IList provide a set of similar functionality to accomplish an operation on a collection without worrying about the specifics.

If you would like to better understand Interfaces I suggest you read "Head First Design Patterns".

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.

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.

While i was going through the book Head first design pattern i found that "Abstract factory relies on object composition: object creation is implemented in methods exposed in the factory interface" in the abstract factory chapter. My doubt here is how come Abstract factory relies on object composition?

if i will take the example in wikipedia then GUIFactory is an interface and WinFactory implements GUIFactory. Then how Abstract factory uses composition. Thanks in advance.

You know, some of the GOF patterns like Singleton or prototype are pretty simple. But some of them like factory method is clearly complicated.

What is your advice for understanding them quickly?

Try reading Head First Design Patterns first. You'll find it's a much gentler introduction if GOF is over your head.

Can some please suggest a good book or resource where I can learn Object Oriented Design principles.

I am designing a software product (both web based and in Android), and I find to hard to get some good material on how to design software systems.

I am aware of Design Patterns, but I not sure of which one to use when.

Thanks in advance.
Kanna

The best book I know about OOP is Object Oriented Software Construction by Meyer, he explains each of his choice or recommendations. He is sometimes provocative but he is one of the few who state clearly his reasonning. So many just say it is good practive and leave at that. Very good book.

An alternative is A Touch of Class by the same author which is cheaper but focus on the same topics.

About design patterns, I suppose the best book is Head first design Patterns, it is a list of well crafted case studies, each being a good example for a design pattern. Not a deep book, but one which communicate very efficiently and fast to read.

Consider struts + spring + jpa for these technology one decide that he need a service locator design pattern, sessionfacade and so on....

my question is where can i find or figure out the best design pattern that are used to develop projects?

like any forum where developer sharing there experience on how they faced problem while integrating some technologies and what design pattern they used to solve those issues

A short quote from Head First - Design Patterns:

Design patterns don't go directly into your code, they first go into your BRAIN. Once you've loaded your brain with a good working knowledge of patterns, you can start to apply them to your new designs, and rework your old code when you find it's degrading into an inflexible mess of jungle spaghetti code.

First look at the project, think of a top-level design that fits the real world requirements. Then (with your brain loaded with patterns) you'll see the patterns inside the design and will know which patterns to use.

Please, don't build your design around beautiful patterns. With one exception: The technology, you've mentioned, comes with some best practice patterns. You should know them and use them (most of them are build in the frameworks anyway and you can't avoid using them). For those you should know and use them, because others expect those patterns when the see a design based on spring, JPA, J2EE, ...

I have this doubt in Java: when people are writing an event listener they implement an interface and they define a particular function in the interface to achieve a particular task. My doubt is instead of implementing an interface can we just define the function with the an appropriate name.

Also, how interfaces help in achieving event listeners?

The Listener interface gives you a lot a implementation freedom.

This way you don't have to implement a specific function in a specific class. Though implementing an interface seemes to be the same, it isn't. The functionality of a listener is just still ja single function, but the function is usualy in a lightweight object. Yet you are able to implement a lot of program mechanics inside a listener, if you need to.

Also, you can change the listeners at runtime. You can't change an overriden function.

There are a lot of good reasons to use composition (over inheritance) here.

If you really want to understand this, I encourage you to look inside "Heads first: Design Patterns". The "look inside" feature of amazon contains the complete chapter 1, which explains this pattern greatly.

I'm on the stage of learning cakephp, which is a OO based framework, but i have not a good understanding of OO. I come from C procedural field.

I need something which can help me think in OO perspective. Can you advicxe me about what can I do/read/watch.... in order to help me think in OO.

Head First: Object Oriented Analysis and Design is a very good book which may be followed by Head First: Design Patterns from the same series.