Design Patterns Vs EffectiveJava - java

I am student striving to improve my Java and general programming skills. I am familiar with some of the basic design patterns.
I have two books on my disposal "Head First to Design Patterns" and "Effective Java"(Josh Bloch), both aiming to promote good programming practices.
However I am confused as to "how should I read the texts so that it makes the most sense?"
From what I understand, design patterns are basics and effective java has some addon practices in addition to general design patterns.
What is the right way to look on the entire scenario?

You just have to build your knowledge up. Some of that is by reading good books, of which the Josh Bloch book is a very good book. Some of it is by taking on programming tasks in your spare time and keeping an eye on blogs and other websites such as stackoverflow. While some of it you will get through other practical experience i.e. at work.
These things take time and come with experience. Just enjoy the language and immerse yourself in it. Patterns aren't the be all and end all of the language - they're part of an effective toolkit though. It's better to understand the language fully, then you will see how design patterns can help solve common problems and often solve them better. But definitely don't get obsessed by patterns, until you know the language well enough. If fact don't get obsessed by patterns at all!
I'd say the Josh Bloch book is the best book to concentrate on 1st - it's excellent and introduces you to all the key concepts (common methods such as equals and hashcode, enums, concurrency) and also introduces patterns which you'll get day to day benefits from e.g. Builder pattern.

However I am confused as to "how should I read the texts so that it makes the most sense?"
My only advice is to avoid overkill and over-engineering. Some experienced OOP (and Java) programmers that learn design patters taking them as they were the Bible often create fuzzy and useless code. That seems contradictory, but if you think about it, it isn't.
When the goal of programming is no longer resolving a problem, producing useful tools, and having measurable results, but becomes the exposition of one's great sophistication, cleverness, and sometimes smartass egotism, then the code becomes just a bunch of tricky brainwave that is useless to anybody, excluding the one who wrote the code and feels good looking at his crazy "white elephant".
Many times I've seen useless applications of them. The most abused is the factory pattern, that in this moment is quite trendy and in fact put everywhere like a food dressing.
Many times I've seen proliferation of classes and interfaces, useless generalizations, which are pointless: in some cases I've seen packages with 2 useful classes, and 10 interfaces and/or abstract classes. I too feel the need of making the code "generic" and "reusable" but there has to be a limit.
Many times I've seen "religious wars" about these topics.
Read all the books you want, and take from them what you need. But after that, write reasonable code. Write useful stuff, that's the original reason why you started programming.

The two books complement each other. Effective Java is about best practices in writing java code. Design Patters describe a set of standard solutions to common software problems. The design patterns are language independent really, while Effective Java is obviously focused on the java language.
But my general approach is "always agree with Josh Bloch" ( unless Jon Skeet disagrees with him )

Programming patterns are best practices.
They should be used sparingly.
Every design pattern tries to handle some form of variation.
For example strategy pattern tackles a variation in implementation
Which is basically a fancy way of saying it is a plug and play method.
Patterns result in flexible code, but they create a large amount of extra complexity in the code.
Maybe you want to take the book Applied Java Patterns next to those books you already have.
It's written by Olav Maarsen and Stephen Stelting. Also the root of all patterns are the Gang of Four, you might want to use their book as a refference as well.

Design Pattern is not always good. Overuse of Design Pattern is bad.
Josh Bloch, however, is always right. Trust him and you are saved.
Forget Design Pattern. Josh Bloch's book gives you all the patterns you need.

Related

Approach to learning algorithms using a specific language

