Analysis and Project in Javascript

Asked

Viewed 624 times

22

When we work with object-oriented languages like Java and C# we have a whole process of analysis and design that helps us to know how to design the application to write more cohesive, less coupled and easier to maintain codes. The object-oriented analysis and design process serves any object-oriented language and therefore this process does not even depend on the chosen language.

At the moment I am working with Javascript. Basically, I have a layered division so that the application client is done with Javascript and the server (where all the logic is really) is done with C# and uses object orientation.

While the server part I know how to design and everything, the Javascript part I get quite lost. It turns out that Javascript has a different notion of objects. The language has no classes, no interfaces, is not strongly typed and this seems to me to be enough impediment to use the process of analysis and object orientation project as I know in Javascript.

So, is there any analysis and design process for Javascript? Principles, recommendations and standards that allow us to write more uncoupled Javascript code, easier to maintain and higher quality?

  • It’s a little wide. You can have a Javascript-rich site or just use jQuery for one or the other thing. When using little Javascript unit analysis and testing are dispensable as they are just simple events. When using full frameworks such as Emberjs or similar, it has its own conversions/way of working, which will help you. There are several frameworks that promise to fix the "little typing" of pure Javascript, but most sites maintain almost 100% of the logic in the same backend. It’s easier, Javascript is very bad in terms of maintainability.

  • 3

    @Andrey agrees that JS is not as verbose as other languages, but the issue of maintainability goes far beyond that. As long as your code is clear and properly modularized, with each module performing a specific function and being well tested (Unit tests), there is no problem with maintainability. And the part of "most sites maintain almost 100% of the logic in the backend, JS is very bad at maintainability" is also questionable -- we have had a great growth of Spas (Single-page Applications) in recent years, not to mention that Node.js is a very popular back-end nowadays.

3 answers

28


A starting point for organizing and structuring your Javascript code is the module Pattern. It is about isolating your code in smaller portions (modules). The main advantages of this:

  • Keep the global scope clean by replacing global variables with object properties;
  • Allows you to implement something similar to private properties and methods;
  • Organize code by separating it into components with defined responsibilities

The most common way to implement this standard is with function expressions immediately invoked (IIFE):

var NomeDoModulo = (function() {
    // corpo do módulo
    var privada = "foo";
    return {};
}());

Of course, the above example is useless, but it illustrates the basic structure of this implementation: a single global variable (or the outermost scope) is declared. Any variable declared within the module is not visible outside it. An object is returned (usually an integer namespace or a constructor function), exposing only the necessary.

If necessary, it is possible to inject a dependency into the module by passing a parameter to the IIFE. For example:

var NomeDoModulo = (function(html) {
    // corpo do módulo
    var privada = "foo";
    return {};
}(document.body.innerHTML));

A slightly more useful example, creating a "class":

var Cliente = (function(){

    // Variável privada do módulo
    var nomePadrao = "Cliente sem nome";

    // Construtor
    function Cliente(nome) {        
        // Propriedade pública de cada instância 
        this.nome = nome || nomePadrao;
    }

    // Método público
    Cliente.prototype.metodo = function() {
        // ...
    }

    // Expõe o construtor
    return Cliente;

}());

var c1 = new Cliente();
c1.nome; // "Cliente sem nome"
var c2 = new Cliente("Exemplo S.A.");
c2.nome; // "Exemplo S.A."

This type of structure served as the basis for the implementation of module formats adopted by the most used dependency managers in Javascript, such as the AMD, used by Require.js, and the Commonjs, used by Node.js. After study the module Pattern, I suggest you try how Require and Node manage modules. I personally prefer the AMD format of Require, but either one should help you a lot to structure your code.

  • Addy Osmani’s excellent book, thanks for the tip!

4

You, in addition to using a framework, can use coffeescript to make your life easier.

http://coffeescript.org

It will compile the code in JS, but the code will be much cleaner and simpler. Including creating classes. Look at an example of inheritance:

    class Animal
      constructor: (@nome) ->

      mover: (metros) ->
        console.log @nome + " moveu #{metros}m."

    class Cobra extends Animal
      mover: ->
        console.log "Rastejando..."
        super 5

    class Cavalo extends Animal
      mover: ->
        console.log "Galopando..."
        super 20

    cobrinha = new Cobra "Cobrinha"
    cavalinho = new Cavalo "Cavalinho"

    cobrinha.mover()
    // Rastejando...
    // Cobrinha moveu 5m.
    cavalinho.mover()
    // Galopando...
    // Cavalinho moveu 20m.

But in the end, remember, everything will become js, so it is good you know well the language, the features and limitations.

  • I like Coffeescript and use it, but 80% of what it does is abstract Javascript syntax only. It helps little when it comes to fixing Javascript defects. "It’s just Javascript".

  • But what do you suggest to solve the defects?

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.