Benefits of creating new modules in my application - javascript

Could anyone explain me what is the pourpuse of create new modules in angularjs application, I have already read the documentation, but we are not quite sure about when is appropiate to create a new module or use our own application module when you create a new service, directive, etc..

I would like to add some thoughts after reading a bit more about the subject:
JAndy, you are right in the general concept, but to be more specific in when do you have to use angularjs modules I think I got a clear answer in this post
Basically we have 3 ways of structuring our angularjs projects:
angular-seed
Yeoman
Structure the project in Modules
Depending of how big is your project you can take one aproach or another.
Basically writing new modules in angularjs helps you to pack functionalities that are related, one of the advantages of this approach is if a new developer comes into your team he can get a general overview and find things easier than if you only have one module, another one is to reuse functionality accross other projects.

I'd like to answer this question in a more general style than being specific.
Why was the ISS not build as one gigantic station instead of multiple independent modules ? The reason behind modules is to separate responsibilities, decouple a construction, etc. In terms of programming it means to have logic, spread over multiple small modules. That way, you not only know exactly where to look if anything goes wrong or you need to extend some functionality, it'll also guarantee that your whole ISS( your application ) will not entirely fail if one of your modules fails. This of course, also requires certain aspects of
programming styles, most important in this context, to hold module interaction and communication loosely coupled (which I just assume).
So whenever you want to implement new stuff, which does not fit in any other existent code or module, you should create a new, independent module, which is specialized to fulfill a certain task.
Even if I'm not using AngularJS on regular bases, I'm sure the same idea of modularization will fit in there.

Related

What is the benefit of using multiple modules in angular?

I'm a familiar person with Angular Js, recently I've seen that in some projects multiple angular modules are created and assembled in main module.
The code looks like.
angular.module("main",['main.sub1','main.sub2','main.sub2'])
angular.module("main.sub1",[])
angular.module("main.sub2",[])
angular.module("main.sub3",[])
My questions are
When to approach such fashion of splitting modules ?
How it is useful ?
Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider for each separately)
If i inject a dependency in sub modules are they by default injected in main modules ?
I read few blogs but I'm not able to get a clear perception.
Can you please guide me through.
1.When to approach such fashion of splitting modules ?
Preferably, Always. But you don't really need to do it unless you have multiple apps that are using the exact same code, maybe the way you handle authentication in a few apps is identical, it would make sense to put the common code into a service and have that service as its own module. This offers code reuse, and we all know that code reuse is good.
2.How it is useful ?
Again, reusability is the key word here. You don't want to go around writing duplicate code. Code duplication is just plain wrong, and results in more expensive maintenance and more error prone code.
Another advantage is that modularising your applications explicitly outlines the dependencies of your application and separates the responsibilities of different parts of your app. Code reuse and separation of concerns are fundamental practices in writing maintainable code.
Another reason to separate your app into modules is performance. Right now I'm working on an app (web shop) which consists of 2 main sections: one section(app) for normal users/buyers/sellers, and another app for the admin. Now the users app needs some scripts/libraries the admin app doesn't, and vice versa. For example the admin app uses a kendo grid which requires a kendo.all.min.js script which when minified is 1.7MB! Now would it make sense to force all visitors to the site to download the heavy 1.7 MB script?
3.Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider
for each separately)
Yes. Ideally your applications will have different route/state configurations, so each app would have their own app.config(), this means you could define separate routes for each app using the shared modules. To my experience the main things you want to move into their own modules are services and directives, not applications routings.
4.If i inject a dependency in sub modules are they by default injected in main modules ?
Yes. If you inject a dependency X into a module A, and module A will be used by another module B then B will also inherit the dependency X.
A module is the kernel of functionality for Angular apps. Modules contain all of the code that we
write for our specific app and, thus, tend to grow huge in a monolithic way. Although this tendency
isn’t bad (modules are a great way to reduce global scope noise), we can divide our modules.
There are several differing opinions about when to create a module and when to nest functionality
in a global module. Both of the following methods are valid ways to break up our functionality by
modules:
1. When to approach such fashion of splitting modules ?
When you want to sepereate your app logic by functionality or by routes, is needed because as your code separated on modules, it easy to understand, to tests and etc. angular module system implementation of Module Pattern.
Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.
2.How it is useful ?
For starters, it's a lot cleaner for developers coming from an object-oriented background than the idea of true encapsulation, at least from a JavaScript perspective.
Your significant other is the new developer on the team who's been asked to fix a bug on one of the many screens in your app.
The developer sifts through the directory structure and sees all the controllers, models and services neatly organized. Unfortunately it tells him/her nothing about which objects are related or have dependencies on one another.
If at some point the developer wants to reuse some of the code, they need to collect files from a bunch of different folders and will invariably forget code from another folder somewhere else.
3.Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider for each separately)
Another method we can use to break up our app is to divide our modules by route. This breakdown
allows us to write isolated tests that focus on the functionality per route. Modularizing by route can
make more sense, depending upon the project; it allows us to divide our functionality efficiently
when we’re dealing with a lot of independent routes.
For instance:
angular.module('myApp.home', []);
angular.module('myApp.login', []);
angular.module('myApp.account', []);
angular.module('myApp', [
'myApp.home',
'myApp.login',
'myApp.account'
]);
This modularization makes sense specifically when we’re dealing with large numbers of routes
and/or when we don’t have too much cross-over between routes
4.If i inject a dependency in sub modules are they by default injected in main modules ?
shortly: yes. :)