So for the summer I decided that I may as well start learning algorithms before school starts. I've been told that the class is fairly fast paced, and that algorithms isn't something you should take lightly (I have a tendency to do this with all the course work during the semester lol).
The book we're going to use is this Algorithms (4th Edition).
Anyway, this is my problem.
I'm almost third way through the book, but I just realized what I was doing. For example, I would read and re-read the sections I don't quite understand. Then if I feel confident enough, I would try to reproduce the same algorithm in java from my head. But by doing this, my code looks almost exactly like the ones in the book..in java.
I can't say I'm just memorizing code after code--I do understand the concepts and they help me code these algorithms--but I feel like I'll only be able to implement these algorithms in java. I should note that I only know java at the moment.
tldr: I'm learning algorithms as if I'm learning to play the guitar--repetition after repetition. But by doing so I feel like I'm being more fixated that I'll only able to implement these in java. How exactly would you learn algorithms if the book you're using is language-specific?
Thanks in advance.
Don't Confuse Yourself
You're studying Java, so write them in Java. Especially if Java is your first language. Don't confuse yourself for now, as you are trying to learn 2 things at once: how to progam in Java, and how to progam. You're learning both a new language and a way of thinking. Don't do too much but adding another language to the sauce for now.
Diversify
Later on, or if you feel confident enough that you can take on another language simultaneously, then it would obviously be beneficial to learn another one and try to replicate the algorithms without looking at the book.
Reproduce and Extend
What we could recommend you is to look for derivates of the algorithms. Known variants, that have been documented, and where you could just read the description of the variant so you can try to implement it from the "base" version, without needing to read the book.
For instance, if your book introduced you to a linked list, you should be able to come up with the algorithm for a doubly-linked list or a circular linked list without reading more than a description of the desired outcome. Or there's something about the original concepts that you clearly misunderstood.
Try First, Read-On Later
I'd recommend you actually even try to implement the algorithms described in your book before they show them to you. The point of seeing Sedgewick's algorithm is to see a canonical implementation, which is considered a standard blueprint. If you just read the section leading up to the implementation (which hopefully is displayed first), then just sit down with the book, and try to figure out how you could do that. If you can't do that at all, then you're too far ahead in your book and should backtrack and start again from scratch.
Thing about algorithms, they're essentially language-agnostic. There's really nothing stopping you from doing Sedgewick's examples in C, Python or some other language.
If you really don't know any other languages, concentrate on Java. Sure, its a bit repetitious, but those bits will stick in your head in a good way and come test time, you'll be glad for the information.
You're in an interesting position right now, since the kind of thinking required to write programs is very different from normal thinking. Add to that the fact you're learning a whole new language with a different syntax, punctuation and the like. Practice really does make perfect, since there are many bits and pieces to remember.
Oh, if you want practice with algorithms, try out project euler, code kata and other challenge sites. These little challenges can help you familiarize yourself with the language as well as get comfortable with the type of thinking required.
First, congrats on taking your first steps on learning how to code. I would say that you are already ahead of your peers by starting to look ahead during the summer.
As far as your fears on only being able to implement algorithms in Java, you have already demonstrated that it will not be a problem for you. It sounds like you are passionate enough to get started early so you should have no problem implementing a solution in multiple languages. Additionally most of the languages with C/C++ (Java and C# to name a few) like syntax will be similar enough that you will be able to translate your knowledge seamlessly.
The best advice that I can give is to CODE, CODE, CODE!! Don't just read about the algorithms actually implement them.
You don't say how well you know the mathematics behind the algorithms. That will be key in determining your facility with the code.
Sedgewick's books are very good. I'd feel free to pick some and check out other books as well, like "Numerical Recipes" and "Numerical Methods That Work". See if another point of view can clarify for you.
If you don't feel like you're getting enough out of copying Java, see if you can translate them into another language, maybe Python or purely functional alternative. If you can do that, you'll know you've got it.
I would either try to learn another language to verify that you can actually port it to another language (javascript would be my vote because it is simple and useful on the front and backend) or write the algorithms out in pseudocode since that is more language agnostic. Most languages will have the code look pretty similar. The only thing to be very careful about is when you are relying on some aspect of the language (such as generics or iterators in java) which you may not be able to use in another language and that could leave a gap in your understanding.
Another way to verify that you actually understand the algorithm is to make slight changes in the problem and make sure that you can adjust the algorithm to still work. For example if it is a sorting algorithm then try to sort by several different attributes rather than just one, if it is a graph algorithm make the graph a digraph and see how things should change.
I'm learning algorithms as if I'm learning to play the
guitar--repetition after repetition.
Then you are not learning algorithms. You are learning repetition. Two different things. The usage of a programming language by an algorithms book is a secondary factor. It is just a vehicle of instruction, an implementation detail.
What you should be focusing is on understanding the structure, logic and mathematical characteristics of an algorithm (and possibly the data structure(s) associated with it.)
That's what your focus should be.
But by doing so I feel like I'm being more fixated that I'll only able
to implement these in java.
But that is because you are focusing on just how the algorithm is being coded (in Java in this particular case.) You are focusing on an implementation detail.
When you learn to drive, you don't focus on how you learn to drive a Honda Civic or a Nissan Maxima. You learn the essence of what driving is, the rules of thumbs, the necessary precautions and the laws governing driving a vehicle.
Same with learning algorithms. You don't learn "Algorithms in Java" no more than "Algorithms in Haskell". You learn Algorithms first and foremost, the vehicle (sans very specialized cases) is secondary.
You should be focusing on what the algorithm does, how and why. Questions like "how/why does it work?" and most importantly *"what are the performance characteristics?", those are the things you should be focusing on.
Every good algorithms book (Sedgewick's included) carry that message. That's what you should focus on. How you get to that re-focusing, that's a function of one's personal learning strategies.
How exactly would you learn algorithms if the book you're using is language-specific?
By not focusing on the language. Focus on the structure, focus on the data structures involved, the invariants, pre-conditions and post-conditions. Understand asymptotic behavior described in Big-O (or Big-Omicron), Little-O/Little-Omicron and Omega notations.
You are learning algorithms, not programming in Java via coding algorithms.
If you can't do this mental leap, it means you do not have sufficient practice or abstract analysis. It is not an insult, but an observation and an advice. Coding, the usage of a programming language is typically secondary to the mathematical analysis of computing, the focus of Computer Science (of which Algorithms is a part thereof.)
NOTE I've done Java for over 10 years, and though I like it for work, I strongly believe it is a poor tool for learning programming or CS topics.
One is better served by learning Algorithms with either A) a procedural, systems-level programming language like C or Ada, or a high-level pseudo-assembler simulator, or B) a functional language like Lisp or Haskell.
Object-Oriented features in pure/pseudo-pure OO languages simply get in the way.
Algorithms are mathematical structures with a nature descriptive of the how (operationally) and/or the what (mathematically). The former is perfectly suited for procedural programming, the later for functional programming.

