Importance of a design pattern? - c++

I am learning C++
I don't know much about this stuff except the fact that programming design pattern is neccesary when actually working in large projects.I hope its correct to some extent.
Is this common to all object oriented languages or do I need to look specifically into
C++ design patterns.
Also How does it helps you.Is this realy important to learn as a C++ programmer.
Please suggest

Design patterns are often misunderstood. They are really a way for experienced users to have shorthand for describing common situations. You don't need to worry about them too much while you are learning C++.

You will hear discording opinions about design patterns, in the programming community at large.
In my opinion, it is sure that there are abstractions that patterns encapsulate that are really useful (factory, singleton, delegate, etc.). I use patterns a lot, but I myself am sometime puzzled by the apparent lack of depth or level of insight that you get by reading a pattern description. This is also in tune with the proliferation of design patterns that specialize for any kind of things.
When the design hey are useful, they are a very good means of communication and certainly they guide you through the process of designing or defining the architecture of your app. They are useful both for small project and for large ones, and they can be applied at different granularity levels.
Patters are a generic concept and all programming languages support them. Anyway, if you work in C++, a book focusing on it is best, because you will get the pattern adapted to the characteristics of the language.
In my opinion, the really fundamental book about design patterns are:
GoF, Design Patterns: Elements of Reusable Object-Oriented Software
VV.AA., Pattern-Oriented Software Architecture Volume 1: A System of Patterns
VV.AA., Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects

Most of the design pattern are common to all object oriented languages.

For me design patterns are nothing but abstractions that shorten communication time between programmers. Instead of expressing a complex idea of how your program is designed, you can probably find a name of a pattern that describes the design of your program.
E.g. TPM says "We should use singleton here", and you interpret "We should use one instance of the class here".
Patterns are useful to learn, but one can program without knowing any patterns, yet using them a lot.

I see design patterns as collections of wisdom gained by experience, particularly addressing issues of flexibility and maintainability of code. For example: by using a facade we can change implementations without changing the code that uses the facade.
I think it's fair to say that all programming languages have wisdom to be captured, and design patterns of some sort will be useful. The C/C++/Java/C# heritage languages seem to offer a particularly rich seem to be mined for wisdom. C++ being quite gnarly really does benefit from some key design patterns.
Some folk see Design Patterns as a way of patching over language deficiencies, that would imply that "better" langauges might need fewer patterns. My feeling is that in all cases we have something to learn from experienced folks and Patterns help us codify their wisdom.
Edited to add: Interesting point made by Munish, it is best to do a little reinvention first? By writing some real code without explicit use of Patterns you may well start to feel dissatisfied with what you write ... when I change this, I need to change all that, is there a better way to write this? ... this may drive you to really need patterns and hence motivate your study.
If you have the luxury of time to learn this way then I think you'll probably benefit.

Design patterns are solutions to commonly occuring problems in Design phase of a project.These patterns provide the solutions which we can use independent of programming language.For e.g. there is Singleton design pattern which ensures that there is only one instance of a class.Now there are numerous occaions on which this may be required.You can use the solution of these pattern and use in your code.
They provide the re usability in Software development .Put simply, design patterns
help a designer get a design right faster.
For more better understanding you could refer Design Patterns: Elements of Reusable Object-Oriented Software

Related

Immutable Data Structure - Application maintenance