In AngularJS app is using plain javascript objects good or bad practice?

Suppose I need some generic object which is not dependent on AngularJS (e.g. specific collection with some special behaviours implementedd).
I could implement it completely outside AngularJS and use it in services/controllers then. I could also do it as service/factory and use it in other components.
I don't know if it is good or bad practice to write write code outside of AngularJS and then use it in the app. One big win is that while testing such code it's easier as it doesn't require AngularJS dependencies.
Do you keep whole application code in the AngularJS world in your apps?
It's generally a good idea to favor the simpler approach, which in this case would be to use a plain JS object.
It will be more flexible due to less outside dependencies and there's less things to do if you want to unit test it as well.
A scenario where you might want to integrate it more deeply into angular is if it actually requires some dependency injection or other such features provided by angular, but if it does its job without any of that then I don't really see a reason to mix them up.
If you wanted to do it as a plain JS object and then perhaps inject it using angular's DI system to one of your angular components, it would be pretty straightforward to wrap the object into a factory separately for this.

How to divide up a JavaScript codebase into modules?

The JavaScript in my web application has grown into one huge file. I want to break it up into modules so it's easier to manage.
I don't know if there are any established best practices for anatomizing the codebase of a web application, or if it just varies too much from project to project?
In particular:
should each module be responsible for an app-wide concept, such as "layout", or "clientside storage", etc?
or should modules be for concepts specific to the app being built (like "comments" or "calendar"), and each module be responsible for managing its own layout, its own clientside storage, etc?
or a mixture of both?
If you take Separation of Concerns and Single Responsibility into account then each module/component etc. should be responsible for doing what it does and nothing else. Break down your modules by re factoring into small, easy to manage chunks that do it's job and nothing else.
In terms of your JS application you could take a look at some client side MVC frameworks (such as knockout, sproutcore, spine etc. to name but a few) these frameworks help to logically separate out views and layouts to controllers and models. You might also be interested in using something like require.js to load your modules as and when they are needed.
There is a very good book by Alex McCaw which is worth a read.
MVC is just one pattern, but it is a very popular pattern and addresses some of the concerns you have.
Best of luck.
All things being equal, you are better to create your modules around concepts specific to the app. This is more object oriented, and tends to group together code that is more likely to change together. This in turn makes your code easier to understand, more tolerant of change, easier to develop and extend (the benefits of "modularity").

Building CoffeesSript browser applications - namespace and scope issues

