When to Encapsulate in javascript? - javascript

I have been developing websites using jQuery for 3 years now and I've recently gained interest in OOP in Javascript and I'm still starting to get my hands on OOP.
I read from this article, and it says:
Encapsulation ...(its methods and properties) are hidden from the rest of the application.
but why would you wanna take the extra time to do that? When you are the programmer and you know you aren't gonna use that on another object anyway. Am I missing something imoportant here? I don't really see any need to do this on my current experiences.
So when exactly to Encapsulate in Javascript?

When you are the programmer and you know you aren't gonna use that on
another object anyway
Only if
You are working on it alone
And have the super memory to remember what-to-use and what-not-to-use years from the start of the project.
As you mentioned yourself, it will help you in saving a lot of documenation effort in terms of which-variable-not-to-use and which-variable-to-use.

Check this out:
In computer science, information hiding is the principle of
segregation of the design decisions in a computer program that are
most likely to change, thus protecting other parts of the program from
extensive modification if the design decision is changed. The
protection involves providing a stable interface which protects the
remainder of the program from the implementation (the details that are
most likely to change).
from: https://en.wikipedia.org/wiki/Information_hiding

Related

File structure preference

I'm a young developer and I'm trying to get some best practice down.
I hope my question isn't subject to too much opinion and I can get a standard answer here.
Basically I have a big ol' JS file I wrote, couple thousand lines long. There are three main types of things? (objects?).
exported functions I use on my node.js server to manipulate data submitted
variables used by the exported functions and nowhere else
functions that are called by the exported functions in this file and nowhere else.
I'd like to split them up so that I don't have to scroll so much when making edits. In my head it would make sense to have the three files, with the "exported functions" file calling the variables and functions it needs on top.
Is this common practice? Is there a best way to call variables and functions from another file? Any advice here would be greatly appreciated.
As long as you're asking for preference that's what you gonna get. But today I want to share part of my personal experience as a programmer that's why I'm writing an answer rather than just commenting.
Modular Programming is good
As long as a software can be managed and modified with ease keep it as it is. If it starts to become cumbersome then consider OOP.
Structured Flexibility
The real power of OOP lies in its flexibility to make any program easy to implement because the planning is usually done beforehand. With the help of UML diagrams you can decide how to best represent an application.
OOP is about acronyms
The most scaring part of OOP is its acronyms, which will take sometime to be digested and sometimes may even sound scary. But those acronyms will help you think of software from a better perspective in the long run.
Consider Design Patterns
Since javascript is not a real OOP language I used to think that design patterns were not applicable to it. Indeed, patterns is more about solving problems than teaching a best practice. Consider structural patterns for inspiration.
Programming is a journey
Because you're young I believe you have plenty of time for making mistakes and learning from them. Make a decision. Try something. Your learning curve will boost in the right direction.
Finally, stay close to StackOverflow. There's much to learn around here.

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.

Learning JavaScript for a total non-programmer

