Applying UML and Patterns

Craig Larman

Mentioned 38

This third edition again delivers a clear path for students and professionals to learn and apply object-oriented analysis and design.

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 want to demonstrate use of Adapter Pattern to my team. I've read many books and articles online. Everyone is citing an example which are useful to understand the concept (Shape, Memory Card, Electronic Adapter etc.), but there is no real case study.

Can you please share any case study of Adapter Pattern?

p.s. I tried searching existing questions on stackoverflow, but did not find the answer so posting it as a new question. If you know there's already an answer for this, then please redirect.

Many examples of Adapter are trivial or unrealistic (Rectangle vs. LegacyRectangle, Ratchet vs. Socket, SquarePeg vs RoundPeg, Duck vs. Turkey). Worse, many don't show multiple Adapters for different Adaptees (someone cited Java's Arrays.asList as an example of the adapter pattern). Adapting an interface of only one class to work with another seems a weak example of the GoF Adapter pattern. This pattern uses inheritance and polymorphism, so one would expect a good example to show multiple implementations of adapters for different adaptees.

The best example I found is in Chapter 26 of Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition). The following images are from the instructor material provided on an FTP site for the book.

The first one shows how an application can use multiple implementations (adaptees) that are functionally similar (e.g., tax calculators, accounting modules, credit authorization services, etc.) but have different APIs. We want to avoid hard-coding our domain-layer code to handle the different possible ways to calculate tax, post sales, authorize credit card requests, etc. Those are all external modules that might vary, and for which we can't modify the code. The adapter allows us to do the hard-coding in the adapter, whereas our domain-layer code always uses the same interface (the IWhateverAdapter interface).

Fig. 26.1

We don't see in the above figure the actual adaptees. However, the following figure shows how a polymorphic call to postSale(...) in the IAccountingAdapter interface is made, which results in a posting of the sale via SOAP to an SAP system.

Fig. 26.2

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

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

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

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

Tips/books/articles/blogs?

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

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

Head First Object-Oriented Analysis and Design

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

The book covers:

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

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

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

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

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

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

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

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

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

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

The Object-Oriented Thought Process

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

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

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

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

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

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

My questions are:

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

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

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

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

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

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

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

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

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

File Structures: An object oriented approach with C++

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

Also make sure to get a book on compilers

Biggest two omissions I see:

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

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

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

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

And let's not forget some database theory books!

I'm going to start learning and using UML.

I need to know what considerations do you suggest for me? What is the best way to learn effectively it do you think?

Thank you

I read Martin Fowler's UML Distilled. That's all you need. It's thin, dense book that's unmatched on that topic.

UML Distilled by Martin Fowler together with Applying UML And Patterns by Craig Larman, makes you understand the concept of UML and how to use it - as well the whole process with UP and so forth.

Although I have a somewhat solid ground on object oriented theory and know how to build something as simple as a tetris / tic tac toe game in a "evolutive" design with no major trouble, I'd like to learn how to take the totally different approach of first designing the system and only them trying to implement it.

I am looking for something that'll teach me how to take a problem (for example, a tic tac toe game) and learn how to make its uml design (object domain model -> system sequence diagrams and finally communication diagrams).

I'm looking for something like a workbook that has a bit of theory, examples, exercises and solutions (if possible).

I know people generally recommend UML and Patterns but I've had it in my OO course and found it awful.

The famous coffee maker problem from Martin Fowler.

Finally buy this book specifically for its treatment of the GRASP principles

Despite having studied Domain Driven Design for a long time now there are still some basics that I simply figure out.

It seems that every time I try to design a rich domain layer, I still need a lot of Domain Services or a thick Application Layer, and I end up with a bunch of near-anemic domain entities with no real logic in them, apart from "GetTotalAmount" and the like. The key issue is that entities aren't aware of external stuff, and it's bad practice to inject anything into entities.

Let me give some examples:

1. A user signs up for a service. The user is persisted in the database, a file is generated and saved (needed for the user account), and a confirmation email is sent.

The example with the confirmation email has been discussed heavily in other threads, but with no real conclusion. Some suggest putting the logic in an application service that gets an EmailService and FileService injected from the infrastructure layer. But then I would have business logic outside of the domain, right? Others suggest creating a domain service that gets the infrastructure services injected - but in that case I would need to have the interfaces of the infrastructure services inside the domain layer (IEmailService and IFileService) which doesn't look too good either (because the domain layer cannot reference the infrastructure layer). And others suggest implementing Udi Dahan's Domain Events and then having the EmailService and FileService subscribe to those events. But that seems like a very loose implementation - and what happens if the services fail? Please let me know what you think is the right solution here.

2. A song is purchased from a digital music store. The shopping cart is emptied. The purchase is persisted. The payment service is called. An email confirmation is sent.

Ok, this might be related to the first example. The question here is, who is responsible for orchestrating this transaction? Of course I could put everything in the MVC controller with injected services. But if I want real DDD all business logic should be in the domain. But which entity should have the "Purchase" method? Song.Purchase()? Order.Purchase()? OrderProcessor.Purchase() (domain service)? ShoppingCartService.Purchase() (application service?)

