Skip to main content

JavaScript Function Spaghetti Code

In this post we will have a look at the spaghetti code created by functions and how to avoid them. First lets quickly go through why this is a cause of concern.


Problems with Function Spaghetti Code

  • Variables/ functions are added to the global scope

  • The code is not modular

  • There's potential for duplicate function names

  • Difficult to maintain

  • No namespace sense.

Let's take for example the following set of functions and check whats the issue with them.
// file1.js

function saveState(obj) {
    // write code here to saveState of some object
    alert('file1 saveState');
}

// file2.js (remote team or some third party scripts)
function saveState(obj, obj2) {
     // further code...
    alert('file2 saveState");
}

Now the problem here is if your application is using saveState() then the execution of saveState() which one to call is determined by the script loading.  The later script overrides same functions already defined by earlier script.
For e.g.

If this script is references as
<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

Then the function defined in file2.js will be overriding the one defined in file1.js. If you change the order the order of overriding changes. So, you can see this is a cause of concern if you have a n application which depends of javascripts both internal and from third party. One way to solve this problem is with closures.

Closure

...an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. ~ Douglas Crockford
In JavaScript yo can nest function and the nested function has access to all the variables and functions defined by its parent. This seems very simple and straightforward, but this is a very complex concept under the hood. Its like a function still holds the variables around its environment even after the function seems out of scope. Let us quickly go through an example.

// The getDate() function returns a nested function which refers the 'date' variable defined 
// by outer function getDate()
function getDate() {
   var date = new Date();    // This variable stays around even after function returns

   // nested function
   return function () {
      return date.getMilliseconds();
   }
}

Now if you call this function as shown below, you will see that the inner function holds on 
the the date variable.

// Once getDate() is executed the variable date should be out of scope and it is, but since 
// the inner function
// referenes date, this value is available to the inner function.
var dt = getDate();

alert(dt());
alert(dt());


The output of the above alert will be the same value of date.getMilliseconds();

Let's take another look at closure and use a module kind of pattern..

var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();
    }
}

var dt = new MyDate();

alert(dt.getMilliSeconds());  // This will throw error as getMilliSeconds is not accessible.

Make the following changes
var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();
    };
    return {
        getMs : getMilliSeconds
    }
}

What you are doing above is encapsulating all your logic in a namespace, in this case MyDate, and only
returning public methods to the outside world as an object literal.

You can use this as shown below..

var dt = new MyDate();
alert(dt.getMs());  // This should work.

The above construct is very similar to "The Revealing Module Pattern", which we will cover in
subsequent posts.

Now let's solve the original problem of saveState.

function App() {
    var save = function (o) {
        // write code to save state here..
        // you have acces to 'o' here...
        alert(o);
    };
    
    return {
        saveState: save
    };
}

var app = new App();

app.saveState({ name: "rajesh"});

Your application can use this as follows, without worrying about other saveStates floating around...

var app = new App();
app.saveState({ name: "rajesh"});

To conclude, we had look at why function spaghetti coding is bad and how to avoid this by using closure and module pattern.

In subsequent post we will look at how to create namespace and dig into deeper of the module pattern.

Hopefully you will find this useful.

Comments

Nice blog here! Also your web site loads up fast!
What host are you using? Can I get your affiliate link to your host?
I wish my website loaded up as quickly as yours lol
Thank you for the auspicious writeup. It in fact was a amusement account it.

Look advanced to more added agreeable from you! However, how can we communicate?
Highly descriptive post, I enjoyed that a lot. Will there be a part 2?
Your mode of telling all in this post is really nice,
every one be capable of effortlessly know it, Thanks a lot.
This piece of writing gives clear idea for the new visitors of blogging, that actually how to do blogging.
Thank you a bunch for sharing this with all folks you actually recognise what you are talking about! Bookmarked. Kindly additionally talk over with my web site =). We can have a link exchange contract between us
hello!,I really like your writing very much! proportion we be in contact extra about your post on AOL? I require an expert in this house to solve my problem. May be that is you! Taking a look forward to peer you.
ehzilqxnx said…
tvvcmJ tvsmghqhnbcb, [url=http://avrznpcyxcuv.com/]avrznpcyxcuv[/url], [link=http://zyruijlomkem.com/]zyruijlomkem[/link], http://xpssrhajfjig.com/
Leeboxz2 said…
Gabsterz2...

Great blog post, saw on...

Popular posts from this blog

JavaScript - The this keyword

"this" is one of the most misunderstood construct in JavaScript.  To understand this first lets go through how to create a construction function in JavaScript.  A constructor function is a function which is used to create instances of objects in JavaScript.

You define a constructor function using the same notation that you use to define a normal JavaScript function.  The convention to follow is to capitalize the first letter of the function name.

This requirement is not enforced by the JavaScript language but it is a generally accepted practice and there are many benefits which we will shortly discuss.

Let's define a constructor function to hold our menu information.

function Menu() { }
So, in the above snippet you have a constructor function named Menu defined. At present this function doesn't do anything good.

Let's see how to invoke this function

var menu = new Menu();
Let's add some public properties to this function.
function Menu() { this.menuName = &q…

C# Abstract Class Vs. Interface - Building a simple rule engine

In this video post we will briefly go over the difference between abstract class and an interface.  This is one of the most confusing concepts for beginners to understand. In the following video we will walkthrough step by step through these concepts and build a simple RuleEngine as a demo.

Please do note that this rule engine is not fully functional and production ready, but is demonstrated to make the concepts clear.

Please leave your constructive comments and also suggestions about future videos, if you like to have on any specific topics.