Implementing Code Blocks

an article added by: Sonja Lande at 05312007


In: Categories » » AJAX » Implementing Code Blocks

Problem: You want to implement code blocks in your JavaScript applications, to optimize your code. Theory Implementing code blocks is a programming technique that at first glance seems to solve a problem that does not exist. Some might even say that a code block is nothing more than a fancy callback. Code blocks in JavaScript do bear similarities to callbacks. But in languages like Ruby, code blocks are part of the programming language and make for simpler code. You use code blocks whenever you would iterate a list or a return function where you want to associate multiple pieces of information with a caller. Solution Let’s first look at a simple example: some code to create a squared series.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    function GenerateSquaredSeries( lastValue) {
    var array = new Array();
    for( var c1 = 0; c1 < lastValue; c1 ++) {
    array.push(  c1 * c1);
    }
    return array;
 }

To generate a series of numbers that are the square, a loop is created that counts from zero to the desired highest value. For each iteration, the value c1 * c1 (square of c1) is pushed onto array. Once the looping has completed, the array is returned. The example illustrates a problem of looping: the loop, and the initialization of the loop, is generic infrastructure code. The bold code shows the application-specific code, called for each iteration of the loop. The application-specific code is sandwiched between the for loop code. Abstracting the sandwiched code requires a callback, which looks like the following.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    function GenerateSeries( lastValue, callback) {
    var array = new Array();
    for( var c1 = 0; c1 < lastValue; c1 ++) {
    callback(  array, c1);
    }
    return array;
 }

The modified GenerateSeries function has an additional parameter, which is the callback function called for each iteration. The callback function serves the purpose of carrying out the business logic, and thus passes the instantiated array and number to the callback. The callback can then process the passed parameters (array and c1) however it pleases. An example of this follows.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    function ExampleSeriesSquare() {
    var array = GenerateSeries( 10, function(  array, value) {
    array.push(  c1 * c1);
    });
 }

The ExampleSeriesSquare function has a single function call that calls GenerateSeries. An anonymous function is passed to GenerateSeries that will process the passed-in array and value. The code in the implementation of the anonymous function is identical to the application logic code in GenerateSquaredSeries, which is rather obvious. The example anonymous function is a code block. As mentioned previously, a code block is like a callback. What makes a callback different from a code block is that a code block is general in nature and represents a separation of two pieces of code. To convert the code from a callback scenario into a code block scenario, GenerateSeries and ExampleSeriesSquare are rewritten as follows:

    function GenerateSeriesMod( lastValue,  callback) {
    for( var c1 = 0; c1 < lastValue; c1 ++) {
    callback( c1);
    }
    }
    function ExampleSeriesSquareMod() {
    var array = new Array();
    GenerateSeries( 10, function( value) {
    array.push( c1 * c1);
    });
 }

In the converted code scenarios are two functions: GenerateSeriesMod and ExampleSeriesSquareMod. The GenerateSeriesMod function still has two parameters: a maximum value and a callback function. The ExampleSeriesSquareMod function still uses an anonymous function. The difference is that the declaration of the array has moved from GenerateSeriesMod to ExampleSeriesSquareMod. This move of the array in this simple scenario is what makes the difference between a plain vanilla callback and a code block. Look at the details of GenerateSeriesMod and you will see that the implementation of GenerateSeriesMod only relates to requirements asked of it. The requirements are to generate a series of numbers that can be processed by an external functionality. The requirements do not state to create an array or create a buffer. The details of what to do with the generated series are implemented in the code block. Thus, two code blocks can be independent of each other, but together fulfill the needs of iterating and generating a series. In this example, it might seem like overkill to use a code block, but you will quickly realize that using code blocks is a great way to process data sets. For example, we have all encountered loops embedded within loops. Very quickly in this situation, the code becomes complex and hard to follow. Using code blocks, you can separate the code, and the embedded loops within loops are reduced to smaller, easily understood code chunks. Code blocks have an advantage in that they can process single results, multiple results, or no results. Looking at the implementation of GenerateSeriesSquared at the beginning of this recipe, an array is returned to the caller regardless of how many numbers are generated. The caller has to query the array and figure out if any numbers have been generated. In contrast, using a code block, the callback will be called only when a number is generated. The following code shows a more formal way of using a code block.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    function CustomList() {
    this.array = new Array();
    }
    CustomList.prototype.iterate = function(  callback) {
    for( item in this.array) {
    callback( item);
    }
    }
    CustomList.prototype.addItems = function() {
    for( var c1 = 0; c1 < arguments.length; c1  ++) {
    this.array.push( arguments[ c1]);
    }
 }

In the example, a CustomList class is being defined. The custom list has two functions: iterate and addItems. The addItems function is used to add an item to a list, and the iterate function iterates each of the elements in the loop and calls a callback. The callback parameter represents a code block. An example of using CustomList is as follows.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    class_list_iterate : function() {
    var list = new CustomList();
    list.addItems( "hello",  "world");
    list.iterate( function( item) {
    info( "class_list_iterate", item);
    });
 },

