Are design patterns in JavaScript helpful? And what exactly are they? - javascript

I have been learning more and more javascript; it's a necessity at my job. We have a web application that uses a lot of javascript and I will be doing more and more every day. I have read bits and pieces about design patterns, but was wondering if someone could just give me a cut and dry example and definition. Are they something that would benefit me? Or is it more high level?

Design patterns are generic and usually elegant solutions to well-known programming problems. Without knowing what problem you're working in, I would say "Yes" they can help make your code more manageable.
This link and this link make some reference to design patterns in Javascript. They may be worth reviewing.

One of the most practical and easy to use JavaScript-specific design pattern I've encountered is the Module Pattern, which is a modified Singleton pattern that "namespaces" related code and prevents the global scope from getting cluttered with variables and functions that might conflict with each other in a complicated page.

Also there is a book about classic design patterns in javascript. You can download examples from it's site.
But from my experience its obviuosly harder to implement projects with great amount of javascript.

As design patterns are language agnostic, I would recommend reading one of the classic books on the subject. My favourites are:
Patterns of Enterprise Application
Architecture by Martin Fowler
(http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420)
Design Patterns: Elements of
Reusable Object-Oriented Software by
the "Gang of Four"
(http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=sr_1_1?ie=UTF8&s=books&qid=1229278937&sr=1-1). This is a bit of a classic.
However, these aren't beginner books by any means and you might get more value out of some of the many web resources and tutorials out there (Wikipedia has some reasonable explanations).
My own experience is that the object model in javascript is a bit trickier to understand than others such as PHP or Ruby and hence, applying design patterns isn't always that easy. Libraries such as Prototype provide functions for making inheritance easier to work with and this makes programming Javascript in an OO way much easier.
I recently used Javascript to implement the Active Record pattern using Prototype, which you can read about more about here if you want:
http://codeinthehole.com/archives/6-Active-record-javascript-objects-using-cookies.html

Related

how can i learn javascript coding patterns

First what i mean by patterns.. Basically in Js there are multiple ways to do something but some ways of doing things offer greater benefits in terms of portability, performance, modularity, and extension. One of the patterns i like most are of jquery.
But when writing my own code i feel urge to just keep on writing function after function...and i don't want to create an object just for the sake of organization. There should be a reason like reusability for object to be created.
I want to learn patterns that make more use of closures, prototype, objects and chaining. So i can write better code.
I know keeping code simple is best but when things are wide spread keeping code less intrusive and reusable is maybe more important.
Check this out:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book was also pretty useful:
JavaScript Patterns
Build Better Applications with Coding and Design Patterns
By Stoyan Stefanov
Publisher: O'Reilly Media
This book really helped me getting started. Apart from that I suggest googling up, reading various articles,blogs, whatever you think is useful.
Don't bother trying to learn every single aspect of JavaScript before you actually need it.
If you suddenly find yourself passing masses of variables to your functions then you might find it easier to use objects, but objects are generally only useful if the data they encapsulate is related in some way. That means since you are aware of objects then as soon as the need arises for them in your code, you'll realise that's the time to use them.
Since objects properties and methods are so easily added to variables in JavaScript it's probably overkill to write out functions to construct objects/override variable prototypes etc.
As a very broad generalization, in languages such as Perl and php, for most programs of less than 1000 lines objects are overkill.
Play it by ear and take the easy way out every time.
I watched this Google talk a few weeks ago and was inspired to read Crockford's entire book, "JavaScript: The Good Parts". Watch the talk and I think you'll find it's exactly what you're looking for, full of best practices for using closures & prototype. It's a little old and just covers core JavaScript, nothing about JQuery, ect. but if that's what you're looking for, this is your book.
http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742

Is OOP usage justified here in this javascript scenerio?

