Anti patterns

I believe if there is something good then opposite also exist. Patterns is a good technique to apply for reoccurring problems, or when you set standards in the company sometimes you suggest all the team members that you all should code in this structure, or pattern. That is to have a enterprise wide common understanding and standard on the code. It will enable to maintain the code easily.

Well… The bad part of it is if you make a wrong call by mistake on a certain approach, you are doom. This is not a anti pattern, it’s just wrong, and you will have to fix it.

I found a nice book on javascript patterns, called Learning JavaScript Design Patterns, by Addy Osmani. This has a section covering anti patterns, read it if you have this book. Personally I think this is an amazing book that you should have in your library.

So what is an anti pattern? And why should we care?

I will be taking some part from this book,

The term anti-patterns was coined in 1995 by Andrew Koenig in the November C++ Report that year, inspired by the GoF’s book Design Patterns. In Koenig’s report, there are two notions of anti-patterns that are presented. Anti-Patterns:

  1. Describe abad solution to a particular problem which resulted in a bad situation occurring
  2. Describe how to get out of said situation and how to go from there to a good solution

To summarize, an anti-pattern is a bad design that is worthy of documenting.

Examples of anti-patterns in JavaScript are the following,

  1. Polluting the global namespace by defining a large number of variables in the global context
  2. Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of eval() internally.
  3. Modifying the Object class prototype (this is a particularly bad anti-pattern)
  4. Using JavaScript in an inline form as this is inflexible
  5. The use of document.write where native DOM alternatives such as document.createElement are more appropriate

If you know what above means, you must have started rewriting your javascript code now.
What if you asked yourself how you can solve the above problems, there’s no answer than rewriting your code. But how would you like to write your code. Without proper guidance you might write the same code again. So when I deal with my subordinates, I have a little principle that is to be a leader not a preacher. That is set an example yourself, rather preaching. That may be working because I am a code lover. Somehow my point is that you should always try to show/be an example,

Lets get back to business right…

Point 1
If I tell you the answer in a nut shell, then its “use Module Pattern”
Actually there are a bunch of patterns you can use, but this pattern gives you a very neat code in the end. Hope you are aware about that in javascript the functions and classes are same. According to this pattern you can move all of your public variables to a class and access them from another class. And you don’t have to worry about the scope anymore. See the below example.


var myclass = (function(){
   var index = 0;
   var func1 = function(param1){
      param1 = index + param1;
      index++;
      alert(param1);
   };

   return {
      myfunc1: function(param1){
         return func1(param1);
      }
   };
})();

“myclass” variable is actually representing the above mention class. And that class have a public function/method called “myfunc1” which accept a parameter “param1”. Function “func1” is not been exposed to the outside, its a private method. Sometimes you might have seen the use of “this” keyword to expose public functions. But this pattern is very neat. In the class level “return” keyword is the place that defines the public functions. Inside each call it decide what private functions should be called. You can have your own library set rather writing page level javascript codes.
How you access these method is given below.


myclass.myfunc1(1); --> alert(1);
myclass.myfunc1(2); --> alert(3);
myclass.myfunc1(3); --> alert(5);

I think this clears up any confusions in how you should write your code to avoid having too many global variables.

Point 2
This is pretty forward, as the above statement itself clears how you should do it. But for those who still struggle how to write this, I will explain using some code.

setTimeout("myfunc();",1000);

Above code might work, but its not the best. This has many limitations, that you can’t pass parameters, and when it executes first it do a eval over the string etc…
Look at the below code, which is correct in this case.


setTimeout(function(){
   myfunc();
} ,1000);

How about using a setInterval. For new coders, the differences between the setTimeout and setInterval, is setTimeout gets called only once after the specified time, but the setInterval will call the function specified, by the given time interval. Such as if we consider the above sample, if its been used by setInterval, then myfunc() method will get called in every second. And you will use clearInterval(x) to stop it.


var index = 0;
var x = setInterval(function(){
   index++;
   if (index == 11) {
      clearInterval(x);
      return;
   }
   myfunc();
}, 1000);

Good practice:

  • Every-time when you write a setInterval code make sure to get the reference. See above sample code, I have assigned the reference to the “x” variable.
  • Without clearing the previous reference, do not use the same variable to assign for another setInterval. This will create memory leaks in the client browser, as you are releasing the reference of a living code while it still executes. See below example.

var index = 0;
function process(){
   console.log(index);
   if (index == 10) {
      clearInterval(x);
      index = 21;
      x = setInterval(function(){ index--;process(); },1000); //using the same variable
      return;
   }
   myfunc();
}
var x = setInterval(function(){
   index++;
   process();
}, 1000);

Point 3
Personally I have not tend to change the object class prototype. So I prefer to avoid this section. Well of course you can use jQuery extenders instead of this. If somebody knows better in this subject please enlighten me.

Point 4
Using javascript inline always screw up your code without your knowledge. Because remember that even the little script tag that you initialize is added to the scripts at global level of the page. So you even can access global variables defined in some other script file, within your script tag section. Watch out for script errors and overriding global variables unintentionally.

Point 5
document.write() can be used to testing purposes or in tutorials. But in real world applications its always wise to use document.createElement(), because this is faster and reliable. Plus document.write can lead to clearing the whole html in your page, and you don’t have much control over what you write.
FYI: after using document.createElement(), you can use some element.appendChild() to get the new element rendered to the page.

I guess that’s all for this post. Hope this will be useful to someone.

Destiny is a globally defined variable, God has forgotten to use Module pattern when writing the worldcreation() class. Otherwise createHumen(isMen) function would have its own Destiny. But if you want you can own it, don’t wait till some one else does it for you. Said By… m3

Advertisements

My life

Welcome to my blog. I am Chinthana Jayawardena. A Technical Consultant in a software firm.

Blogging is something really cool, that allows us to share our thoughts, day to day problems and solutions etc… I do think internet has been the leader to bring innovations to the world. That is in the aspect of allowing a place to share ideas. Therefore more people get to know lot of experience that they never had by reading other people blogs. Actually blogs have saved my day because of some bloggers. I must say that everybody should start sharing to build a better world tomorrow.

In the end all these thoughts running in someones mind suddenly blast into a new innovative idea.

Now what I would like to cover in my blog is the problems that I counter day to day, or my team members, that is worth sharing.

Technology wise I am open to all. But my majors are,

  1. Microsoft technologies .NET, ASP.NET/ C#/ MVC, entity framework/Azure
  2. SpringFramework for .net
  3. nHibernate
  4. Javascript/jQuery
  5. HTML5/CSS3
  6. Deployment packages experience with Windows 2008 server, Azure servers

New applications trend has gone to UI Rich applications. Therefore we have a great challenge, and demanding requirement which everybody ask that is a cohesive model that give best performance with UI Rich experience.

My blogs will mostly focused in these matters. But of course I may give crash courses/tutorials kind a samples as time allows.

May god bless me and you and our families to do our duties to the world.

High five for the bloggers!