I code CSS/XHTML like it should be my mother language, and I do write valid, semantic code following guidelines of accessibility and such.
But I want to learn Unobtrusive JavaScripting, but with a total non-programmer brain I need some motivation / tips / etc., like what's the best way to learn it, and how long does it take/did it take you before you could feel the power of knowledge? :)
PS: I do have an understanding on how JavaScript works and changes the DOM etc.. I think it's more about learning the syntax by head instead of having to look it up.
See also:
Suggestions for someone starting javascript programming.
Just use it. Really, the more time you spend reading and writing the language, the more natural it becomes. Use Firebug or an equivalent console to test short ideas; take an existing web page and wire up events interactively from the command line, get used to the idea of writing behavioral code as a separate process from writing markup.
If you want a good book, i can recommend the excellent jQuery in Action - yes, it's targeted at jQuery users, but the concepts apply regardless of your choice in libraries.
Motivation, sorry can't help there.
Syntax is learned by rote. The rules are simple, and reasonably consistent, so in truth syntax isn't that hard.
What you conflate with syntax are likely the other aspects like what properties are available on what objects, what functions to call, what does your framework provide. That, again, is basically rote memorization.
Many frameworks add a little bit of syntax through clever use of the JavaScript syntax, and you'll need to learn those as well.
But when it all comes down to it, the only way to learn this stuff is to use it.
You can't read about it, you have to do it.
Find an issue that you want to work on, a feature for your site or whatever, and attack that.
If you find a tutorial or whatever on line that does what you want, TYPE IN THE CODE, don't cut and paste it. As you type it in, question every symbol or character, try to understand why you're typing what you are typing.
Make an effort to change things, even if it's just variable names, because then you get a better idea of what things are being used for, and how they're referenced. It also lets you focus on a small part of the larger program.
If you're changing the "window1" variable to "myWindow", then at least you can look at the code as "blah blah blah window1 blah blah window1" without having to understand all of it.
Start small, don't worry about "doing it right", etc. so much as just being successful. If the way it's done doesn't bother you, then you're good. If you look at it and go "That's not quite right" because you learned something later after you started, then go back and clean it up.
At this stage, function is greater than form. Much of the form simply comes from experience.
Depends on what you want to do. Are you a successful web designer who's considering getting into the development side? Forge ahead, but tread cautiously. JavaScript can be easy to start with, but it can get ugly very quickly. And it's very different from any server-side language (including Java). Some of your JavaScript skills will translate to other languages, (conditional and control-flow operators, for example). But some things are unique to JavaScript and will require some relearning if you move to another language.
Also, some things in JavaScript won't completely make sense unless you've done object-oriented development; even though JavaScript is "prototype-based" rather than strictly object-oriented, without the OO concepts to relate to, the prototyping system may be difficult to understand. The typing system also may not make much sense if you don't have a lot of experience with different typing systems (static vs. dynamic, explicit vs. implicit).
Use a good framework like jQuery or YUI, but be sure to understand what's going on behind the scenes. Shog9's suggestion to use FireBug is a good one, too. It will show you what's going on (without having to do a lot of alert() statements in your code).
Your HTML DOM and CSS experience will help some, but only in the sense of understanding what the JavaScript is trying to do. Having written HTML and CSS by hand won't help you learn to write JavaScript; HTML and CSS are document markup languages, not imperative programming languages.
So go for it, but don't expect it to be easy. You may make a lot of quick progress, only to find that you're not as far along as you think, and that things don't work the way the appear to. But with enough effort and research you'll probably get there.
I think learning Javascript is a great idea if you are all ready doing HTML and CSS. Javascript is a cool, but quirky language. Most people that use don't really know how to write good JS code. I highly recommend watching Douglas Crockford video, see http://video.yahoo.com/watch/111593
They will give the real scoop on Javascript.
I've recommended JavaScript: The Good Parts before (and can't recommend it highly enough), but if you're new to programming I suggest starting with Head First JavaScript.
(source: oreilly.com)
I think you've got an abundance of great answers and resources already, but I'd like to chime in, too, since I've seen a couple of jQuery recommendations:
I love jQuery, too, and use it nearly daily. That said, for a beginner, I would recommend that you be comfortable with javascript proper first before diving into jQuery. Being comfortable with the syntax, variables, scope, and at least some DOM concepts will greatly improve your understanding of how to do what you want with jQuery. If you try to speed too quickly past the fundamentals, you'll definitely get stuck on some common misunderstanding that jQuery won't be able to help you with.
http://codeavengers.com level 1 JavaScript is great for the complete beginner. I created the courses and have had lots of great feedback from beginners who have found my course a fun and effective way to learn JavaScript.

Should I learn/become proficient in Javascript?

