JavaScript Module pattern for Java Developers -- Part 1
Lately I have spent some time figuring out what a JavaScript Module pattern is as well as its purpose. After that I decided to write down the nitty-gritty.
Let's take a simple example of a Java BankAccount class. It has two private fields to store the owner of an account and its balance. In some real-world application a reference to a more elaborate data type such as a Client class which holds some other useful data can be used instead of name and BigDecimal class should be used for precision purposes. However for our discussion a simple String and double would suffice.
This class has two private fields to store its data. It is important that the balance field is hidden from the outside world in order two prevent incorrect manipulation of the account. This is done using a private keyword. However, the account should be manipulated somehow, so the class exposes three public methods to work with balance, which allow to increase and decrease the deposited sum in the correct way as well as check its current state. For our example purposes a private method which is used by a public method withdraw to check if an operation is possible is added.
JavaScript has objects but lacks a private keyword, so if one intends to hide some data and logic a special mechanism should be used to attain this. A JavaScript counterpart of a BankAccount object could look like this.
An object is enclosed in curly braces and names of fields are separated from values by colons. Notice that method names are on the left side of colons and when one is calling them parentheses should be added. The problem that one can modify the balance variable without any hassle. This is where a module pattern which helps to hide object fields and some methods comes into play. The latter is based on several important features of JavaScript language.
Firstly, in JavaScript one can define a function inside another function which is impossible for methods in Java. Moreover, an inner function has access to local variables of the outer one, but those same variables are not accessible outside account() function. The snippet below shows the aforementioned.
It is important to notice that the above function returns an object, the singular member of which is a getBalance() method. In fact, we created a getter method. Now we have an object which consists of a single getter method. It has no fields, but a single public method which is called on an object to print balance. A private field is encapsulated in the outer function which is used to produce the object. Should it work? Common sense dictates no. When a function has finished executing all its local variables cannot be accessed, especially from the outside. Does it work? Yes!
Secondly, there is such a notion in JavaScript as a closure. In a nutshell that means that the above code snippet works. If we store a reference to an object returned by the outer function and the object somehow operates on the outer function's local variables, those variables are not destroyed in memory, but can be accessed. So, instead of defining our fields and methods in a class construct which is absent in JavaScript, we define them in a function. All local variables serve as private fields, all internal functions are like private methods. Public fields and methods are exposed via return statement, where an object is returned, which is underscored by curly braces after the return keyword. Public names are on a left side of colons. To call a method one should suffix it with a pair of parentheses.
Finally, the above example could be shortened with a help of such JavaScript phenomenon as self-executing anonymous function. To make long story short, instead of defining a function and than calling it one can put a function inside of a pair of parentheses add an additional couple of parentheses to designate a method call and then finish with a semicolon, like in the snippet below.
This function executes immediately and puts an object described by the return statement into myVar variable.
The aforementioned technology of producing objects, which use an outer function to encapsulate object's data and behaviour is called a Module Pattern, a Revealing flavour of which we used in our example. The full code is below.
The variable which stores the returned objects start with an uppercase letter due to a convention to start module names with an uppercase, while regular variables are named with a lowercase letter first. Also the names of private methods are prefixed with an underscore and although it does not make them private, it improves code readability. It is also simply a convention.
To further one's knowledge of the JavaScript Module Pattern one could add a getter and setter to the ownerName variable. Also a Stack object, a LIFO abstraction, could be tried to be approached with the pattern described.
Links
1.Some useful class examples
2.A thorough description of JavaScript Module pattern
3.Yet another description of JavaScript Module pattern
Let's take a simple example of a Java BankAccount class. It has two private fields to store the owner of an account and its balance. In some real-world application a reference to a more elaborate data type such as a Client class which holds some other useful data can be used instead of name and BigDecimal class should be used for precision purposes. However for our discussion a simple String and double would suffice.
This class has two private fields to store its data. It is important that the balance field is hidden from the outside world in order two prevent incorrect manipulation of the account. This is done using a private keyword. However, the account should be manipulated somehow, so the class exposes three public methods to work with balance, which allow to increase and decrease the deposited sum in the correct way as well as check its current state. For our example purposes a private method which is used by a public method withdraw to check if an operation is possible is added.
JavaScript has objects but lacks a private keyword, so if one intends to hide some data and logic a special mechanism should be used to attain this. A JavaScript counterpart of a BankAccount object could look like this.
An object is enclosed in curly braces and names of fields are separated from values by colons. Notice that method names are on the left side of colons and when one is calling them parentheses should be added. The problem that one can modify the balance variable without any hassle. This is where a module pattern which helps to hide object fields and some methods comes into play. The latter is based on several important features of JavaScript language.
Firstly, in JavaScript one can define a function inside another function which is impossible for methods in Java. Moreover, an inner function has access to local variables of the outer one, but those same variables are not accessible outside account() function. The snippet below shows the aforementioned.
It is important to notice that the above function returns an object, the singular member of which is a getBalance() method. In fact, we created a getter method. Now we have an object which consists of a single getter method. It has no fields, but a single public method which is called on an object to print balance. A private field is encapsulated in the outer function which is used to produce the object. Should it work? Common sense dictates no. When a function has finished executing all its local variables cannot be accessed, especially from the outside. Does it work? Yes!
Secondly, there is such a notion in JavaScript as a closure. In a nutshell that means that the above code snippet works. If we store a reference to an object returned by the outer function and the object somehow operates on the outer function's local variables, those variables are not destroyed in memory, but can be accessed. So, instead of defining our fields and methods in a class construct which is absent in JavaScript, we define them in a function. All local variables serve as private fields, all internal functions are like private methods. Public fields and methods are exposed via return statement, where an object is returned, which is underscored by curly braces after the return keyword. Public names are on a left side of colons. To call a method one should suffix it with a pair of parentheses.
Finally, the above example could be shortened with a help of such JavaScript phenomenon as self-executing anonymous function. To make long story short, instead of defining a function and than calling it one can put a function inside of a pair of parentheses add an additional couple of parentheses to designate a method call and then finish with a semicolon, like in the snippet below.
This function executes immediately and puts an object described by the return statement into myVar variable.
The aforementioned technology of producing objects, which use an outer function to encapsulate object's data and behaviour is called a Module Pattern, a Revealing flavour of which we used in our example. The full code is below.
The variable which stores the returned objects start with an uppercase letter due to a convention to start module names with an uppercase, while regular variables are named with a lowercase letter first. Also the names of private methods are prefixed with an underscore and although it does not make them private, it improves code readability. It is also simply a convention.
To further one's knowledge of the JavaScript Module Pattern one could add a getter and setter to the ownerName variable. Also a Stack object, a LIFO abstraction, could be tried to be approached with the pattern described.
Links
1.Some useful class examples
2.A thorough description of JavaScript Module pattern
3.Yet another description of JavaScript Module pattern
Comments
Post a Comment