File structure preference - javascript

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.

Related

When to Encapsulate in 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

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.

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

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

Categories

Resources