This is a case where I think it's very hard to use real business logic inside the domain entities. If it's not good practice to inject anything into the entities, how can they ever do other stuff than checking its own (and its aggregate's) state?

I hope these examples are clear enough to show the issues I'm dealing with.

Big part of you requests are related to object oriented design and responsibility assignment, you can think of GRASP Patterns and This, you can benefit from object oriented design books, recommend the following

Applying UML and Patterns

A user signs up for a service. The user is persisted in the database, a file is generated and saved (needed for the user account), and a confirmation email is sent.

You can apply Dependency Inversion Principle here. Define a domain interface like this:

void ICanSendConfirmationEmail(EmailAddress address, ...)

or

void ICanNotifyUserOfSuccessfulRegistration(EmailAddress address, ...)

Interface can be used by other domain classes. Implement this interface in infrastructure layer, using real SMTP classes. Inject this implementation on application startup. This way you stated business intent in domain code and your domain logic does not have direct reference to SMTP infrastructure. The key here is the name of the interface, it should be based on Ubiquitous Language.

A song is purchased from a digital music store. The shopping cart is emptied. The purchase is persisted. The payment service is called. An email confirmation is sent. Ok, this might be related to the first example. The question here is, who is responsible for orchestrating this transaction?

Use OOP best practices to assign responsibilities (GRASP and SOLID). Unit testing and refactoring will give you a design feedback. Orchestration itself can be part of thin Application Layer. From DDD Layered Architecture:

Application Layer: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems.

This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.

My question is related to this one: Python tool that builds a dependency diagram for methods of a class.

After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like this.

At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?

It's often not possible to say whats 'correct' or 'wrong' when it comes to class design. There are many guidelines, patterns, recommendation etc. about this topic, but at the end of the day, imho, it's a lot about experience with past projects. My experience is that it's best to not worry to much about it, and gradually improve your code/structure in small steps. Experiment and see how some ideas/changes feel/look like. And it's of course always a good idea to learn from others. read a lot of code and analyse it, try to understand :).

If you wanna read about the theory I can recommend Craig Larmanns 'Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development' Amazon. He covers several parts of your question, gives some rough guidlines and shows them using an example application. I liked the book.

Could you upload your app somewhere? Perhaps on github or so, perhaps you could ask for some concrete advices.

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

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

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

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

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

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

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

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

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

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

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

I am currently half-way through the following book:

http://www.amazon.com/Applying-UML-Patterns-Introduction-Object-Oriented/dp/0131489062

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

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

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

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

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

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

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

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

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

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

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

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

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

I'm developing cross-platform project that would support :

  • Four C++ compilers - GCC, MSVC, SunStudio, Intel,
  • Five Operating Systems: Linux, OpenSolaris, FreeBSD, Windows, Mac OS X.

I totally understand that without proper unit testing there is no chance to perform proper QA on all these platforms.

However, as you all know writing unit tests is extremely boring and slow down development process (because it is boring and development of FOSS software shouldn't be such)

How do you manage to write good unit-testing code and not stop writing code.

If you at least get salary for this, you can say - at least I get something for this, but if you don't, this is much harder!

Clarification:

I understand that TDD should be the key, but TDD has following very strict restrictions:

  1. You have exact specifications.
  2. You have fully defined API.

This is true for project that is developed in customer-provider style, but it can't be done for project that evolves.

Sometimes to decide what feature do I need, I have to create something and understand if it works well, if API is suitable and helps me or it is ugly and does not satisfy me.

I see the development process more like evolution, less development according to specifications. Because when I begin implementing some feature, sometimes I do not know if it would work well and what model would it use.

This is quite different style of development that contradicts TDD.

On the other hand, support of wide range of systems requires unit tests to make sure that existing code works on various platform and if I want to support new one I only need to compile the code and run tests.

As others have told you: writing the tests first makes it fun. Your statements that it can't be done for a project that evolves need to be reconsidered. Actually the opposite is true. If you are going the agile route, you are highly discouraged to define everything up front. TDD fits in a paradigm that this is impossible and that change will happen. A book that makes this very clear, and gives examples of this is applying uml and patterns.

Even though I've been programming for quite a while now, when it comes to coupling objects I always seem to bang my head against the wall so I'm wondering if anyone has any resources or golden rules I can follow.

Let me give a small example, in no particular language...

class Person {
    private int personnel_id
    private String first_name;
    private String last_name;
    private int personnel_level;
    //Lab labs[4]; <- Lab(s) the Person works in
}

class Lab {
    private int lab_id;
    private String lab_name;
    //Person[99] personnel; <- Person(s) working in the Lab
}

Lets ignore ctors/setters/getters/dtors for now and just instantiate some stuff...

Person people = new Person[1500];
Lab labs = new Lab[10];

My question is.. what's the best practice here...

people["Gordon Freeman"].blewUp((Lab)"Black Mesa");
-> returns T/F

or...

labs["BlackMesa"].blownUpBy((Person)"Gordon Freeman");
-> returns T/F

or maybe it doesn't even matter :S

The real-life example I'm working on is a ton more complex. Whenever the Person does something, everyone in the Lab needs to be notified, etc, and I'm just trying to figure out if there are any principles I can apply here.

I am not entirely sure what your example means, but an

An excellent book that has what you want in it is Applying UML and Patterns by Craig Larman.

The book talks extensively about assigning responsibilities. For example, you might use the Information Expert pattern, in which case, the object that has the most knowledge of the variables involved will be the one that is given the responsibility of having the method.

I have looked at a couple of books and all I have looked at were just discussing the technicalities of OOP. By technicalities I mean, here's a concept, here's some code, now get working. I have yet to see a book that discusses the architectural process, what are the ways of doing this, why doing this is bad, how to actually incorporate design patterns in a real-world project, etc.

Can you recommend a good resource or book? I am mainly programming with PHP but a language-agnostic book/resource would do :)

I've had The Object-Oriented Thought Process on my wishlist for a few months, but I haven't got my hands on it yet. The reviews and snippets I've seen are positive, though. You'd need to supplement it with language-specific details from the PHP reference on Classes and Objects, but I think most of the fundamentals should translate well enough, provided you can port the examples.

Edit: Oops. If you're looking for something more advanced, I've also got these two on my list:

I like Craig Larman's Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition). Most PHP programmers would do well to learn habits like design patterns and GRASP.

You could also "keep it in the family" and read the free online book Building Skills in Object-Oriented Design by Stack Overflow top-ten scorer Steven Lott.

I'm writing a game where the mouse-driven controller object clicks on a player object to have it do something.

