Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?

share|improve this question
1  
Very related: Choosing the right design pattern –  MichaelT 10 hours ago
3  
Do you think you could speak entirely in idioms? No? Then you shouldn't construct your programs by cobbling together design patterns. –  Kilian Foth 10 hours ago
    
In your example, the Null object pattern is only added for academic purposes, it does not introduce "a good design" into this code. –  Doc Brown 9 hours ago
1  
Yes, just look at what your code does, describe it in two words, and say it follows that design pattern. –  djechlin 3 hours ago

5 Answers 5

up vote 33 down vote accepted

should there always be some design pattern that I am following?

Dear God NO!.

I mean, you can go ahead and say that any random code is following some random XYZ pattern, but that's no more useful than me claiming to be king of my computer chair. Nobody else really knows what that means and even those that do won't exactly respect my claim.

Design patterns are a communication tool so that programmers can tell other programmers what to do, or what should be done without spending a bunch of time repeating themselves. And since they're things that come up a bunch of times, they're useful concepts for programmers to learn "hey, making XYZ always seems to come up because it's good/useful".

They do not replace the need for you to think for yourself, to tailor the patterns for the unique problem in front of you, or to handle all of the inevitable things that don't fit into nice buckets.

share|improve this answer
8  
What if I am a secular programmer? Can I ignore the god part? –  Cerad 10 hours ago
    
Your first paragraph is part of how I would answer this. Something becomes a pattern when it is repeated. If it is repeated enough times to require communication, it is a Pattern and benefits from a name. It is even argued by some that a pattern only develops because some abstraction is missing. Pursuit of patterns is the road to infamy as a member of the vaunted Cargo Cult. –  Magus 7 hours ago
    
@Cerad: Sure, as long as you promise not to write God classes as well! –  yatima2975 7 hours ago
    
John Doe - Technical Engineer, Generic Code Monkey and King of his computer chair –  h.j.k. 1 hour ago

if I am writing more complex code, should there always be some design pattern that I am following?

No. Design patterns are just that: patterns in relationships between objects. In other words, relationships that are used and reused often enough that someone said "Hey, we seem to be doing this a lot, let's give it a name." The list of design patterns were not determined all at once in the beginning of OOP and then handed down by GOF! They were discovered and eventually documented, and then popularized by the book.

That said, a big part of the benefit of design patterns is that they make it easier to think about software design at a higher level. They let you skip worrying about implementation details and think more about the big picture. In that sense they free you from the minutia, but they can also limit you in the same way that the way you express yourself can be limited by the words that you know. So, there may come a time when there is a design pattern for most of what you do simply because the patterns that you know are the terms in which you think. Keep your eyes open for cases where you might be abusing a pattern, and where you may need to think more deeply about better ways to do things.

Also, realize that in practice you often don't implement a given design pattern so much as recognize the pattern in some existing code, like an object framework. Knowing about common design patterns makes it much easier to learn how a framework is intended to be used because you can see the relationships between classes in terms that you already understand.

share|improve this answer
1  
Thank you. This is very clear. –  user2030677 10 hours ago

No.

This is what the Gang of Four (who originally popularized design patterns) had to say about it in their book:

"No discussion of how to use design patterns would be complete without a few words on how not to use them. Design patterns should not be applied indiscriminately. Often they achieve flexibility and variability by introducing additional levels of indirection, and that can complicate a design and/or cost you some performance. A design pattern should only be applied when the flexibility it affords is actually needed."

The example you show doesn't actually do much of anything (I don't think it was meant to, I think it was just meant to be an example). By itself, it has no need of the null object pattern. In the context of a larger program, it might.

The wrong approach is assuming that just because it has been labelled a "design pattern" it must be good, and then looking for more places to cram more patterns in. Use them when they fit the program and actually solve a problem for you.

share|improve this answer
1  
The book being Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. –  developerwjk 5 hours ago

Design patterns have two advantages

  1. They are easy to describe to other developers, because people generally agree on what the patterns are
  2. They tend to have been beaten on pretty thoughtfully by our predecessors, so their strengths and weaknesses are well understood.

The goals of every program should be

  1. It works. It has to do whatever the end goal is, or it doesn't matter how many design patterns you use. OO design patterns make it easy to dice up the problem into easy to understand bits so its easier to prove it works.
  2. It is easy to read. This is where design patterns are nice. The OO problems they solve are complicated. If you solve them in a "standard" way, its easier on the next developer
  3. It is easy to grow. Almost 0 modern programs finish where everyone planned them to. Every program grows after its initial release. OO patterns are known for being curiously good at growing.

That all being said, note that every reference to OO design patterns is "they're just good at the job." They are not perfect, but they do fill a niche very effectively. Use them when they work, avoid them when they don't.

As an example, of "complex code," as you mentioned in your question, take a scripting language I wrote. Most of it is OO with design patterns everywhere. However, when it came to writing the garbage collector, I unceremoniously dropped all pretenses of OO, because the particular things I needed to do were better modeled as good ol' fashioned bit-bashing. There's not an OO pattern in the entire thing up until it came to writing finalizers, where once again OO started to be a useful model again. Without any pomp nor circumstance, the code suddenly shifted back into using OO techniques again.

Use design patterns whenever they make your product better; avoid them when they make your product worse.

share|improve this answer

Broken question. Let me give you a novel definition of design pattern that would undo a lot of damage released by GoF: a design pattern is a good coding practice. That's it.

Any reasonably complex module will have several design patterns in it. Any time you cache it's probably a flyweight pattern but I'm not going to revoke your programming degree if you don't call it that. Any time you have a callback in it you're in some sort of event / fire / callback pattern. etc. If you have the word "static" you have a singleton. If you have a static constructor you have a factory pattern. If a resource is passed to your module you are using dependency injection.

"Design pattern" is a broken term ill-popularized by GoF, that makes it sound like all patterns are on the same level or you should use the doctor recommended 3 to 5 per class. Any time you do something right that someone else did right, it's a design pattern. A for(;;) is a common pattern used to represent an infinite loop, for instance.

You shouldn't go try to learn a bunch of design patterns. Programming knowledge is not indexed by design patterns! Rather you should learn how to write good code by read books, blogs, and attend conferences in your field. For instance, if you're already using dependency injection but just haven't labeled it, you might benefit from always using DI or using an IoC framework. Or if you're struggling to code right in events and callbacks, go learn Haskell so you're familiar with functional design patterns and it becomes easy.

And if your entire class reads as one big thing someone else did right, why are you reinventing the wheel? Just use their stuff.

share|improve this answer
    
In what language is for(;;) idiomatic? That is probably not the best example of something someone did "right". –  Telastyn 3 hours ago
    
@Telastyn C, C++, Java, Javascript, C#. –  djechlin 3 hours ago
    
I've never seen anyone prefer that over while(true) (or while(1)) in C, C++, Java, or C# in my 20+ years of programming. –  Telastyn 3 hours ago
    
@Telastyn stackoverflow.com/a/2611744/1339987 fwiw I started preferring while(true) because it looks more readable to me. –  djechlin 3 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.