I have been reading about Immutable data structures and understood that change detection has been made easy . And quite often, I hear that it makes the application maintenance simpler and provides an easy to understand programming model.
I need help to understand the way it simplifies the job.
The Clojure community has embraced immutability and it is an eye opener. The best I can do is send you to the source: Rich Hickey's essay on State and his talk The Value of Values. Rich explains how separating the concept of a variable into three distinct concepts: identity, state, and value helps you model your system and reason about it.
It boils down to this: in your programming model, you should only allow things to change if they change in the system you are trying to model. Otherwise you are adding moving parts (mutable variables and objects) to a model that doesn't need them. This makes it harder to understand the model (specially as time evolves) but has little or no benefit.
Even though reading helps, the only way to grok this is to program in a language that takes immutability as a default until you realize how most of the systems you model actually have only a handful of things that change instead of pages and pages of mutable variables.
Immutability is certainly more embraced in functional languages than in imperative ones, even if you can have a Java programming style that limits mutability (see this for immutability in Java). That said, I will just comment on [functional/immutability] and [object/mutability].
I'm Clojure fan and find functional programming really powerful, but...
May be I spent too much time with C++ & Java and not enough with Lisp & Clojure, but I reckon that the simpler maintenance argument has yet to be proven by facts. I'm not sure there are reliable surveys on the actual cost of maintenance in big production systems with data on the technology used and associated costs.
Certainly, in terms of LOC, language like Clojure are really more focused and concise than Java. Hence you can say that less code leads to less maintenance, but I think functional style gives really more compact code that needs a very focused attention to fully understand what a function is doing comparing to imperative style which is more verbose but kind of straightforward. One big advantage of functional programming associated with immutability, is the ability to isolate a function and experiment with it without the need to drag a heavy context of satellite objects or build a bunch of mocks, which is very often the case with OO languages. Putting aside the experimentation, a pure function won't modify its arguments, which ease the fear to break unintentionally some piece of code outside the scope of the function.
But, putting aside the merits of functional/immutability over oop/mutability, in terms of maintenance, my experience leads me to think that it's not the technology which is the main issue, but the design, code quality and evolution of this code over time even when the initial one was of good quality. By "good", I mean that the code is respectful of style conventions (like basic naming), managed complexity, and has a sensible test harness, in a continuous (or at least automated) build environment.
Then, the question becomes: is there a paradigm (functional/immutability, object-oriented/mutability) that enforced a better design and better code. My feeling is that functional languages are the land of computer science passionates, OTOH OOP is more mainstream. Isn't it because OOP is easier to apprehend or is ot just a matter of education? but then, in order to maintain a system in the long run, should one go for a "clever" functional environment with few people able to tackle it, or some mainstream OO technology - with its unsafeness or permissiveness - but lots of people having some knowledge in it?
Certainly the solution is to choose the right technologies (plural) with the right, motivated people...

C++ Design Pattern library?

What is the most common C++ Design Pattern libraries?
I've read about Loki library in Alexandrescu's book, but looks like it somewhat dead now. Is there something similar out there?
“Design patterns are bug reports against your programming language” --
Peter Norvig
To answer the question why there are not many C++ design pattern libraries, it is useful to know what design patterns were meant to solve in the first place. The classic GoF book states in the preface
Design patterns describe simple and elegant solutions to specific
problems in object-oriented software design.
The 90s style of object-oriented programming relied heavily on using abstract classes as interfaces, with concrete implementation classes deriving from these interfaces. The GoF patterns describe creational, structural and behavioral relationships between objects of different class types. They key element was: encapsulate and parameterize whatever will frequently change. Many of the GoF patterns can also be reformulated using templates, but then the flexibility is constrained to compile-time rather than run-time.
Object-oriented programming makes it very easy to add different concrete implementations of an interface. What OOP has a hard time with is adding new functionality to existing interfaces. The Visitor pattern is the prime example: it is essentially a work-around that relies on an extra level of indirection to allow new algorithms to work on existing data structures.
This is the exact opposite of functional programming: with functional programming it is very easy to add new functions for existing data, but it is much harder to add new data types to which such functions apply. The difficulty in getting extensibility in both functions and types is called the expression problem.
OOP style polymorphism is heavily based on internal polymorphism: the dynamic function dispatch is based on the object's type. Modern C++ also uses external polymorphism where techniques such as type erasure allow run-time flexibility with a static interface. The new std::shared_ptr and boost::any or adobe::poly classes are prime example of these techniques.
A recent ACCU presentation by Tobias Darm showed many examples of transforming the old internally polymporhic GoF patterns to this new style externally polymorphic patterns. The rough idea is to replace abstract classes with a function argument that can take std::function as a parameter. The std::function then controls the polymorphic flexibility from the outside. Many of the GoF patterns can be greatly enhanced in terms of boilerplate this way.
TL;DR: The classic GoF patterns were tailored to solve OOP shortcomings. But OOP is no longer the dominant C++ style. A combination of generic programming (the Standard Library, Boost) and OOP can solve many problems more elegantly, making classic design patterns no longer the go-to solution.
The original definition of a design pattern was a reusable approach to a reoccurring problem that could not be conveniently encapsulated in a library. Thus, the moment you can encapsulate a pattern in a library, it ceases to be a pattern, in my opinion. This has, for instance, largely happened with iterators in C++, as the standard C++ library has a comprehensive framework for implementing iterators now.
I’ve never tried to use Loki, but reading Alexandrescu’s book, I was not persuaded that a library based approach really had much to offer for many patterns.
May seems tautology, but the most common is ... the standard library itself!
It is not -strictly speaking- a "pattern library", but a folder for a number of tools addressing common pattern implementation.
Note that your question is not answerable, being a pattern just a conceptual definition commonly used in a variety of problems. Libraries don't provide patterns, they (can) use patterns (like anybody else can) to provide implementation of specific problem solutions.
Patterns are at an higher abstraction layer than coding.
In an effort to improve code maintainability, re-usability and readability, some researchers (such as GoF, Booch) started examining best practices. They have noticed that there are some patterns adopted by experienced developers to address specific design problems.
As you can see, experience created design patterns. So using design patterns is coding like a specialist. And there is no silver bullet for this.
It is true that some straightforward design patterns such as decorators find support from specific languages. But that's the limit. Domain specific frameworks also guide you to use their interfaces to complete the design pattern decided by the authors of those.
Libraries will only help you understand how design patterns used in that library will facilitate your implementation. It won't even give you a choice to change the design.