CustomList is instantiated and assigned to the variable list. An item is added to the list using the addItems function. Notice that addItems is multiple-parameter-aware. Often in programming languages, you need to call the addItem method to add an item to a list as often as there are items. The addItems method is different in that you can specify as many parameters as you like, and each of those parameters represents a single item to add to the list. To iterate the list, a code block is defined, and in the implementation of the code block, the data can be processed however it pleases the caller. In this example, the items are output using the info method. Code blocks can also be used to generate and process return values. Let’s consider an example that creates a function used to find the closing statistics of a stock ticker. Following is the implementation of the code using a traditional non-code-block approach:

    function StockTracerTraditional( ticker) {
    if( ticker == "YHOO") {
    var obj = new Object();
    this.company = "Yahoo";
    this.close = 23;
    this.change = -1;
    return obj;
    }
    return null;
    }
    function CallerStockTracer() {
    var obj = StockTracerTraditional(  "YHOO");
    if( obj != null) {
    info( "return_value",  "Company=" + obj.company + " close=" + obj.close +➥
 " change=" + obj.change);
 }
 }

The StockTracerTraditional function has a single parameter: the ticker to be found. If the ticker is found, an object is instantiated and the appropriate properties are assigned. Once the properties have been assigned, the instantiated object is returned. The CallerStockTracer function implementation calls StockTracerTraditional with the appropriate ticker, and the returned object instance is assigned to obj. Then a decision is made to verify if obj is null or not. If the ticker has been found, then obj will not be null and the object can be processed. Otherwise, the function returns without doing anything. The example code can be simplified using code blocks. The following rewritten implementation of StockTracerTraditional uses code blocks results.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    function StockTracker( ticker, callback) {
    if( ticker == "YHOO") {
    callback( "Yahoo", 23, -1);
    }
 }

The StockTrader function is rewritten, and the same decision block to find the ticker is used. What is new is the use of the callback that is called when a ticker is found. Consider what happens if the YHOO ticker is found: the callback is called with three parameters. If a code block were not used, then an object would have to be instantiated and returned to the caller. Because a code block is used, there is no need to verify if data is returned, as illustrated by the following caller code.

    Source: /website/ROOT/ajaxrecipes/javascript/codeblocks.html
    return_value : function() {
    StockTracker( "YHOO", function(  company, close, change) {
    // Do something with the data
    info( "return_value",  "Company=" + company + " close=" + close + "  change=" +➥
    change);
    });
 },

Calling StockTracker with the ticker to find as YHOO will result in the anonymous function being called. In the implementation of the anonymous function would be the code that is executed when data has been returned successfully. With code blocks, the caller does not have to implement a decision structure, because the anonymous function will be called only if the ticker exists. Code blocks are a means to an end, and do not imply that you should never use decision blocks or create loops with application logic. Code blocks provide amechanism to simplify and decouple code from another. When you use code blocks, remember the following:

• Code blocks are like callbacks, except that code blocks promote the separation of logic, making pieces of code independent of each other.

• The advantage of code blocks is that they can process single results, multiple results, or no results. The calling code does not have to determine if the results worked.

• Using the dynamic nature of JavaScript, a function can process multiple parameters as a set.

• Code blocks can be used as an alternative to the return statement to send more complex data. As mentioned in Recipe 2-17, code blocks are the perfect way to return data to the caller without having to use a return type.

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. Understanding the Definition and Philosophy of Ajax
The focus of this article is to provide solutions to some common, general problems and questions that are bound to arise before or during development of Asynchronous JavaScript and XML (Ajax) and Representational State Transfer (REST) applications. These common questions are not always technical in nature, often leaning more toward theory or philosophy of development. The problem with these kinds of questions is that once you begin to think about them, you keep going in a circle and end up where you star...

2. Understanding the Definition and Philosophy of Web Services and SOA
Understanding the Definition and Philosophy of Web Services and SOA Wikipedia offers the following definition of Web services:4 The W3C defines aWeb service as a software system designed to support interoperable machine-to-machine interaction over a network. This definition encompasses many different systems, but in common usage the term refers to those services that use SOAPformatted XML envelopes and have their interfaces described by WSDL. For ex...

3. Understanding the Definition and Philosophy of REST
Understanding the Definition and Philosophy of REST REST is a controversial topic among Web service enthusiasts, because it’s considered to stand for the opposite of what Web services and SOA are trying to achieve. The problem with this thinking is that REST is not in contradiction with the abstract definition of SOA and Web services. REST is in contradiction with technologies such as SOAP, WSDL, and WS-* specifications. The following offers a quick definition of REST:...

4. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...

5. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

6. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

7. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...