I am a .NET webdev using ASP.NET, C# etc... I "learned" javascript in college 5+ years ago and can do basic jobs with it. But I wonder if it is useful to become proficient in it.
Why should I learn Javascript?
Is it more advantageous then learning JQuery or a different library?
Yes, definitely learn Javascript before you learn one of the libraries about. It's the whole walk-before-you-can-run thing.
Make sure you add these sites to your bookmarks:
Mozilla's developer site: This contains the reference to the Javascript API in Mozilla. This will help you make sure you're writing code that Firefox understands.
IE's site in Microsoft Developer Network: The same, for IE.
W3's reference of DOM for HTML: In most web applications today, the Javascript code manipulates the DOM, which is an internal keeping track of the objects displayed on screen (but you already knew that, right ?) This is the reference to the DOM API. It is language neutral, which means it does not target Javascript, but these methods exist in Javascript too.
Douglas Crockford' site: Doug Crockford is THE MAN when it comes down to Javascript. The articles in his page are a must read. Because Javascript has closures and first-class functions, he believes it is closer to Lisp and Scheme than to other languages. And he teaches you how to greatly improve your code with these language features.
Yahoo Developer network: You may also want to check this. I'm not a regular visitor to this site, though, so I can't really say much about it.
Yes, absolutely you should learn JavaScript if you are doing web development. I highly recommend JavaScript: The Good Parts, by Doug Crockford. And, JQuery is a great framework to use (this site uses it) -- it kind of depends on what you are trying to do -- YUI and ExtJS are also very nice.
The answer is simple.
Hands down yes. There's a reason that Google have made such a big fuss about the V8 JS engine for Chrome, why Mozilla are working on TraceMonkey for Firefox and why Webkit have been working on Squirrelfish for a while (now Squirrelfish extreme). It's because JS is becoming more popular by the day.
Javascript is one of those languages that spending a few hours learning will probably teach you 99% of what you will ever really use. I would imagine you are at the point in your learning of javascript that you know more than enough now and just learn one or more of the frameworks now.
I would recommend brushing up on your non-frameworked javascript first. Refreshing/learning basic concepts of dom manipulation and what not. Like learning how to build a linked list, stack or queue in C++ before learning how to use the STL (standard template libraries).
In addition to brushing up on straight javascript, it might be good to get into a framework that doesn't abstract and change the way things work so much, for instance Prototype. You code with it very much the same way you code with straight javascript. Read through the Prototype code, learn how to make classes, and do some fancy stuff. From experience, I can say reading through the Prototype.js helped me learn alot.
After messing around a bit, then I'd say go for jQuery. If jQuery didn't, literally, change the way you write code I'd say go for it first, but learning how to build classes and js inheritance and what not can be a very important lesson for someone who wants to become fluent in JS.
Learning javascript is recommended for any web application developer. Why?
You will better understand the possibilities, limitations and dangers related to developing a web application
It is a boost for your career, if you are working on a web application that has a user interface.
However, learning javascript is usually a trade-off between a programming language and another. You should consider whether javascript is relevant for your career or project.
Unless you want to really get into javascript, I think you'd be better off learning enough JS to leverage one of the tried and tested javascript libraries out there.
One thing nice about JavaScript is that it is quite different from mainstream languages such as C#, VB.NET or Java. Learning it, especially if you have occasions to use it, will give you another insight on programming, and that's always good. I think it's worth learning it.
If you are doing web development then at some point you are going to get exposed to Javascript or ECMAScript at some point in your career for any one of a number of reasons. At a minimum you should know enough Javascript to be able to be able to validate user input; however, the web is moving in the direction of using more an more Ajax so you should also know enough Javascript to properly leverage one of the major libraries out there such as jQuery.
As some of the other users have noted, you can learn most of what you need of Javascript on a day to day basis in a single day or a couple of afternoons. If you want to get more advanced with Javascript then you are going to have to invest much more time in learning the language but odds are that unless you seek out this type of work that you are not going to encounter something that a preexisting library doesn't already exist for.
If all you want is to do some simple UI-effects and the like, I suggest you just pick a library and go for it!
Using libraries eliminates all the flawed implementations of JavaScript and provides you with an API which is the same across all browsers. And if you're working together with others it is also a great way of implementing code-standards and best practices.
Learning a second programming language is always good.
By the sound of it, JavaScript is a language that you use, to it will be of practical use too. As a web dev, it has been recommended to me in a review that i learn at least basic JavaScript.
A library such as jQuery is essential for web development thse days, so you could learn that too.
I don't think a lot of deliberate learning makes sense (but of course you need some basic knowledge), but I also think after some years of web development you'll become pretty proficient in the language anyway :)
If you are a webdev then yes, you should be proficient with Javascript. Javascript is a major part of making web apps as interactive as desktop apps.
With that being said, learn to use one of the cross-browser compatible libraries like JQuery, Prototype, etc. We do not need to have any more single browser crud created using Javascript, just because any real man/woman rolls their own.
A few things to learn in Javascript:
1. Basic syntax
2. The various flavours of function declaration.
3. Passing functions around and how to use passed in functions.
I recommend Jeremy Keith's books: DOM Scripting and Bulletproof Ajax. After you become more fluent in JS I would recommend a JS library(I use jQuery, but that is not important).
JS is important to learn. You cannot use a framework without the proper understanding of how it works. That is doing things backwards.
i thing you should have a good knoloedge base of language specification and DOM (Document Object Model). it means,you shoud know how find/create "page object" an edit properties. Also you should have an idea of "object oriented" javascript tecniques, which the starting point of a lot of framework. you don't need learn specific framework if you don't use it. simple keep in mind generic base concept!
I'll go with the opposite answer most are putting out there. Learning javascript as a developer these days is almost pointless. The language is similar enough to java/C# that it's syntax and semantics shouldn't be lost on you.
What you should learn is jQuery.
As you use jQuery you'll pick up the most common things you'll ever need from javascript anyway.
If you're involved with the Web in anyway then the answer is "Yes, always". Maybe an embedded or system's programmer could get by without JavaScript, but not a webdev.
Most of the libraries are designed to alleviate some of the pain of interacting with a multitude of browsers. They will not abstract away core JavaScript functionality.
Yes, you should learn JavaScript. Sooner or later you will need to use it!

Categories

Resources