Are some design patterns language dependent?

If yes, then are there any patterns that are specific to C++, and some that are not?
Which are they, if any? Well I am referring to these design patterns: http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29
RAII is a powerful pattern that relies on C++'s scope cleanup mechanism. In garbage-collected environments this language feature is usually missing. Other languages (e.g. Ruby) have other ways of using user-provided control flow constructions.
I'm not sure if there is another answer other than "Yes".
If the design pattern depends on language-agnostic object behavior, the same DP can be applied across languages.
However if the design pattern is dependent on some language features, then translating it to another language would require some effort or be impossible. Some patterns might come into existence because of some characteristics of a specific language (but are not needed in other languages).
People come up with patterns all the time. So yes.
I think the best answer here is "it depends" because the notion of pattern has some fuzzy boundaries.
If you are willing to say "C++ virtual function" or "Java interface" is a "pattern" then, well, you have by default come up with a "pattern" that is applicable to exactly one language at the exclusion of all others. Given that a pattern is simply a way of solving a problem that can be applied in varying contexts, you could argue technically that single-language patters can in theory exist.
However the common use of the term "pattern" is something slightly more abstract than a specific language feature. What I think most people can agree on is that there are patterns that are specific to certain families of languages, where the family can be very small, e.g., languages supporting OO, supporting actors, supporting channel-based communication, etc.
When your pattern becomes so specific that the language family to which it applies winds all the way down to a single language, you get into the fuzzy area where people might quibble about whether something is a pattern or a language feature. The rationale here is that "well heck, can't someone just create another language based on this language so that the pattern will apply to the derived language too?"
However, if you can reasonably argue that your alleged pattern is indeed a way of solving a problem that can be used in different contexts, and that no other programming language in existence can reasonably implement this solution, then you can say yes.
.... Until someone creates that dialect! :-)
Yes.
The most notable way to see this is to experiment with a paradigm shift. For example, compare Java (OO) to Haskell (Functional).
Let's take the Flyweight pattern, in Java. In Haskell, it's a no-brainer, data (which is immutable) is implicitly shared.
Other example: the Command pattern. Haskell supports first-class functions (and curryism), commands are built-in.
Some will argue that DP exist to cover what a language does not provide in a built-in way. In this sense, the higher level a language, the more DP are embedded.
The patterns which uses the specific language functions like Multiple Inhertance in C++, Dynamic behaviors like Reflections are quite language dependent. GoF design patterns are considered as the base for most of the patterns but as the years went, systems became more complex and distributed. Hence the fundamental design patterns and principles were evolved and extended. Web frameworks and libraries are one of the best examples for implementing real-world scenarios to meet the developers/users need. Like dynamic page generation, AJAX etc. But I seriously believe that, the patterns must be generic and should not rely on languages.
For e.g if you're is using too much patterns which depends on PHP, may not help them to switch to some other dynamic languages like Python. The general/generic implementations can be realized easily across most of the languages.