Class library for design patterns in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I find my self writing again and again the same programming patterns in many new projects.
I have been thinking about creating my own reusable library of typical implementations of such patterns -not trying to cover all possible design patterns, but only them that experience has shown that it makes sense to put such typical implementations in a library (e.g., adapter, factory, etc ...)- but before I would like to know if there is not an existing library for this purpose already available for Java?.
I know that it is very difficult to completely generalize programming patterns in a way that they could be reused across different implementations with complex requirements (e.g., composition of patterns, classes participating in more than one pattern, etc ...). However, most of the time the pattern instantiations I need are quite simple and standard, and in many situations the implementation work could be sped up a bit with the use of such a library.
Thanks for your feedback.!
Design pattern are just... patterns. They aren't classes ready to use for anyone, but common concepts found across several projects. That's why you won't find a Design Pattern API.
This is precisely the reason why I created PerfectJPattern. Just make sure to check out and understand the code examples. They are available for download as well as in the site documentation pages for each of the Pattern implementations. If you read the GoF book, then you will understand the examples more easily.
For instance, if you want to use the Composite Pattern in your code, and if you use PerfectJPattern you only need to specify which interface (generic parameter and class instance) you would like to use as Composite and the rest is provided to you, see PerfectJPattern Composite. At the bottom of that page, a working example is provided that shows how to accomplish that.
Another aspect you should also take into account, is that in PerfectJPattern you do not necessarily need to reuse the generic Pattern implementations (e.g. perfectjpattern-core Maven submodule), you also do have the choice to only reuse the pure abstract level (perfectjpattern-api Maven submodule) and provide the implementation yourself. In PerfectJPattern you have the flexibility of reuse at different levels of abstraction since there is a fine-grained layered design reflected also in the Maven project structure. Reusing the perfectjpattern-api gives you an abstract template guideline if you wish, that will help you speed up your own Design Pattern implementations. However, ideally you should reuse as much as possible.
Update: following up on a comment below, it is worth noting that not all Patterns can be fully compotentized see From Patterns to Components. Some Patterns can be only partially componentized and some others not at all like the case of the Singleton. The Singleton depends too much on the context and that's why you can only find an interface in PerfectJPattern. However in PerfectJPattern the following Patterns are fully componentized e.g. Observer, Command, Adapter, Decorator, Composite, Proxy, Visitor, DAO, etc.
I disagree with the other answers that no reuseable implementations can be created for design patterns. However, it might not always be straightforward, and involves a lot of abstract programming.
Coming from C# I was missing the simplicity of the observer pattern in Java. (events in C#) After finishing a reusable generic observer for Java I came across the PerfectJPattern library.
It might be worthwhile to check it out.
A componentized pattern is in essence a context-independent, reusable
and type-safe variation of the original pattern that covers at least
as many use-cases as the original pattern and that does not require
developers to re-implement the same boilerplate code in every
different context. Design Patterns are reusable in terms of design,
componentized patterns are reusable in terms of design and code.
Kudos for wanting to reduce any form of duplication possible. "Don't repeat yourself" is one of the most important principles in programming.
As some extra arguments design patterns can be centralized in a library I give you some further examples:
Lazy initialization in C#.
Entire LINQ is based on IEnumerable.
Java's attempt at a reusable Observer pattern. (I didn't say all are good.)
Several patterns integrated in the Spring framework.
As in Pangea's answer: Java JT framework.
What you are looking for is PerfectJPattern.
Checkout dp4j. It allows you to implement the Singleton pattern with #Singleton and lazy initialize it with #Singleton(lazy=true). It is a "collection of reusable componentized Design Patterns implemented in Java".
For the Singleton recommend dp4j. To implement a Singleton you annotate your class with #Singleton and to lazy initialize it you annotate with #Singleton(lazy=true).
If you find yourself repeating similar code in multiple projects, it might be a good idea to extract the portions that are repeated into a library of reusable code in hopes of avoiding repeating yourself in the future.
This is unlikely to lead to fully general reusable implementations of design patterns.
JT Design Pattern Framework for Java/j2EE
A lot of the patterns are built into the Java SE - you may not notice.
Decorator is all over the java.io package.
The java.sql package is AbstractFactory.
All the wrapper classes are Flyweights.
I stand with those who say don't look for a pattern library. They should be discovered as you write your code.
It is possible in a languange which offers higher order functions and some other stuff. Here are some slides which references a paper which discusses 'the origami pattern' library. It shows 'library code' for the following patterns: Composite, Iterator, Visitor, Builder. So if you want to try that out on the jvm you can today, just use scala. http://www.slideshare.net/remeniuk/algebraic-data-types-and-origami-patterns
Do you see a forest or trees?
Design patterns should become apparent rather than be selected up front. By the time they become apparent, you don't need the pattern because the code exists. Then you marvel at how the solution solved itself and your brain subconciously selected the right approach. It gives you that warm fuzzy "i trust that code" feeling.
If you build a design pattern library, you have built yourself a big hammer (or hammer factory, or hammer factory factory [1]) and everything becomes a convenient nail (including screws) resulting in lots of sore thumbs and bowls of spaghetti in your development team.
[1] http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12