There are 2 ways of initiating the interaction between mouse and player:

  • Controller calls player's function:
    Controller listens for mouse events. When a mouse click occurs anywhere onscreen, the controller searches all objects under the point that was clicked. If one of the objects is a player object, and it's "clickable" property is true, then call its appropriate function.
  • Player calls controller's function:
    Player listens for mouse events. When a mouse click occurs on the player, and the player's own "clickable" property is true, then call the controller's appropriate function.

My dilemma here is that the first option seems more intuitive with how I imagine the scenario happening in the real world, but the second option seems more intuitive with proper object-oriented design because it doesn't require looking into another object's property, which violates encapsulation to some extent (the controller must look into the player to read its "clickable" property). Also, the second option seems inline with the 'Controller' design pattern.

This is always a struggle for me -- do I defy proper object-oriented design (e.g. option 1) or do I use an implementation that seems counterintuitive to the real world (e.g. option 2)?

I'm hoping there's some kind of middle ground I'm missing.

This is always a struggle for me -- do I defy proper object-oriented design (e.g. option 1) or do I use an implementation that seems counterintuitive to the real world (e.g. option 2)?

Reality may be a good starting point for molding or evolving a design, but it is always a mistake to model an OO design to reality.

OO design is about interfaces, the objects that implement them, and the interaction between those objects (the messages they pass between them). Interfaces are contractual agreements between two components, modules, or software sub-systems. There are many qualities to an OO design but the most important quality to me is substitution. If I have an interface then the implementing code better adhere to it. But more importantly, if the implementation is swapped then the new implementation better adhere to it. Lastly, if the implementation is meant to be polymorphic then the various strategies and states of the polymorphic implementation better adhere to it.

Example 1

In mathematics a square is a rectangle. Sounds like a good idea to inherit class Square from class Rectangle. You do it and it leads to ruin. Why? Because the client's expectation or belief was violated. Width and height can vary idependently but Square violates that contract. I had a rectangle of dimension (10, 10) and I set the width to 20. Now I think I have a rectangle of dimension (20, 10) but the actual instance is a square instance with dimensions (20, 20) and I, the client, am in for a real big surprise. So now we have a violation of the Principle of Least Surprise.

Now you have buggy behavior, which leads to client code becoming complex as if statements are needed to work around the buggy behavior. You may also find your client code requiring RTTI to work around the buggy behavior by testing for conrete types (I have a reference to Rectange but I have to check if it is really a Square instance).

Example 2

In real life animals can be carnivores or herbivores. In real life meat and vegetables are food types. So you might think it is a good idea to have class Animal as a parent class for different animal types. You also think it is a good idea to have a FoodType parent class for class Meat and class Vegetable. Finally, you have class Animal sport a method called eat(), which accepts a FoodType as a formal argument.

Everything compiles, passes static analysis, and links. You run your program. What happens at runtime when a sub type of Animal, say a herbivore, recieves a FoodType that is an instance of the Meat class? Welcome to the world of covarience and contravarience. This is a problem for many programming languages. It's also an interesting and challenging problem for language designers.

In Conclusion...

So what do you do? You start with your problem domain, your user stories, your use cases, and your requirements. Let them drive design. Let them help you discover the entities you need to model into classes and interfaces. When you do you'll find that the end result isn't based on reality.

Check out Analysis Patterns by Martin Fowler. In there you'll see what drives his Object Oriented designs. It is mainly based on how his clients (medical people, financial people, etc.) perform their daily tasks. It has overlap with reality, but it isn't based or driven by reality.

According to Applying UML and Patterns (Craig Larman) the User Interface (your mouse events) should never interact with your application classes, that is, the user interface should never drive the business logic directly.

Instead one or several controllers should be defined to act as a middle layer to the user interface, so option 1 does in fact follow a good object oriented approach.

If you think about it, it does make sense to couple as fewer classes as possible to the UI in order to make business logic as independent of the UI as possible.