I am new to CoffeeScript and am trying to get a feel for the best way of managing and building a complex application that will run in the browser. So, I am trying to determine what is the best way to structure my code and build it; with consideration for scope, testing, extensibility, clarity and performance issues.
One simple solution suggested here (https://github.com/jashkenas/coffee-script/wiki/%5BHowTo%5D-Compiling-and-Setting-Up-Build-Tools) seems to be maintain all your files/classes separately - and the use a Cakefile to concatenate all your files into a single coffee file and compile that. Seeems like this would work, in terms of making sure everything ends up in the same scope. It also seems like it makes deployment simple. And, it can be automated, which is nice. But it doesn't feel like the most elegant or extensible solutions.
Another approach seems to be this functional approach to generating namespaces (https://github.com/jashkenas/coffee-script/wiki/Easy-modules-with-CoffeeScript). This seems like a clever solution. I tested it and it works, but I wonder if there are performance or other drawbacks. It also seems like it could be combined with the above approach.
Another option seems to be assigning/exporting classes and functions to the window object. It sounds like that is a fairly standard approach, but I'm curious if this is really the best approach.
I tried using Spine, as it seems like it can address these issues, but was running into issues getting it up and running (couldn't install spine.app or hem), and I suspect it uses one or more of the above techniques anyways. I would be interested if javascriptMVC or backbone solves these issues - I would consider them as well.
Thanks for your thoughts.
Another option seems to be assigning/exporting classes and functions to the window object. It sounds like that is a fairly standard approach, but I'm curious if this is really the best approach.
I'd say it is. Looking at that wiki page's history, the guy advocating the concatenation of .coffee files before compilation was Stan Angeloff, way back in August 2010, before tools like Sprockets 2 (part of Rails 3.1) became available. It's definitely not the standard approach.
You don't want multiple .coffee files to share the same scope. That goes against the design of the language, which wraps each file in a scope wrapper for a reason. Having to attach globals to window to make them global saves you from making one of the most common mistakes JavaScripters run into.
Yes, helper duplication duplication can cause some inefficiency, and there's an open discussion on an option to disable helper output during compilation. But the impact is minor, because helpers are unlikely to account for more than a small fraction of your code.
I would be interested if javascriptMVC or backbone solves these issues
JavaScript MVC and BackBone don't do anything with respect to scoping issues, except insofar as they cause you to store data in global objects rather than as local variables. I'm not sure what you mean when you say that Spine "seems like it can address these issues"; I'd appreciate it if you'd post another, more specific question.
In case you would prefer the node.js module system, this gives you the same in the browser: https://github.com/substack/node-browserify
File foo.coffee:
module.exports = class Foo
...
File bar.coffee:
Foo = require './foo'
# do stuff

Architecture of a single-page JavaScript web application?

How should a complex single-page JS web application be structured on the client-side? Specifically I'm curious about how to cleanly structure the application in terms of its model objects, UI components, any controllers, and objects handling server persistence.
MVC seemed like a fit at first. But with UI components nested at various depths (each with their own way of acting on/reacting to model data, and each generating events which they themselves may or may not handle directly), it doesn't seem like MVC can be cleanly applied. (But please correct me if that's not the case.)
--
(This question resulted in two suggestions of using ajax, which is obviously needed for anything other than the most trivial one-page app.)
MVC architecture of PureMVC/JS is the most elegant IMO. I learned a lot from it. I also found Scalable JavaScript Application Architecture by Nicholas Zakas helpful in researching client side architecture options.
Two other tips
I've found view, focus, and input management are areas that need special attention in single page web apps
I also found it helpful to abstract away the JS library, leaving door open to change mind on what you use, or mix & match should the need arise.
Nicholas Zakas's presentation as shared by Dean is a very good place to start with. I was also struggling to answer the same question for a while. After doing couple of large scale Javascript products, thought of sharing the learnings as a reference architecture in case someone needs it. Have a look at:
http://boilerplatejs.org/
It addresses common Javascript development concerns such as:
Solution structuring
Creating complex module hierarchy
Self contained UI components
Event based inter module communication
Routing, History, Bookmarking
Unit Testing
Localization
Document Generation
etc.
The way I build apps:
ExtJS framework, single page app, every component defined in a separate JS file, loaded on-demand
Every component contacts its own dedicated web service (sometimes more than one), fetching data into ExtJS stores or special-purpose data structures
The rendering uses standard ExtJS components, so I can bind stores to grids, load forms from records, ...
Just choose a javascript framework, and follow its best practices. My favorites are ExtJS and GWT, but YMMV.
Do NOT roll your own solution for this. The effort required to duplicate what modern javascript frameworks do is too big. It is always faster to adapt something existing than to build it all from scratch.
Question - What makes an application complex ?
Answer - The use of word 'complex' in the question itself. Hence, a common tendency will be to look out for a complex solution right from the beginning.
Question - What does the word complex means ?
Answer - Anything that is unknown or partially understood. Example : The theory of Gravity even today is COMPLEX to me but not to Sir Isaac Newton who discovered it in 1655.
Question - What tools can I use to deal with complexity ?
Answer - Understanding and simplicity.
Question - But I understand my application . Its still complex ?
Answer - Think twice, because understanding and complexity does not co-exist. If you understand a huge huge application, I am sure you will agree that it is nothing but an integration of small and simple units.
Question - Why all of the above philosophical discussion for a question on
Single Page Application (SAP)?
Answer - Because,
-> SPA is not some kind of core technology that is newly invented for which we need to reinvent the wheel for a lot of things that we are doing in application development.
-> Its a concept driven by the need for better performance, availability, scalability and maintainability of web applications.
-> Its a fairly newly identified design pattern, so an understanding of SPA as a design pattern goes long way in making informed decisions about the architecture of a SPA.
-> At the root level no SPA is complex, because after understanding the needs of an application and the SPA pattern, you will realize that you are still creating an application, pretty much the same way you did before with some modifications and re-arrangements in the development approach.
Question - What about the use of Frameworks ?
Answer - Frameworks are boiler plate code / solution for some commonly identified and generic patterns, hence they can take off x% (variable, based on the application) load from application development but then not a lot should be expected out of them specially for heavy and growing applications. Its always a good case to be in complete control of your application structure and flow but most importantly the code for it. There should be no grey or black areas in the application code.
Question - Can you suggest one of the many approaches to SPA architecture ?
Answer - Think of your own framework based on the nature of your application. Categorize application components. Look for an existing framework that is close to your derived framework, if you find it then use it, if you do not find it then I suggest going ahead with your own. Creating framework is quite an effort upfront but produces better results in long run. Some basic components in my SPA framework will be:
Data Source : Models / Collections of Models
Mark Up for presenting data : Templates
Interaction with the application : Events
State capturing and navigation : Routing
Utilities , widgets and plug-ins : libraries
Let me know if this helped in any way and good luck with your SPA architecture !!
The best thing to do is to look at example uses of other frameworks:
TodoMVC showcases many many SPA frameworks.
You can use javascript MVC framework http://javascriptmvc.com/
The web application that I am currently working on uses JQuery and I would not recommend it for any large single page web application. Most frameworks i.e. Dojo, yahoo, google and others use namespaces in their libraries but JQuery does not and this is a significant drawback.
If your web site is intended to be small then JQuery would be ok but if you intended to build a large site then I would recommend looking at all the Javascript frameworks available and deciding which one most meets your needs.
And I would recommend applying the MVC pattern to your javascript/html and probably most of your object model for the javascript could be done as the json that you actually return from the server through ajax and the javascirpt uses the json to render html.
I would recommend reading the book Ajax in action as it covers most of the stuff you will need to know.
I'm using Samm.js in several one page applications with great success
I would go with jQuery MVC
Check out http://bennadel.com/projects/cormvc-jquery-framework.htm Ben is pretty sharp and if you dig around on his blog he has some nice posts about how CorMVC is put together and why.
Alternative: take a look to ItsNat
Think in JavaScript but code the same in Java in server with the same DOM APIs, in server is way easier to manage your application without custom client/bridges because UI and data are together.
Or have a look at https://github.com/flosse/scaleApp
NikaFramework allows you to create single-page application. Also allows you to write HTML, CSS (SASS), JavaScript into separate files and bundle them into only one output file in the end.
I would recommend to explore Yeoman. It allow you to use existing "best practice" for your new project.
For example:
if you decide to use Angular.js, there is a Yeoman generator, that give you a structure for routing, views, services, etc. Also allow you to Test, minify your code, etc.
If you decide to use Backbone, checkout this generator

Categories