Design patterns, how do they differ from other programming styles?

Design patterns aren't necessarily a programming style but rather a template for solving a problem in a number of different situations.
But how do they differ from other programming styles?
Thanks
Edit:
"(a) What are design patterns? How do these differ from other programming styles? [7]"
A design pattern provides a known solution to a common design problem, and is given a name to allow programmers to communicate more efficiently.
However, I have no idea what you mean by "programming styles".
Edit: I think the question is simply very badly worded. While "design pattern" has a relatively clear definition, "programming style" is, in my experience, not a term with a generally agreed clear definition. The question seems to assume that design patterns are a kind of programming style, and I don't think that's true.
If we take "programming style" to mean this, then the primary difference between programming styles and design patterns boils down to form vs. function: programming styles merely suggest how code is supposed to look, but dont have anything to say about how the code works; while design patterns are all about how code is programmatically structured and executes, but say nothing about how the code looks.
Design patterns are common solutions to object-oriented programming problems, so they differ from other styles in exactly the same way that object-oriented programming does.
As I see it, programming styles refer to the "specifc" way in which you'd go about implementing something (Design patterns included). Although Design Patterns have traditionally been linked to OOP many design patterns still exist in other programming paradigms. The question, i think, is trying to prove whether or not you've got the difference between a "generic" and proven way of solving a problem, and an specific way of implementing a solution to "that" problem.
Regards,
I agree with other answers and in additional to that I think some program specific properties integrated some design pattern philosophy. Like the "delegate" keyword in C#, which implements the delegate pattern but it is absolutely supported by the language itself.

Design patterns that every developer must know?