If I`m programming a game in which there is a worker that cuts wood (from trees), where would I put the "cutWood" method, in the worker class, or the tree class?

EDIT: The first example I read on OOD was about a circle (a class called circle) which has in it a method called "calculate area". Now, sure enough a circle doesn't calculate its own area. The only way to think of it is that calculating area is an operation that is relevant to the circle (an operation done on the circle)

So, cutWood method is relevant to both, the worker, and the tree.

Object design is all about assigning responsibilities to your classes. That means there really is no good answer to this question. As it all depends how you model the responsibilities in your design. (see: Larman)

Thus you need to decide what object/class is responsible for what. This will lead you to correct answers on question about were to place what kind of methods.

Thus ask you’re selves questions like: does the worker decide on his own to cut wood? If he does, he probably does not need to be ordered so, thus he will not have a need for a method cut(tree). But if the user can order him to do that, he will need a cut(tree) method. An other example: does the tree have to know he is cut? Well, if a cut tree just leads to his removal from the forrest, he might not have a need for such a tree.cut() method. But if you assign to the tree the responsibility to (re)draw himself during cutting, you might have a need for a tree.cut() method. The tree could even be modeled as having a width and that he can calculate how many cuts are needed before he collapses.

Introduction to the problem

I have been taught about OO Analysis and Design through Craig Larman's Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development, that follows the UP(Unified Process).

When using it, we usually draw a Domain Model and from it, doing Interaction/Association Diagrams, we get to the Class Diagrams. We generally then make Controllers that will be the "gate" between our Model and the "outside World" (following the GRASP patterns). All the world accesses to do any kind of logic has to go through the Controllers. I'll call those Controllers Model's Controllers, so later when we talk about MVC's Controllers we can differentiate them. That can be depicted in the following most awesome diagram:

alt text

In black we have our Model's objects and that classes' associations. In red we have the Model Controllers, that use data from the Model.

Basically, following this kind of design, you can only work with the Model through the so called Model's Controllers (we usually had one Controller per Use Case!).

Now the question itself

When learning about the MVC, I always had the question of wherever the MVC's Controller was in fact Model's Controller or not? Are they the same concept or not? I think they are different concepts, as the Model Controllers we used to do didn't ever know about anything other than the classes on our Model, which is not what seems to happen in MVC's Controllers.

If what I'm saying is true, the following diagram should make sense:

alt text

Am I right?

I think I understand what you are talking about :)

What you are calling Model Controllers are known as Repositories. This is an interface that defines your specific interactions with the underlying model. For example, if you had a class representing Employees, and you wanted to do three things:

  • List<Employee> List()
  • Add(int employeeID)
  • Delete(int employeeID)

Then you would define an interface called something like:

public interface IEmployeeRepository
{
    List<Employee> List();
    void Add(int employeeID);
    void Delete(int employeeID);
}

You would make sure that all your code deals with the Interface, and not the object directly - the Repository Pattern. This is what you are calling a Model Controller. See http://www.dev102.com/2008/12/08/working-with-aspnet-mvc-part-2-the-model-and-the-repository-pattern/ for more details, or search on Repository Pattern.

A contoller in the MVC world is actually something that dictates logic of program flow. For example, say you had a view of a list of employees. When the user hits "Delete" button on this view, the controller would load the appropriate repository and call the Delete method on it.

tl;dr: MVC Controller = When user does this, do this in a program (program logic); Repository (Model Controllers) = Define what interactions are supported with objects in my model

And yes, you're right :)

I'm trying to move into OOP development and am turning to here as I'm sick of searching the web and finding only the very basic information about what classes are and how they can inherit from each other - that I understand.

What I don't understand as yet is how all these classes can be stored in different files, doted around a folder structure, and yet all you need to do to use the class is just mention its name in your code. How does this work exactly?

And on a related note, if anyone can recommend a good book or online tutorial which will provide a good foundation in OOP (preferably php based) I'd be very grateful.

And on a related note, if anyone can recommend a good book or online tutorial which will provide a good foundation in OOP (preferably php based) I'd be very grateful.

Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development

Recently I got requests from potential clients for very complex web applications.
They wanted me to write a spec before the "real" works begins.
The spec, as they see it should only be words describing the app and DB.
Where I found the best approach is to "paint" or "build" a prototype of the screens the application will have (html is easier then writing a book, especially if you use WYSIWYG just for this phase...standards are not important at this point).

When you have a screen in front of your eyes, it becomes immediately clear what elements should be (calender/photo galleries/ what major links, search box etc)

So, am I wrong in my approach? Or are the customers bad-informed on the correct way to do things?

The user interface is not the most important part of the app, focusing on this part so early might lead to false assumptions and impose choices based on interface, not on functionality.

I suggest focusing on functionality first, in order to agree what the app is expected to do, not how it will look on the screen. The interface will change in time, the client will want this button to the left not on the right, colored blue, not yellow, this text box larger and a different font, these are details for later, if you provide an interface with the specs you risk discussing those minor details instead of the important functionalities.

Take a look over Applying UML and Patterns, I think it might be useful. One of the books from the "Extreme Programming" series was also nice, I'll check later which one exactly.

Not a book that talks about how to code but more high level organization of software.

Though perhaps it is not strictly architecture-related (although I believe you'll find that most prescriptions of architecture patterns are mere guidelines at best, and far from comprehensive), Steve McConnell's Code Complete is truly required reading. More importantly than teaching you design patterns, it will teach you to be a better programmer so that you can make these kinds of decisions for yourself.

General Responsibility Assignment Software Principles and Domain Driven Design are in my opinion are the next must have things you should get familiar with after learning to code. API Design is also a good read, especially when you are developing the software that will be used/extended by multiple people.

I am not in favor of learning patterns as it is EASIER to misuse them if the intention is not understood correctly. (Everything seems like a nail if you have a hammer kind of thing). I have nothing against patterns but I have seen it mostly misused by the junior developers thus creating hard to maintain products.

I am writing a BFS and DFS in Java. What I was hoping to do was create one class like this:

/** Preforms BFS and DFS on ...
*/
public class Search{


  private XXX toSearch;
  // where XXX is an interface of Stack and LinkedList that has
  // remove() and add() methods.  

  public Search(boolean isBFS){
    if(isBFS)
      toSearch = new LinkedList();
    else
      toSearch = new Stack();
  }

  public void preformSearch(){
    while(toSearch.size() > 0){
      preformSearchOn(toSearch.remove());  // <----- KEY LINE
    }
  }

  private void preformSearchOn(...){...}

}

This class can perform BFS and DFS depending on how it is initialized. What is XXX? I don't think that it exists.

I thought that the entire point of object oriented programing is being able to do cool stuff like this.

What is the cleanest way to handle this?

XXX should be of type java.util.AbstractList as both LinkedList and Stack are derived from it.

But that will not solve you're problem, as the remove() method for each class will behave the same way. In order to get different behaviour you will actual need to call the different removale methods: remove() or pop(). And as method these remove() and pop() are both implemented on java.util.Linkedlist (see Queue interface) there is no need to use the java.util.Stack class either.

You could do call the different methods pop() and remove() with in an if statement, but that would be definitly be an OO anti pateern. An basic OO solution would be to implement 3 classes:

  • Abstract parent named Search Class
  • BfsSearch: works with remove() in it's search.
  • DfsSearch: works with pop() in it's search.

This way, the user of this class can work with Search without needing to know if he is using BfsSearch or DfsSearch.

An even more advanced and flexible OO approach would be to use the Strategy pattern as described by mike. But for simple solutions that don't need this kind of flexibility it might be overkill.

BTW an excelent book on OO design that will explain all these kind of choices and patterns is Larman:

Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)

What is the idea behind Grasp's Controller pattern?

My current interpretation is that sometimes you want to achieve something that needs to use a couple of classes but none of those classes could or has access to the information needed to do it, so you create a new class that does the job, having references to all the needed classes(this is, could be the information expert).

Is this a correct view of what Grasp's Controller is about?

Generally when googling or SO'ing controller, I just get results about MVC's (and whatnot) which are topics that I don't understand about, so I'd like answers that don't assume I know ASP.NET's MVC or something :(

Thanks

According to Wikipedia:

A Controller object is a non-user interface object responsible for receiving or handling a system event.

From Applying UML and Patterns:

What first object beyond the UI layer first receives and coordinates ("controls") a system operation?

Controllers, across the board - be it in MVC or GRASP or Patterns of EAA - are all about receiving input and responding to events.

I conceptualize it very literally: think of a video game controller. NES controller

It responds to input events - the user pressing buttons. It doesn't necessarily know what to do when you hit a button, but it at least receives the event.

Looking at the controller, one can easily figure out what the system events are - that is to say what inputs it responds to and how the user interacts with the system. On a Nintendo Controller, it's evident that system events are:

  • Press A
  • Press B
  • Press X
  • Press Y
  • Press
  • Press
  • Press
  • Press
  • Press L
  • Press R

If we were to take all these events and build a software controller to deal with them, it would be an MVC controller: these events are all concerned with the physical controller as presented to the user - it's "view", if you will. But there's a second layer of input events for most video games, where button mashing maps on to specific system operations. For example, if you're playing as Scorpion in Mortal Kombat 2, pressing ← ← B triggers one of your special moves. In that case, the system could need different controllers which deal with these different kinds of events:

UML diagram of various controller classes - a Button Controller with methods for each button press, and then various controller objects for different playable characters. Each player controller exposes methods corresponding to the character's special moves.

Here, the NES Button Controller is a MVC controller which would keep track of the state of UI elements - for example, remembering what buttons were pressed in what order. Depending on application state (see Application Controller - another one!) the NES Button Controller would response to certain button combinations by invoking methods on the other controllers - for example the Scorpion Controller - which are Use Case Controllers.

What's important is that by looking at the design of these controller objects, you can quickly and easily enumerate the system events they respond to.

Altogether, in the end, the MVC Controller is still a kind of GRASP Controller - as its methods tend to represent system events, which respond to user input. But there are other GRASP controllers which are not MVC controllers: Use Case controllers. A GRASP Use Case controller might respond to system events such as "user creates a new sale" while an MVC controller would respond to events like "system receives a PUT request for /sales/new" or "a java.awt.event.ActionEvent fires`".