Looking for Projects having extensive usage of (mostly used) design patterns

I want to get my hands dirty with some projects (in C++) which have used design patterns extensively.
I have already read design pattern documentation (as well as code) from net and other books (gang of four and Head first), but i am looking for a place where i can get already implemented projects (using design patterns), get my hands dirty with them, understand them, enhance them etc.
Could anybody point me to a place(s) from where I can get design experience in the best possible way? (Please note: Language C++, Complexity of the project can be intermediate to difficult)
ACE is a good example - uses many concurrency and communications patterns. There's a list of related tutorials on their website here.
If you are feeling ambitious take a look at Loki.

Symptoms and alternatives to overused OOP

Lately I am losing my trust in OOP. I have already seen many
complaints about common OOP misuses or just simple overuse. I do not
mean the common confusion between is-a and has-a relationship. I mean
stuff like the problems of ORM when dealing with relational databases,
the excessive use of inheritance from C# and also several years of looking
at code with the same false encapsulation belief that Scott Meyers
mentions in the item 23 of Effective C++
I am interested in learning more about this and non OOP software
patterns that can solve certain problems better than their OOP
counterparts. I am convinced that out there there are many people
giving good advice on how to use this as an advantage with non pure OOP
languages such as C++.
Does anyone knows any good reference (author, book, article) to get
started?
Please, notice that I am looking for two related but different things:
Common misuses of OOP concepts (like item 23)
Patterns where OOP is not the best solution (with alternatives)
Well I can recommend you a book Agile Principles, Patterns, and Practices in C#.
Examples are in C# of course, but the idea of the book is universal. Not only it covers Agile but also focuses on bad practices and shows in examples how to convert bad code to a good code. It also contains descriptions of many design pattern and shows how to implement them in semi-real example of Payroll application.
This has to be done but if you truly want to get away from OOP or at least take a look at concepts which are not OOP but are used with great effectiveness: Learn you a Haskell. Try a new programming paradigm and then start seeing where you can apply much of the concepts back to OOP languages. This addresses your second bullet, not in a direct way but trust me, it'll help more than you can think.
It's a bit odd that you mention C#. It has very powerful keywords to keep the usual inheritance misery in check. The first one ought to be the internal keyword. The notion of restricting the visibility to a module. That concept is completely absent in C++, the build model just doesn't support it. Otherwise a great concept, "I only trust the members of my team to get it right". Of course you do.
Then there's the slammer one, the sealed keyword. Extraordinary powerful, "the buck stops here, don't mess with me". Used with surgical precision in the .NET framework, I've never yet found a case where sealed was used inappropriately. Also missing in C++, but with obscure ways to get that working.
But yes, the WPF object model sucks fairly heavy. Inheriting 6 levels deep and using backdoors like a dependency property is offensive. Inheritance is hard, let's go shopping.
I would say to look at game engines. For the most part, OOP has a tendency to cause slight performance decreases, and the gaming industry is seemingly obsessed with eliminating minor slowdowns (and sometimes ignoring large ones). As such, their code, though usually written in a language that supports OOP, will end up using only those elements of OOP that are necessary for clean code / ease of maintenance that also balances performance.
EDIT:
Having said that, I don't know if I would really go look at Unreal. They do some strange things for the sake of making their content pipeline easier for developers... it makes their code... well, look if you really want to know.
One common overuse is forcing OOP in programs/scripts that take some input, turn it to output, then exit (and not receiving input from anywhere else during the process). Procedural way is much cleaner in these cases.
Typical example of this is forcing OOP in PHP scripts.