Is OOP justified here?
Today was my first day at work at a small start-up. The start-up has a whiz JS developer who has A LOT of custom js using OOP for features such as modal window. More importantly, he has made almost all data display(such as rows of data to be displayed with edit/delete buttons) into some form of javascript OOP representation.
One of the things we are trying to do is remove a bunch of use of modal and just display the contents outrightly on the main window. Usually this would just mean copy/pasting a bunch of html/php code that was otherwise shown in the modal window. However, since this dev has developed everything in OOP and all these UI-related objects are closely tied to each other, moving away from modal window appears to require a lot more labor/fixing.
When I took this job I was excited and thought I'd get some experience getting knee deep with practical OOP. But a day later, I am yet to see its utility and at worst seems very counterproductive.
Am I missing something? When is it a good/bad idea to use OOP in javascript?
I think it's a good practical approach, but as with OOP in any other language, it can be either implemented well or poorly. OOP techniques for JavaScript can properly separate code instead of having strictly utility methods, so I don't believe it's a bad idea. But from the sounds of it, you may want to try to refactor the design to make it more simplified, and then move code around...
There are concerns with doing everything in JavaScript, depending on what's being done in it, such as security, maintainability, cross-browser support, and more.
HTH.
OOP can be a very powerful tool to ensure that rewriting code is not necessary and that code is maintainable, but if it is improperly done, it can have the opposite effect. Design Patterns are employed to make sure that code is maintainable, and OOP is a big part of that. This book seems to be an authority on the subject.
Without knowing more specifics of his implementation, its hard to say whether or not is approach is good. However, there is a strong trend in web applications to do heavy OO design (along with MVC or MVP design patterns) on the client in Javascript. Additionally, much of the rendering of the page is done with Javascript as well- frameworks such as Backbone.js (or Knockout.js as mentioned above) for this purpose are very popular, and quite interesting.
Javascript itself is actually an extremely good Object oriented language (see what Douglas Crockford has to say about it), and is currently undergoing a sort of renaissance, especially with younger developers.
Since pretty much everything in JavaScript is an object, it's difficult to avoid some degree of OOP-iness in your code. OTOH, most JavaScript frameworks focus more on the functional aspects of the language.
In any event, I suspect the problem you are really getting at is that there is insufficient decoupling between the UI and the data model. If so, then look at frameworks — such as knockout.js — that explicitly separate them.
I will say that OOP has a tendency to bend the brain into the wrong shape. I remember that in the early days of OOP and OOAD, the idea that objects should be responsible for rendering themselves to a GUI was extremely common. As problematic as this is, it was a direct consequence of the core OOP principle that the behaviour of an object should be coupled with its data.

Advanced JavaScript/JQuery Design Patterns

What are the best resources on Design Patterns catering specifically to web development with JavaScript and JQuery?
I'm particularly interested in information on programming my own libraries, reusable components, widgets, etc. and the merits of various techniques (for instance in the case of components/widgets comparing those employed in jQuery UI vs. rolling your own).
I'm also curious about the intricacies of JavaScript as a programming language, and the finer points of object-based programming with JavaScript.
Big fan of Douglas Crockford and the Yahoo video series. Looking for additional examples.
One very instructional thing you might do is read over the jQuery source code. It's a treasure-trove of interesting and efficient coding techniques. You might then broaden your horizons by reading over the source for Prototype or some other library.
The nice thing about reading good code and trying to understand it is that it's really real; it is the good code, so you bypass a layer of rhetoric.
Similar to Pointy's answer, you should take a look at these two videos, which help you understand the source code of JQuery (it might be difficult for some to dive into the code from start to finish):
10 things I learned from the jquery source
11 more things I learned from the jquery source
Paul Irish, a member of the JQuery team, goes through some very interesting design patterns in the JQuery source in a humorous way. I think he picks some really interesting spots, which really gives you a lot of usable knowledge you can use elsewhere.
It's probably the resource that has given me the most knowledge about a particular field in the shortest time. It's just really valuable.
This guy has some really good stuff as far as the "intricacies of JavaScript as a programming language" part of your question is concerned:
http://devlicio.us/blogs/sergio_pereira/default.aspx
e.g.
http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx
The comp.lang.javascript group on Usenet is an excellent resource: pretty much everything related to browser scripting has been discussed there and is available in the archive, and some of the regulars, while not always the most polite, are incredibly knowledgeable.