..where do you begin?

As a basis for any design - for instance a package - where do you as a developer start.

I start by mapping out the requirements and breaking them down into sub categories and from this objects and methods.

Usually takes a while before I start drawing it out by hand - then that goes through a few versions. But I always have the underlying feeling I'm never finished and it could just be better. How can I overcome this?

And once I have my own design ideas I'm never sure how to incorporate design patterns into it.

How much time is justifiably spent designing for OO? (obviously it depends on the project at hand)

Might I suggest Peter Coad's Java Design as a good guide for doing OO/Java design? Something much more heavy weight and rigorous: http://www.amazon.com/Applying-UML-Patterns-Introduction-Object-Oriented/dp/0131489062/ref=sr_1_1?s=books&ie=UTF8&qid=1288364561&sr=1-1

As for starting with Reqs- I suggest writing brief use cases and tie reqs to them so the reqs are in context.

Consider the following scenario:

I want to design a discount calculator which gets me the discount that can be applied to an order. There are two types of order: Online and In-Store. Based on type of the order and total amount of the order, a discount calculator calculates the discount.

I programmed to demonstrate the scenario in C# but the problem is language independent. In the below code, DiscountCalculator class calculates the discount by examining the actual type of input parameter.

I feel checking the actual type of IOrder argument in GetDiscount method is code smell; because I hid the implementation details behind the interface IOrder, then I somehow bring out of the box what was meant to be hidden.

    interface IOrder
    {
        int GetTotalPrice();
    }

    class InStoreOrder : IOrder
    {
        public int GetTotalPrice() { // returns the price of order }
    }

    class OnlineOrder : IOrder
    {
        public int GetTotalPrice() { // returns the price of order }
    }

    class DiscountCalculator
    {
        public int GetDiscount(IOrder order)
        {
            Type orderType = order.GetType();
            if (orderType == typeof(OnlineOrder))
            {
                if (order.GetTotalPrice() < 100)
                    return 2;
                else
                    return 5;
            }
            if (orderType == typeof(InStoreOrder))
            {
                if (order.GetTotalPrice() < 100)
                    return 3;
                else
                    return 6;
            }
            else
                throw new Exception("Unknown order type:" + orderType.Name);
        }
    }

Any idea?

Update:

I really appreciate people collaborating on this. All of the solutions were not only enlightening but also brought an elegant way on the table.

BTW, since the time all of the answers assured me that the solution is not good, I was thinking to myself that Abstract Factory may be a good alternative. Why? Because we are dealing with a family of related objects: Order and DiscountCalculator.

Something like this:

Factory f = new FactoryRepo ("Online");
IOrder order = f.CreateItem();
IDiscountCalculator discounter = f.CreateDiscountCalculator();
....

This way, I think for future changes, as @Dhruv Rai Puri pointed out, Decorator pattern may be easily applied.

Any Idea?

The solution of Strategy was already proposed http://stackoverflow.com/a/32798708/1168342, but this answer has some advantages.

Discounts and Orders are common domain problems. This wheel has been reinvented a few times. I'll cite a solution from chapter 26 of Craig Larman's "Applying UML and Patterns" book:

Pricing Strategy classes (part of Figure 26.9)

In this solution, a Sale is like your Order and ISalePricingStrategy is like your DiscountCalculator.

ISalePricingStrategy is an application of the Strategy pattern (the name is in the interface), and Strategies are always attached to a context object. In this case, it's the Sale (or in yours, IOrder).

Mapping to your problem

Here's the UML of how I see your problem fitting into Larman's suggested use of pricing strategies:

Pricing Strategy applied

Both your cases are composite instances of the AbsoluteDiscountOverThresholdPricingStrategy if I understand properly. Let's take the code from your conditional for OnlineOrders:

if (order.GetTotalPrice() < 100)
  return 2;
else
  return 5;

This is like adding to your order two instances of

onlineOrder.addPricingStrategy(new AbsoluteDiscountOverThresholdPricingStrategy(2,0));  // orders under 100
onlineOrder.addPricingStrategy(new AbsoluteDiscountOverThresholdPricingStrategy(5,100));  // orders >= 100

So, Larman goes a step further and explains that you can combine such strategies using the Composite pattern. I'll apply it to your problem (the hint is in the add... method above):

Composite strategies per Larman, figure 26.14

The two classes I put in pink are optional. If you always give the best strategy to the customer (as in the pseudocode of the note I attached to GetTotalPrice) you don't need them. Larman explains you can go a step further and say that if more than one strategy applies, the calculation is either in favor of the store or the customer. Again, it's a question of instantiating the class and attaching it. The code to do this could be run from a "Configuration" menu command in your software.

The code to use this would look something like:

IOrder onlineOrder = new OnlineOrder();  //...
...
CompositePricingStrategy comp = new CompositePricingStrategy();
comp.add(new AbsoluteDiscountOverThresholdPricingStrategy(2,0));  // orders under 100
comp.add(new AbsoluteDiscountOverThresholdPricingStrategy(5,100));  // orders >= 100
onlineOrder.setPricingStrategy(comp);
// repeat as above for instoreOrders ...

There are more flexible ways again to do this, using factories. See Larman's book for very cool examples in Java/.NET.

Advantages

Since this answer is similar to another one, I want to explain some advantages of this method, even though it's more complicated. If you use GetTotal() in the discount logic, it has some advantages over GetDiscount():

  • GetTotal() handles (encapsulates) all the logic to calculate the total.
  • If multiple strategies apply (e.g., online orders get 5% discount, orders over $200 get 10% discount) you may want to code how this is handled. Larman gives an example using Composite pattern where again GetTotal() works impeccably without the client code having to do anything special.
  • You can extend other types of Strategies and instantiate them as needed. For example, for any order over $500 you can make the discount 50. It's a question of instantiating the new class in the code (not coding the logic).

I am interested in improving my designing capability (designing of classes with its properties, methods etc) for a given. i.e. How to decide what should be the classes, methods and properties?

Can you guys suggest me good material for improving on this?

I would recommend you to read up on some UML and design patterns. That gets you going with the thinking in "drawing" terms. You can also get a good grasp of a big class/object a lot easier.

One particular book that is good in this area. Applying UML and Patterns

I'm fairly new to programming and new to java, but I'd like to jump in the deep end with a little database driven website project. I've read quite a lot about requirements in the 'real world' requesting experience with Spring and Hibernate, so I have those installed on netbeans and a project created (if I hit run I get the default spring page). Now I just need a little guidance as to where to start designing my app (please tell me if I'm getting in a bit too over my head for a beginner!).

Should I start off with my classes? - create all my classes as they map to my database tables and decide which attributes and methods each will require?

Can anyone suggest any good books for maybe.. making a java based website from scratch (i.e. from design right through to deployment) that might be useful for a beginner?

Any help appreciated thanks.

Edit: since posting this I've found a brilliant book that fits my needs just right to get started. Firstly I tried both spring in action and hibernate in action - but found both to be a bit too heavy for my novice mind. Instead I got the Java EE 5 Development with Netbeans 6 book https://www.packtpub.com/java-ee5-development-with-netbeans-6/book and its been a great help. If you use netbeans and are in a similar position to me, I'd say pick it up!

Not trying to gut your goals, but if you are wondering whether to start with your classes, I would suggest you work on your programming skills more.

I'd suggest taking a look at Larman's "Applying UML & Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)" as well as a book on relational database theory (you need to know how to model databases properly.)

You can try your hand at building a database driven web app, and it might give you an insight into how to do it, but you need have some programming maturity to take those skills into the non-trivial.

This is a completely personal opinion so please take it with a grain of salt: Before someone tackles the building of a data-driven application with the purpose of eventually being able to use it in non-trivial projects, that person needs to have a good exposure to programming (by good I mean a LOT, say 1-2 introductory courses, 1-2 intermediate and at least one junior-level course, perhaps a total of 15-30 credits.) Unless that person is a natural programming virtuoso, I don't see it happening otherwise.

I would suggest, if you are serious about programming, to spend a substantial amount on learning the fundamentals before tackling something like this.

Good luck.

I'm getting the sense that reputable OO design and patterns come down to reducing conditional statements (if statements) via polymorphism. This would be very general statement, and wondering if it's true. If it's not true, can you provide an example.

To be clear - My question is purely academic. It is not concerned with the realities and practicalities of crafting software. For example, the question is ignoring tradeoffs like understandability vs complexity.

As the other answers state, reducing conditionals is not the main objective of OO design, but rather a benefit from function polymorphism. Other paradigms such as functional programming can also have that effect.

OO design is more about producing a Low Representational Gap (LRG) -- the distance between a model of the problem and a model of the solution. It's what another answer refers to as "code making sense."

The following is reused from http://programmers.stackexchange.com/a/308922/51948


A solution to a real-world problem needs to have a representation that closely resembles the model of the problem. It's why a dice game has a class called Die with a method called roll(), and not a block of code with 011100110000001110101000100001010101000100 (assuming those binary digit abstractions made sense on some platform). This has been called the representational gap by Larman. Abstractions allow keeping this gap smaller -- a strategy known as Low Representaitonal Gap (LRG). It makes code easier to trace to requirements and to understand. The Domain-Driven Design (DDD) approach is similar.

Rolling the dice by jcoterhals, on Flickr
"Rolling the dice" (CC BY-NC-ND 2.0) by jcoterhals


UML class diagram of DiceGame

When designing both the domain-model and class-diagrams I am having some trouble understanding what to put in them.

I'll give an example of what I mean:

I am doing a vacations scheduler program, that has an Administrator and End-Users. The Administrator does a couple of things like registering End-Users in the program, changing their previleges, etc. The End-User can choose his vacations days, etc.

I initially defined an Administrator and End-User as concepts in the domain-model, and later as classes in the class-diagram. In the class-diagram, both classes ended up having a couple of methods like

Administrator.RegisterNewUser();
Administrator.UnregisterUser(int id);

etc.

Only after some time I realised that actually both Administrator and End-User are actors, and maybe I got this design totally wrong. Instead of filling Administrator and End-User classes with methods to do what my Use-Cases request, I could define other classes from the domain to do them, and have controllers handle the Use-Cases(actually, I decided to do one for each Use-Case). I could have a UserDatabase.RegisterNewUser() and UserDatabase.UnregisterUser(int id);, for example, instead of having those methods on the Administrator class.

The idea would be to try to think of the whole vacation-scheduler as a "closed-program" that has a set of features and doesn't bother with things such as authentication, that should be internal/protected, being that the only public things I'd let the outside world see would be its controllers.

Is this the right approach? Or am I getting this totally wrong? Is it generally bad idea to put Actors in the domain-model/class-diagrams? What are good rules of thumb for this?

My lecturer is following Applying UML and Patterns, which I find awful, so I'd like to know where I could look up more info on this described actor-models situation.

I'm still a bit confused about all of this, as this new approach is radically different from anything I've done before.

I would not say that your design, as you speculate, is totally wrong, in fact Administrator and End-User are valid domain objects that should be represented somehow in the Class Diagrams. Just because you identify those two entities as actors doesn't mean they should be excluded from the Domain, remember, your domain is your scope, or "relevant context", that is, the set of useful objects that play a relevant role in your solution.

You may start with basic objects that comprise your model, just write them down, without further analysis, like brain storming...

  • Vacation
  • Location
  • Travel Agent
  • Schedule
  • User
  • Reservation
  • Reservation Service (This can be an interface for accessing the vacation reservation stuff)

Then try to establish the relationships between those objects, if you can not find any relationship that means you are not choosing the right objects, if they are part of the same problem domain then they must be related somehow.

After some time, you will discover that there are objects missing, try to encapsulate as much as possible, and represent the correct abstractions, Design Patterns might help you out with that.

When every possible object is represented with all its properties and methods, then you should have a fully, although not yet finished, functional design.

I know you should have a lot of theory in your mind, so get going, without fear, I myself have used this approach successfully many times at work.

Finally get a copy of UML Distilled

Regards,

Very often singletons are a bad thing (e.g. see here and here) and I want to avoid them. A typical use case for singletons I don't have an alternative for yet is when you have multiple objects which have to reference some sort of parent/global object.

Example 1: you have some sort of a tree and every leaf-object has to know the root object. (which is bad design but it's just for the example)

Example 2: you have a 'global' configuration object typically accessed like global_config::get_instance()->get_item(name)

Question: for the given examples - are there any alternative concepts to singletons apart from extensive dependency passing and per-instance-storing (aka Dependancy Injection)?

Question: for the given examples - are there any alternative concepts to singletons apart from extensive dependency passing and per-instance-storing (aka Dependency Injection)?

In both cases, you're talking about a visibility requirement of the information, not a singleton (i.e. only one instance of an object) requirement.

Craig Larman's "Applying UML and Patterns" states there are four ways that an object A can access an object B:

  • Attribute visibility -- B is an attribute of A.

  • Parameter visibility -- B is a parameter of a method of A.

  • Local visibility -- B is a (non-parameter) local object in a method of A.

  • Global visibility -- B is in some way globally visible.

The last one is what is provided by a Singleton. It's why this pattern is controversial.

Dependency injection is the first option -- B is injected to A in its constructor.

The general rule of thumb: the more you expose a piece of information in your design, the harder it could be to change your design later (because of coupling and dependency on that information). Global visibility makes it easy in the short term to solve some access problems in your design. It has the risk of creating problems in the long-term, because of over-exposure of information.

Can you please suggest a book for studying objected oriented approaches and programming.

First of all I have to mention that I have read many C++ virtual questions in on stackoverflow. I have some knowledge how they work, but when I start the project and try to design something I never consider/use virtual or pure virtual implementations. Maybe it is because I am lack of knowledge how do they work or I don't know how to realize some stuff with them. I think it's bad because I don't use fully Object Oriented development.

Maybe someone can advise me how to get used to them?

Check out abstract base classes and interfaces in Java or C# to get ideas on when pure virtuals are useful.

Virtual functions are pretty basic to OO. Theree are plenty of books out there to help you. Myself, I like Larman's Applying UML and Patterns.

I have a java class, which has lots of functions, and all are in one file. The total number of lines in this file is around 50K. I makes it very hard to read. Can I move some of the functions to different file? If yes, how to do that. And if no, is there is some other technique to make program more readable.

Define domain objects (e.g. value objects) for the various concepts in your model, and put functionality related to those classes inside them.

For instance if you have

public class MyBigClass {
   ...
   private String account;
   ...
   private boolean accountIsValid() { ... }
   ...
}

then separate the account into an Account class, like this:

public class Account {
  public Account(String accountNumber) { ... }
  public boolean isValid() { ... }
}

public class MyBigClass
  ...
  private Account account;
  ...
}

if you keep doing that, and you make sure functionality is always located together with the value, your huge class will shrink rapidly. Try to avoid using native types (like String) for anything but the internal values of your value objects.

Also, look at libraries like commons-lang and google guava, to make sure you are not re-implementing something complex that there already exists a suitable solution for; Examples of classes that will both simplify your code and reduce the chance of implementation errors are EqualsBuilder and HashCodeBuilder.

To further improve your coding style, consider reading the following books:

I'm trying to find some good reads to clarify this but I'm unable to find it (or maybe I just don't know how to search this properly).

What I'm trying to find is, considering that you have an application that:

  • interacts with a db;
  • interacts with Mainframe;
  • interacts with external providers;
  • etc...

What is the best approach to draw a diagram that represents this in a functional view rather then in a more techinical view? What kind of books, articles, websites can help me to get a clearer understanding of which approach should I follow?

Thanks in advance.

Well,

First thing that you should ask yourself:

Why I am drawing or want to draw a diagram about this?

Maybe you answer is :

To understand important/significiant communication between those elements.

Then we can say:

Oh maybe sequence diagram may help...

Buy may be you answer is:

Oh I am worry about topology of system components. How those things will be deployed?

Then we can say that:

Oh, may be deployment diagram will help you...Draw one.

So depends on "context"...

UML diagrams will not solve your problems. They help you to understand tricky and hard part of your system and think about alternative solutions by visual modeling.

Modeling is not "self masturbating" activity. It is like "group sex". You will get most benefit when you do with others...

So the main problem is not to draw which diagram... The main problem is:

What kind of problem you have? With whom you wanto to find solution? What kind of benefit may you get from drawing a diagram?

For UML i definelty suggest Larman book: Applying UML and Patterns :Check at amazon

And lastly, if UML does not fit your purpose, be creative and pragmatic...Use textual desription or even create your "own" visual modeling :-) or do anthing which help you...

In Craig Larman's book Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition), a use case is converted to a System Sequence Diagram (SSD) which contains system operations. It's a way of doing high-level design first, that's easily traceable to the requirements (use case), and later refining it by detailing the system operations at the domain level via OO design principles.

I'm trying to understand this methodology using RESTful services. The trouble spots seem to be with resources and the stateless operations.

Here's a sample from the book, an SSD with four system operations:

Example of a SSD - System Sequence Diagram

An SSD is also an abstraction of the presentation layer (on the left) and the domain layer (on the right). The domain layer might also include the application and or business logic.

In Larman's approach, a system operation (e.g., makeNewSale()) should be handled by a GRASP Controller which is a domain object that handles the system operation.

Now, let's say we're trying to use RESTful services in this approach:

  • The Uniform Interface constraint of REST is part of the presentation layer. For example, one can configure the route that a POST operation on a resource takes, allowing it to eventually call some operation of an object in the Domain layer. This Byte Rot blog by Aliostad explains very well the details of traditional layer architectures and REST.
    • In Larman's example, the Cashier clicks somewhere in the GUI to invoke a http://...com/sales - POST request and eventually a GRASP Controller receives makeNewSale(). The REST part http://...com/sales - POST request creates a new resource for the sale e.g., 001 and also makeNewSale() is sent to a GRASP controller object. Sequence diagram showing layers
  • Session Controllers (mentioned in the GRASP Controller pattern) don't exist on the System, since REST operations are stateless on the server. This implies that system operations might actually need more arguments to pass state information to the server, and that isn't obvious from the use case. For example, makeNewSale() probably needs to receive and process an authentication token as an argument, since :System has no session information. I found a related question and answers here at RESTful Authentication

So, assuming my understanding up to now is right, my questions are:

  1. Does the Uniform Interface constraint of REST respect loose coupling of presentation/domain layer separation? At first, it seems to be a detail of the presentation layer (like an actionPerformed() method in Java Swing). But the part that bothers me is that http://...com/sales ties right into a Sale (which is a domain) object.

    Another way of putting it: by creating REST resources and REST verbs accessing them via a Uniform Interface, isn't application/business logic being put into to the presentation layer? Larman's SSD approach is about layers and he explicitly states that application logic should not go in the presentation layer. For example, a POST to http://...com/sales creates a new sales/001 resource and also sends makeNewSale(). The first part seems like business logic. The fact that my REST resource names follow many of my Domain object names seems like my Presentation layer is (more) coupled to my Domain layer, than if I were using Swing and only called makeNewSale() from an actionPerformed() on a JButton.

  2. Larman's SSD concept is oriented towards the RCP model (with state in the server), but can an SSD be made to easily jibe with a REST philosophy? For example, endSale() exists to break the system out of a loop of enterItem() calls. Later in the book, Larman even presents a state diagram about this:
    State diagram for DSS
    I read about How to manage state in REST and it seems one has to take care with passing state on each system operation if needed (as in the authentication token example above), or the "state" is actually encapsulated in the resources. I thought about it, and with REST, endSale() could probably be removed entirely.

I used a concrete example here, so that the answers can also be concrete.

This past semester I took intro to object oriented programming in java and next semester I will be taking computer science 2 with java which is basically learning about various algorithms and data structures implemented in java such as linked lists, binary trees, etc... What are some ways that I can reinforce the knowledge I've learned in my intro to object oriented programming class while still preparing for next semester of algorithms and data structures.

I see you want to improve your OOP skills and not the problem solving skills. My best suggestion is below and in that order

  1. General Responsibility Assignment Software Principles or GRASP
  2. Practical API Design: Confessions of a Java Framework Architect

We are going to develop content Management System in ASP.net.Please suggest us what is the good design pattern do we need to follow in order to have good design.

I belief it's not the right start to search for usefull patterns first. Take a look at Graig Larmans Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development

It's all about the design. First write down the requirements. What do you want to develop. What should the features be. The Applying UML book is very clear about this. I can't explain it in a few sentences.

I want to know what kind of diagrams I should use in each step of a project lifestyle, for example in the first step I should do the use case diagram, but what diagrams should I do after this step, for example what diagrams I should use during the analyse of the project, the design, etc.

First of all you should decide which process model you want to use. Let it be Waterfall (not recommended), V-Model, Scrum, Unified Process, Rational Unified Process, etc.

Then you can start talking about first, second step and so on, because the steps depend on the process model that you use.

These diagrams you're referring to are also called artifacts, and you should only use them, if you need them and if they create value (more understanding for example), you should not use them just to have done it (only if it's an academic/school project and you want to learn).

If you want to improve your knowledge in that certain area, there are several good books out there, e.g. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development by Larman.