What are the design patterns that every developer must know?
I'm interested in the context of Java web developers working with Spring & Hibernate. I have often heard that good knowledge in design patterns is essential for working with those frameworks. Can anyone list the specifics?
For example, I know that understanding abstract factory & factory pattern, singleton pattern etc is absolutely essential. I'm looking for a comprehensive list.
Inversion of Control
If you are ever going to design decoupled systems, you will need to know how to properly link dependencies between classes.
Command Pattern and Variants
In Java in particular, it is essential to learn how to pass a piece of functionality to another method as an object because of the lack of closures and function pointers in the language.
Factory Pattern
Factories are ubiquitous in Java frameworks and it is essential to learn why and when to use the factory pattern.
Singleton (pattern and anti-pattern)
Learning how to use the singleton pattern responsibly is very helpful for understanding the pitfalls in other people's code you may be reading.
Overall, learning the why with regards to patterns is much more important the the how. Knowing when not to apply a pattern is just as important as knowing when to.
Everybody should know about Singleton, but also when not to use it! It's currently the source of much pain for me on a project at work.
Singletons make the code hard to understand and follow, and make writing unit tests much more difficult. I like the blog post Singletons are Pathological Liars.
Most design patterns are pretty obvious--you already know and use them if you've been programming a few years.
The biggest advantage I've found to design patterns is sharing a common set of names. If someone says "Callback" that can mean quite a few things, but if someone says "Listener Pattern" that means a more specific set of calls and implies a higher level relationship between objects.
So in essence, read through a good design patterns book, get an idea of the name of each pattern, spend some time understanding any you don't know, and you're good to go.
I wouldn't completely ignore any of them--they are all good to have seen. You should be able to recognize a situation that might benefit from a specific pattern and know where to look to find out more about it.
Model–view–controller just has to be on the list, Spring has an MVC framework:
http://en.wikipedia.org/wiki/Model–view–controller
I recommend you to read Head First Design Patterns book. This is a well written book about all commons and useful patterns.
I would recommend you get and read the Design Patterns book, since it gives you the vocabulary.
But don't forget the fundamentals :)
Interviewing Java Developers With Tears in My Eyes
http://java.sys-con.com/node/1040135
Hibernate? Then the Unit Of Work is a must http://martinfowler.com/eaaCatalog/unitOfWork.html
Composite, it's present in the JUnit framework. (Test-TestCase-TestSuite)
The Adapter, Builder, Command, Template Method and Strategy patterns are easy and often usable in practice.
The State pattern also helped me to clean up mess in inherited source codes.
This would be a comment to Greg Hewgill's reference to "Singletons Are Pathological Liars", but I can't make comments yet.
That article makes a convincing case, but his ire is misdirected. As several commenters on his blog noted, his problem is really global state. His code fix could still be making use of singletons, and still gain the exact increase in clarity and testability.
Re-read the article. He's not bothered that OfflineQueue needs an initialized Database instance, nor that CreditCardProcessor needs an initialized OfflineQueue. He's bothered that those dependencies aren't visible, which causes issues with maintainability and testability.
His problem is with secret global state (does this make me sound like a conspiracy theorist?).
However, he's (imo) misinterpreting that secret global state as being the fault of singletons.
That doesn't mean I'm in favor of singletons where they're not necessary - certainly, they have drawbacks (including the obvious thread contention bottleneck possibility). But I prefer to be clear about what practices I'm eschewing.
Incidentally, I'd go further in my refactoring - based on the class names, I'd assert in a code review that CreditCardProcessor should, well, process the charges, so instead of his:
card.charge(cardProcessor, 100);
I'd have this, instead:
cardProcessor.chargeCard (card, 100);
(and yes, I replaced his variable names c and ccp with names I considered more readable)
Apart from Abstract factory , Factory Method and Singleton patterns, which you have quoted already, I think below patterns are useful.
Bridge Pattern : Abstraction and implementation can change independently
Decorator Pattern : Change the behaviour of object at run time
Mediator Pattern : Enable central communication medium between different objects
Chain of Responsibility : If you are adding filters to web service request, this is very useful.
Strategy Pattern : If you want to change the algorithm from a family of algorithms at run time by checking a parameter
Facade Pattern : If you have many services in your system and don't want to expose all the services to client, have one Facade class, which will interact with other services.
sourcemaking provides excellent details on each design-pattern : Intent, Strucutre, Checklist and Rules of thumb.
One more SE question would be definitely help you :
Design Patterns web based applications
Singleton - Singletons apparently can and should be used for everything

Multiprocessor Programming Course Feedback

I am planning to attend a one week course on this subject. I am primarily involved in Java projects and have decent knowledge of C and C++ too. And, I am interested in learning more on concurrent programming and would like to get feedback on this course. Has someone read the book or found these concepts relevant in contemporary programming?
More information on the course:
http://www.amazon.com/Art-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916/
I would definitely, suggest you to go with this. But I would like to add another really important resource, specific to java - as you labeled the question 'java' - which is Java Concurrency in Practice.
The concepts are very relevant.
I seem to recall I had a very quick "flick" through this book at some point. It covers some quite interesting material. But a slight thing that concerned me as I recall is that it presents various algorithm implementations that rely on access to volatile arrays, and assuming that the individual elements have volatile access semantics when doing so. As far as I'm aware, the Java Memory Model doesn't offer this guarantee, so the implementations given may need some modification.

Categories