Has anyone used JS.Class and liked it?

Has anyone used JS.Class and liked it? I 've used Joose before and find it really good in creating clean code that is very readable and maintainable. Any real life stories about JS.Class?
Sorry for the first-person answer here, but although I have not used JS.Class, from a Java/Javascript developer standpoint, it looks very good. Our team works on a Java project with most of our front end using home-brewed JavaScript (and not a small amount of it). We don't use any JS frameworks (jQuery didn't exist when our project started) and we've even implemented our own drag and drop/sort utilities that make extensive use of inheritance.
For convenience and for the ability to use inheritance, (and through much evolution) we ended up developing methods that come to nearly the exact same patterns as JS.Class (but not nearly as extensive).
Everything I read in the docs on classes and modules, inheritance, etc. seemed very natural — in fact, it looks like we could probably replace all of our class-creation methods (a method we called objectLib.createClass) with new JS.Class with no other changes to make.
We also ended up developing our own Set classes and other array and object utilities that JS.Class includes as part of it's core functionality.
So, while I can't say that I've used JS.Class and liked it, I can say that as a Javascript developer I have needed to solve nearly the exact problems that JS.Class appears to solve very well.
I have not used it and I do not personally find a good use for the classical inheritance pattern so far in my experience. I switched to Javascript programming from Java to run away from all those design patterns!
You may also (if you haven't already) take a look at these posts from Douglas Crockford on what he thinks of classical inheritance in javascript.
http://www.crockford.com/javascript/inheritance.html
http://javascript.crockford.com/prototypal.html

Object Oriented Javascript

In the course of programming we encounter large javascript files which are open source and written in an object oriented manner( like JQuery ).
If we need to modify these files we have to have a basic knowledge of the members and the flow. If we have multiple files then the task is much more difficult.
Where do I start to get the flow of this??
First of all I think that you have to understand how JavaScript object orientation works, JavaScript OO is Prototype-based, in which classes are not present, and behavior reuse is implemented by prototyping.
I've seen that this can be hard to catch at the beginning for programmers that have been working on conventional class-based object-oriented languages (like C++, C#, Java, etc).
Recommended articles:
Introduction to Object-Oriented JavaScript
JavaScript: The World's Most Misunderstood Programming Language
Classical Inheritance in JavaScript
Private Members in JavaScript
Class-Based vs. Prototype-Based Languages
There are two things I would do:
Read. If there's documentation files, read those. If there's comments, read those. If neither of those help you, then go to the source and read that.
When you talk about open source Javascript, I assume you mean this JS is collected into some kind of project; all client-side JS is open source :P. In that case, the authors may be willing to tell you about their code. Locate their email on the project page, and ask them to give you a high-level overview of the code so you can start reading it and understanding it yourself. They probably won't be willing to hold your hand through the entire thing, but having that as a starting point would probably help.
I have a copy of
Javascript: The Good Parts
and
Javascript: The Definitive Guide
sitting on my desk right now. Incidentally these are the only two Javascript books which Douglas Crockford thinks are any good ;)
They'll teach you how Javascript works, specifically how its object model is different to most (but not all) other object-oriented languages.
Other than that, do check out all the articles on Crockford's website, as have already been mentioned in other answers.
I agree with allyourcode there's no magic trick. You have to read the code and read the docs. And if the docs are no good, maybe you should think about using a different framework.
A good start is in understanding the difference between traditional OO and Javascript's Prototype model. (Crockford has some articless that implement traditional OO for Javascript in order to contrast the behaviors.)

Categories

Resources