Web IDE tips

March 27, 2010 2 comments

  It has passed 3 month since I use Web IDE for my front end tasks. Sometimes it works brilliant but in some cases it makes me pain after refactoring. This beast can do changes in unpredictable places and the worst is that it leaves the latent errors. I understand the challenge of creating IDE for dynamic languages such as javascript. Anyway the benefit of using is tremendous. I found out the following rules that could make you more happy with this IDE.

1) One javascript class per file (the size of class doesn’t matter).
2) Unique names for methods, field, and classes. It means that if it’s supposed to be named “onRender” you better to name it “onRenderMyComponent”. The long names is painless with this IDE as you have intellisense.
3) Do not make long namespaces, for instance, “MyCompany.controls.dd.zone.MyDragZone”.
4) Do not make huge classes. First of all, it is hard to maintain in terms dynamic languages, thus it leads IDE errors.
5) If you have external library files (such as ExtJs, JQuery, DOJO .etc) it is better to track changes out there before committing.

  As you see some of items are just good practices of programming javascript but some are related to Web IDE.

Categories: javascript, pattern

ExtJs. Struggling against boilerplate code.

March 23, 2010 Leave a comment

  I don’t like any scent of boilerplate code in any programming language, specially in dynamic languages. The dynamic languages are just not designed for it, having boilerplate code out there twice pain as in static languages.
  If you are using well-known “Preconfigured class” idiom, you will find the following idiom very useful. It delegates part of routine to just one method. I name it “config merge” idiom:

    
Config = {};
Config.merge = function(config, defaultConfig){
        config = config||{};
        defaultConfig =  defaultConfig||{};
        Ext.applyIf(config, defaultConfig);
        return config;
}
    

I bet the following routine of incoming config and default config is repeated in your code sometimes or more often:

    
MyCompany.MySuperPanel = Ext.extend(Ext.Panel, {
   constructor:function(config){
         config = config||{};
         var defaultConfig = {width:100, height:200, autoScroll:false};
         Ext.applyIf(config, defaultConfig);
         MyCompany.MySuperPanel.superclass.constructor.call(this, config);
}});
  

And with “merge” idiom:

  
 MyCompany.MySuperPanel = Ext.extend(Ext.Panel, {
    constructor:function(config){
          Config.merge(config, {width:100, height:200, autoScroll:false});
          MyCompany.MySuperPanel.superclass.constructor.call(this, config);
}});

Applying this idiom results in twice less code or even in one line code.

 MyCompany.MySuperPanel.superclass.constructor.call(this,
    Config.merge(config, {width:100, height:200, autoScroll:false}));

ExtJs. Preconfigured class.

October 28, 2009 2 comments

 I just have read the post
http://www.extjs.com/forum/showthread.php?t=26728.

 I disagree the concept of “Preconfigured class” considered as suggestion. Probably, in some cases it is OK but they are few of them. When I first time faced the “Preconfigured class” in extjs, I recall the ASP.NET ecosystem controls immediately. Because both “Preconfigured class” and ASP.NET control class use inheritance to customize, there are some pitfalls that are intrinsic to them:


public partial class MyControl : System.Web.UI.UserControl
{  
        private void CreateUrlResolver(){
        ...

        private Renderer GetRenderer(){
        ...

        protected void Button1_Click(object sender, EventArgs e)
        {
                //some logic
        }
...
  1. The class is not testable as it is part of UI framework so you cannot unit tests it. You need to employ other techniques as is extra effort.
  2. The class is usually littered with a lot of code. There are  event handling, creation methods, and view methods that are related to rendering. These all violate SRP and it is nightmare to maintain such classes in system.

 The javascript environment is much more flexible but people still use inheritance. I have seen a lot of samples where people extend the Ext.Component in order to add one event handler only, thereby making constrains for them to unit test and utilize it again. For instance, there is a panel with button that is charged with task of saving current state. In case of “Preconfigured class” I would have something like this.


var StatePanel = Ext.extend(Ext.Panel,  {
        frame:true,
        renderTo:'panel',
        constructor:function(config) {
           config.items = config.items || [];
           var button = new Ext.Button({text:"Ok", width:50});
           config.items.push(button);
           StatePanel.superclass.constructor.call(config, this);
           button.on("click", this.onClick, this);
        },

        onClick:function() {
                 // save the current state
         }
});

 Let’s assess the implementation above:

  1. Complexity. It invokes extending mechanism to emulate inheritance – that means extra manipulation with JavaScript’s prototypes. It is complex and emits the extra objects and closures that support inheritance.
  2. Reusability. What is really annoying is that the code that is charged with saving state is sealed. It cannot be used anywhere else. Sure, you can derive the base panel class and inject it there, thereby making messy at the abstract level. I mean that you shouldn’t share functionality with the base class. If you would use it as store of common methods it just loses its cohesion. You cannot maintain the class that is littered with a lot of aspects of system in future.
  3. Testability. This class is part of UI framework so the unit testing is an issue. You need some scaffolding to run it.

 If you dare to test it, you need html holder (it is div element with id) for your panel and then you have to init it in “set up”.


function set_up(){
     _testPanel =   new StatePanel({renderId:”testId”});
}
function testMethod(){
     .....
}

 You always need to keep in mind both ExtJs and UnitTestRunner lifecycles. But the most routine would be clean up code after the test as each test is interlaced with html.

 Let’s assess the same “StatePanel” but all handling is moved to “StateHandler” class that acts as controller:

 
function StateHandler(button) {
            this.init = function(component) {
            this._component = component;
            button.on("click", this.onClick, this);
           }

           this.onClick = function() {
                  // save the current state
            }
}

var button = new Ext.Button({text:"Ok", width:50});
var stateHandler = new StateHandler(button);
new Ext.Panel({frame:true, renderTo:'panel',items:[button],plugins:[stateHandler]});

What we have gained here:

  1. Complexity. I have plain object with single responsibility and it’s cool.
  2. Reusability. I can plug it to any component.
  3. I can simply test it without any scaffolding as I have plain object not connected to UI framework.

 This implementation recalls the MVC pattern, especially PassiveView. The idea is to make the view a dumb slave to move all code to the controller. It doesn’t mean that view is untouchable, it rather means that view should encompass methods that are familial to view. It could be methods that deal with the rendering which probably requires the intimate overrides. The new API of view could be subject to extend it.

 In sample above I used the plugins property to inject controller.

    
         var button = new Ext.Button({text:"Ok", width:50});
         var stateHandler = new StateHandler(button);
         new Ext.Panel({frame:true, renderTo:'panel',items:[button],plugins:[stateHandler]});
    
  

 You can use any kind of injection. The “plugins” property as pattern is not requirement. Use any creational patterns not to duplicate the creation of panel as well as gain flexibility in re-using the code and applying conditional algorithms there.


MyApplication.windows.FormBuilder.CreateMySuperPanel = function(){   
           //some conditional logic related to creation
           //
           var panel = new Ext.Panel({frame:true, renderTo:'panel',items:[button]);
           var button = new Ext.Button({text:"Ok", width:50});
           var stateHandler = new StateHandler(button);
           stateHandler.init(panel); 
 
}

 You can approach it in many ways, the main is to keep in mind separation of concerns. The initial concern is to wire all dependencies. I bet it’s much better to have class named “builder” that creates the panel at your will rather than to extend that panel for injection of only creation routine.

  
  var StatePanel = Ext.extend(Ext.Panel,  {
    myConfigConstant:'someConstant',
    frame:true,
    ...
    constructor:function(config) {
           config.items = config.items || [];
           var button = new Ext.Button({text:"Ok", width:50});
           config.items.push(button);
           StatePanel.superclass.constructor.call(config, this);
           button.on("click", this.onClick, this);
        },
   

 The next concerns are view and controller where the controller is the “StateHandler” and view is “Ext.Panel”. This approach will evolve your architecture in future. Though it cannot be considered as remedy. You cannot apply it to everywhere, for instance, a gender control. I wouldn’t implement controller and builder for it I would rather implement “Preconfigured class”.

  
 Ext.extend( Ext.form.ComboBox, {
      typeAhead: true,
      triggerAction: 'all',
      lazyRender:true,
      mode: 'local',
   
   constructor :function(){
       var male = "male";
       var female = "female";
   }

});


 

 I call such component the “primitive component”. It’s not worth to apply builder and controller as separate classes. It is pretty enough to pre-configure. I don’t believe that the gender component will ever grow. In other words if it’s simple per se, don’t add extra complexity. It is not worth to segregate extra classes to highlight their relationships.

Categories: anti pattern, ExtJs, javascript

JavaScript “finally” block is anti pattern.

September 21, 2009 4 comments

  I bet many of us hate debugging JavaScript code. The absence of strong-typing makes you pain when trying to figure out the error. So, you must employ the best patterns and practices of JavaScript and implement client code accurately. In some cases a debug tool becomes a useless tool.

  For instance, let’s review the following implementation:

function taskRunner(taskExecutor){
           try{
                    taskExecutor();
               }
       finally{ //debugger would navigate you to this line

                 //do some clean up

              }
       }

onload = function(){

          var task = function(){

               //process something

               //and then eventually facing exception

               return i+j;// - this line of code throws exception
             }

          taskRunner(task);
}

  The finally block of taskRunner function can be considered as anti-pattern. Whatever you do the debugger navigates you to finally block instead of real place of error at least for IE in this trivial sample. The one tool I know to figure out an error is a common sense. You have to search usages and analyze the code. Even if you manage not to use such constructions, it does not mean you to be safe. Nowadays, there are a lot JavaScript frameworks that probably use such constructions. I know one for sure. It’s the Ajax.net. The anti–pattern is exhibited in the Sys.net.XmlHttpExecutor.

  Once you have an error in one of your HttpRequest handlers, you will get into finally block immediately. How to figure out the error line? It’s good if you know what is going on, but what if you deal with legacy code and there is mix of Asp.Net update panels with ajax.net control and components(well-knowing name is extender). It is sad but your chances are low.

The singleton is evil, no room for doubts.

August 6, 2009 Leave a comment

dd I bet most of us understand or at least guess at it. Here, I composed the list of items that make singleton antipattern. Surely, some of them you have already seen but I just can’t ignore them.

  1. dSingleton is global variable. The global variable is not good, well-knowing issue, right? As it is treated as global variable, the singleton has the same issues.

  2. sSingleton is hardcoded and breaks underlying abstraction of application. It makes application dependent on details. Thus, it breaks Dependency injection principle and affects a mobility of the component as well as TDD possibilities.

  3. sInheritance is sealed (private constructor) so you have to duplicate the singleton functionality everywhere in code. Another way is to devise some wrapper that encompasses it. Both them don’t suit me. I don’t like workaround idea at all. I would rather change strategy then devising workaround. Anyway, whatever you do to outcome duplication, the singleton is closed for extending and therefore it breaks Open closed principle.

  4. 4 It breaks Single responsibility principle as it mixes more than one different responsibilities into single class. It has at least controller that limits the instances of class, creation, and business responsibilities. My point is that only business responsibility should concern client rather than if it’s singleton or not. Other way imposes a special behavior to client.

  5. . Memory leaks happen often as a singleton is not disposed during lifecycle of application. I faced two memory leak issued by singleton. Both were in context of web application. One of them was in Java web application couple years ago and another one is recent issue. Each of them took a lot of time to fix. I always believe that anything can be fixed soon but it’s not related to memory leaks. At any time it’s always hard to diagnose even if you have a lot of tools. You have to dig much far deep as well as to learn a lot of new things.

  6. 6 The singleton serves as global access point for some services. You cannot just exam your interfaces to find out its usages. Instead, you have to inspect each your method. It’s ok when it’s strong-typed language with functional IDE. But, what if you deal with weak-typed language such as JavaScript? Getting rig of singleton becomes is tedious task. Furthermore, it is really unsafe task because JavaScript hasn’t any static code analyzers and nobody wants to write unit tests.

  7. 7 Singletons carry state with them during application lifecycle. Sometimes, there are needs to reset them all. It can be application demand in itself. For example, applying crucial settings of application that requires corresponding clean up. If you cannot handle it you have to restart application which affects user experience. The unit testing also requires the test independence that itself implies resetting the state.

  8. 8 Threading issue. I don’t feel like commenting here as it is well-knowing issue. The one thing I can say surely is that in many cases it is better to have a number instances rather than one shared object in context of multi-threading. There is no need to increase complexity adding the synchronization code. At some point it will fail. Surely, there are might be performance requirements and you have to do singleton. But it’s well-knowing issue that performance is not at initial state but at final state. So my point is to do everything to avoid adding singleton into code. There are at least three ways you can do to pass reference:  by creation, by introduction, by construction.

 

 

wSo, singleton violates TDD, Open-Closed, Single Responsibility and Dependency Inversion principles. I think it’s pretty enough for to say singleton is evil.