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 Scope

In this blog post we will dig deeper into various aspects of JavaScript scope.  This is a pretty interesting topic  and also a topic which confuses many beginning JavaScript programmers. Understanding JavaScript scope helps you write bug free programs (hmm.. atleast helps your troubleshoot things easily) Scope control the visibility and lifetimes of variables and parameters.  This is important from the perspective of avoiding naming collisions and provides memory management service. Unlike other languages, JavaScript does not have block level scope.  For e.g. take for instance the following piece of c# code. public void Main () { int a = 5; if (true) { int b = 10; } // This will throw compile time error as b is not defined // and not within the scope of function Main(); Console.WriteLine(b); } If you write the same code in JavaScript, then the value of 'b' will be available outside the 'if' block. The reason for this is JavaScript does no

Personal Development : Time, Planning , Repairs & Maintenance

These are just my thoughts, but some you may find something interesting in it. Please think over it. We may know many things, but still we always keeps procrastinating it. I have written this as I have heard many people coming back and saying they don’t have time to do things they like. These are my thoughts buy may be useful to someone else too. Certain things in life needs periodic repairs and maintenance. To cite some examples , your CAR, your HOUSE, your personal laptop/desktop, your health etc. Likewise there are certain other things in professional life that requires repair/ maintenance /or some kind of polishing, so that you always stay on top of it. But they are not always obvious. Some of them are - Improving your communication skills - Increasing your vocabulary - Upgrading your technical skills - Pursuing your hobby - Increasing your knowledge/awareness etc… etc… And then there are certain things that we are always short

JavaScript for Web and Library Developers

This is my first blog post on my home domain and in this series of posts I will explore various facets of JavaScript language that will help us become better programmers.  The idea is tear apart the language and understand how to use the features and build libraries like jquery, knockoutjs, backbonejs. The idea is not to replicate this libraries, but understand the inner workings using better JavaScript coding practices, design principles and thereby make the web a better place to visit.. We will be covering the following topics, though not in order and there may be addition to this list. Foundations Patterns Closure this keyword Hoisting Anonymous function Currying Server side JavaScript Canvas etc. Hope you will enjoy this journey with me!