Mastering Web Application

(Rick Simeone) #1
Chapter 1

The declarative style of programming is usually more expressive as it frees
developers from giving very precise, low-level instructions. The resulting code is
often very concise and easy to read. But for the declarative approach to work, there
must be machinery that can correctly interpret higher-level orders. Our programs
start to depend on these machinery decisions and we need to give up some of the
low-level control. With the imperative approach, we are in full control and can fine
tune each and every single operation. We've got more control, but the price to pay
for "being in charge" is a lot of lower-level, repetitive code to be written.


People familiar with SQL language will find all this sounding familiar (SQL is a very
expressive, declarative language for adhoc data querying). We can simply describe
the desired result (data to be fetched) and let a (relational) database figure out how
to go about retrieving specified data. Most of the time, this process works flawlessly
and we quickly get what we have asked for. Still there are cases where it is necessary
to provide additional hints (indexes, query planner hints, and so on) or take control
over data-retrieval process to fine tune performance.


Directives in AngularJS templates declaratively express the desired effect, so we
are freed from providing step-by-step instructions on how to change individual
properties of DOM elements (as is often the case in applications based on jQuery).
AngularJS heavily promotes declarative style of programming for templates
and imperative one for the JavaScript code (controllers and business logic).
With AngularJS , we rarely apply low-level, imperative instructions to the
DOM manipulation (the only exception being code in directives).


As a rule of thumb, one should never manipulate the DOM elements
in AngularJS controllers. Getting a reference to a DOM element in a
controller and manipulating element's properties indicates imperative
approach to UI - something that goes against AngularJS way of
building UIs.

Declarative UI templates written using AngularJS directives allow us to describe
quickly complex, interactive UIs. AngularJS will take all the low-level decisions
on when and how to manipulate parts of the DOM tree. Most of the time AngularJS
does "the right thing" and updates the UI as expected (and in a timely fashion).
Still, it is important to understand the inner workings of AngularJS, so that we can
provide appropriate hints to the framework if needed. Using the SQL analogy once
again here, most of the time we don't need to worry about the work done by a query
planner. But when we start to hit performance problems, it is good to know how
query planner arrived at its decisions so that we can provide additional hints. The
same applies to UIs managed by AngularJS: we need to understand the underlying
machinery to effectively use templates and directives.

Free download pdf