Showing posts with label Bracket. Show all posts
Showing posts with label Bracket. Show all posts

Introduction To A New Array Type: Key-only Array

By Howard Stone (2010 October 2)

In general, there are two types of array, indexed array and associative array. The array introduced in this article does contain keys only. So far, the best use of key-only array is to represent the dataset in table data type. Let us start from a table in database which contains a dataset as a result of SELECT query.

A normalized table usually has less group relationship between records, that is more to stateless. For this nature, the applications of normalized table tend to deal with a single record once at a time. On contrast, the denormalized table usually has group relationship between records, which may generated from SELECT query that includes GROUP BY clause. This kind of dataset then would be process bulky for sake of relationship between each rows. The major usages include feet data to option group, list box, etc.

The key-only array in Javascript, for instance, for above table would be:

; var arr = new Array(13)
; arr['Language'] = new Array(1)
; arr['Language']['Order'] = 1
; arr['English'] = new Array(1)
; arr['English']['1'] = 0
; arr['Spanish'] = new Array(1)
; arr['Spanish']['2'] = 0
...
; arr['Arabic'] = new Array(1)
; arr['Arabic']['12'] = 0

Actually, this is not so-called new type, it is just a multidimensional associative array, for which some values become keys. Please note, the values of 1 or 0 here are useless. To having values is indeed a compromised setting to enable current design of languages to parse the key-only array without any change. However, the concept of key and value changed since. The container of full information is the keys. The values here thus can be used as flag at programmer's discretion.

Why such? Because it enables to access selected information simply through hierarchical traverse by using keys without complicated parse process. The key-only array does naturally contain the internal relationship between rows, which was generated by original SELECT statement in SQL query. In addition, in comparison with traditional arrays, this would use less codes.

Please note, the key-only array can include or exclude the title of the columns in original table. If any field is null, please turn it into string 'NULL' first. It would be then accessible in key-only array. Please use bracket '' for all keys because the fields in original table may contain whitespace, which would cause problems when key-only array being used in AJAX or other Dynamic HTML.

Let us see how to use this key-only array. When calling it at higher dimension, such as arr['English'] would assign a set of new sub arrays that contain all cells after dimension "English". To get list of the dimension immediately after "English", which is often used for cascade triggering, following codes can be used:

; var immediateList = new array()
; for (key in arr["English"]) immediateList.push(key)

In JSON, it would be:

; var arr =
{"Language":{"Order":1}
,"English":{"1":0}
,"Spanish":{"2":0}
...
,"Arabic":{"12":0}
}

Only at very root, there is array bracket []. All rest are in brackets {}. To access sub arrays started from "English" or "1" after "English" assume there is further sub arrays:

arr["English"]
arr["English"]["1"]

If "1" is something other than numeric, it can be called:

arr["English"].something

To access keys at next dimension after "English":

; var immediateList = new array()
; for (key in arr["English"]) immediateList.push(key)

Summary:

1. Key-only array can use all existing functionalities of indexed array and associative array.
2. Since the information is key itself, there is no need to do any value search. It thus achieves directly random access without traverse.
3. It makes contained relationship information between original rows usable.
4. It uses less code.
5. It can be in JSON format too.

Special notes:

1. Since values are not in use, it can be used to represent last column. However, it is not recommended because it would require special treatment for leave of key tree.
2. Replace null with string 'NULL" at SQL query if the data source is database.
3. Always use bracket to make sure all keys are in string datatype.
4. When calling key-only array, always use array calling method rather than identifier calling method, that is arr["English"]["something"] instead of arr.English.something. This is to avoid possible error because in some languages like JavaScript identifiers can't begin with a numeral.

Code Conventions

This is the general one of a serials articles cover different languages.

Bracket

Put opening bracket and closing bracket at same vertical position enabling easier visual check.

Comments

Since full stop/period merely used by any language as ending sign of a statement, it is suggested all comments are to be finished by full stop/period for readiability purpose.

Comparison of IF Statement

Put matched at the left hand side to avoid possible mistake of assignment. For instance:

; if ('String'==varA)

instead of:

; if (varA=='String')

IF ELSE Statement

If there is more than one set of conditions, please use following method to deal with the complex logics:

1. Employ a middle layer, say Action, between Conditions and Functions. Unlike Functions, Actions are just flags of Functions and some of them can override others.
2. Use several IF Statements instead of a single IF ELSE Statement to cover every situations selected by you.
3. Because some Actions may override others, so, careful arranging the orders of IF Statements is necessary.

For detail, please refer to IF ELSE Statement (http://koncordpartners.blogspot.com/2010/04/if-else-statement.html).

Indentation

Use of tabs should be avoided because there still is not a standard for the placement of tabstops. Different code editor will show it differently. The unit of indentation is two spaces, to enable indenting many levels.

Code Conventions: JavaScript

Organizing

There can be six major parts:

1. Passing Variable Register: This is to register any variable across the HTML files. Do not use crossing file variable directly in body of JavaScript, instead declare here. For instance:

; var localVar = parent.superVar

2. Passing Function Register: To register the functions calling other functions located in different HTML file. Do not call crossing file function directly in body of JavaScript, instead declare here. For instance:

; function closeProcess()
{
; parent.closing()
}

Put Passing Variable Register and Passing Function Register at top of JavaScript file to enable easier updating during coding phrase.

3. Local Global Variable Declaration.

4. Event Functions: Include all event functions here, such as onload, etc.

5. HTML Action Functions: If the function is called by HTML file, initialized by the user, it should be included here.

6. Internally Called Functions: Functions called by event functions or action functions.

End of Statement

JavaScript allows the developer to decide whether or not to end a line with a semicolon. If the semicolon is not provided, JavaScript considers the end of the line as the end of the statement. It is suggested to use semicolon instead of nature line break. Furthermore, you can indeed use semicolon in front of each statement, not only emphasis the line break, but also to increase visual impact on the indentation. All examples in this post are in this format.

Comments

It is suggested to use closed comments tag as much as possible: <!-- -->. By doing this, it would be relatively easier to keep coding parts clearer. In addition, if you are using PHP Wrapping JavaScript Debugging Method, as introduced here:
http://koncordpartners.blogspot.com/2010/04/how-to-enforce-download-of-javascript.html, it is essential to use the closed comments.

DHTML

Use + to concatenate every line of HTML codes, such as:

; var htmlBody = ''
+ ' <table> ...
+ ' <tr> ...

Whitespace within string serves no purpose for HTML. However, it can make visual alignment for coding purpose.

Function Declaration

Always use most orthdox variablized function declaration:

; funcation func()
{
...
}

Avoid to use variablized function declaration like var func = function() {...}, unless it is necessary. If you do use variablized function declaration, make sure it had been placed before the caller. For details please see http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html.

Form With PHP Behind

Use '' instead of null. Accordingly, the PHP end should be:

if (0!=strlen(trim(@$_POST["theInputItem"]))) {...};

When use function to assign value to form, string parameter would need to be assigned with '' in consideration of it might be null or undefined:

; document.theForm.theInputItem.value = (parameter) ? parameter : ''

For details, please refer to http://koncordpartners.blogspot.com/2010/04/trouble-with-internet-explorer.html.


http://javascript.crockford.com/code.html

Heredoc and Nowdoc in PHP

Heredoc is to double-quoted string. So the inside can be parsed if there is variable. There is bug associated with Heredoc, namely the line with the closing identifier must contain no other characters, except possibly a semicolon (;). Example:

$err = ‘Parse error, unexpected $end in this.php on line xx’;
<<<HEREDOC
This is to show error message “$err” if you put whitespace either at front or end of closing line.
HEREDOC

Nowdocs are to single-quoted strings however. So a nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. This is very useful to parse a large block of embedded dynamic codes. Example:

<<<’NOWDOC’
Within this block, though $err is a variable, the final result would be exactly same as what you are seeing now. The variable “$err” won’t be parsed.
NOWDOC

No escape needed for both methods.

In addition, although you can use any word for heredoc and nowdoc purpose, it is recommended using exactly these words to emphasis the difference as well as the help you to remember what these techniques are called.

http://ca2.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Labels