Thursday, April 26, 2012

Consistent List Indentation

courtesy : https://developer.mozilla.org/en/Consistent_List_Indentation

 

Consistent List Indentation


One of the most common style changes made to lists is a change in the indentation distance -- that is, how far the list items are pushed over to the right. This often leads to frustration, because what works in one browser often doesn't have the same effect in another. For example, if you declare that lists have no left margin, they move over in Explorer, but sit stubbornly in place in Gecko-based browsers.
In order to understand why this is the case, and more importantly how to avoid the problem altogether, it's necessary to examine the details of list construction.

Making a List

First, we consider a single, pure list item. This list item has no marker (otherwise known as a "bullet"), and is not yet part of a list itself. It hangs alone in the void, simple and unadorned, as shown in Figure 1.
Figure 1
That dotted red border represents outer edges of the the content-area of the list item. Remember that, at this point, the list item has no padding or borders. If we add two more list items, we get a result like that shown in Figure 2.
Figure 2
Now we wrap these in a parent element; in this case, we'll wrap them in an unordered list (i.e., <ul>). According to the CSS box model, the list items' boxes must be displayed within the parent element's content area. Since that parent has no padding or margins yet, we get the situation shown in Figure 3.
Figure 3
Here, the dotted blue border shows us the edges of the <ul> element's content area. Since we have no padding for the <ul> element, its content wraps snugly around the three list items.
Now we add the list item markers. Since this is an unordered list, we'll add traditional filled-circle "bullets," as shown in Figure 4.
Figure 4
Visually, the markers are outside the content area of the <ul>, but that's not the important part here. What's key is that the markers are placed outside the "principal box" of the <li> elements, not the <ul>. They're sort of like appendages to the list items, hanging outside the content-area of the <li> but still attached to the <li>.
This is why, in every browser except Internet Explorer for Windows, markers are placed outside any border set for an <li> element, assuming the value of list-style-position is outside. If it's changed to inside, then the markers are brought inside the <li>'s content, as though they're an inline box placed at the very beginning of the <li>.

Indenting It Twice

So how will all this appear in a document? At the moment, we have a situation analogous to these styles:
ul, li {margin-left: 0; padding-left: 0;}
If we dropped this list into a document as-is, there would be no apparent indentation and the markers would be in danger of falling off the left edge of the browser window.
In order to avoid this and get some indentation, there are really only three options available to browser implementors.
  1. Give each <li> element a left margin.
  2. Give the <ul> element a left margin.
  3. Give the <ul> element some left padding.
As it turns out, nobody seems to have used the first option. The second option was taken by Internet Explorer for Windows and Macintosh, and Opera. The third was adopted by Gecko, and by extension all the browsers that embed it.
Let's look at the two approaches for a moment. In Internet Explorer and Opera, the lists are indented by setting a left margin of 40 pixels on the <ul> element. If we apply a background color to the <ul> element and leave the list item and <ul> borders in place, we get the result shown in Figure 5.
Figure 5
Gecko, on the other hand, sets a left padding of 40 pixels for the <ul> element, so given the exact same styles as were used to produce Figure 5, loading the example into a Gecko-based browser gives us Figure 6.
Figure 6
As we can see, the markers remain attached to the <li> elements, no matter where they are. The difference is entirely in how the <ul> is styled. We can only see the difference if we try to set a background or border on the <ul> element.

Finding Consistency

Boil it all down, and what we're left with is this: if you want consistent rendering of lists between Gecko, Internet Explorer, and Opera, you need to set both the left margin and left padding of the <ul> element. We can ignore <li> altogether for these purposes. If you want to reproduce the default display in Netscape 6.x, you write:
ul {margin-left: 0; padding-left: 40px;}
If you're more interested in following the Explorer/Opera model, then:
ul {margin-left: 40px; padding-left: 0;}
Of course, you can fill in your own preferred values. Set both to 1.25em, if you like -- there's no reason why you have to stick with pixel-based indentation. If you want to reset lists to have no indentation, then you still have to zero out both padding and margin:
ul {margin-left: 0; padding-left: 0;}
Remember, though, that in so doing, you'll have the bullets hanging outside the list and its parent element. If the parent is the body, there's a strong chance your bullets will be completely outside the browser window, and thus will not be visible.

Conclusion

In the end, we can see that none of the browsers mentioned in this article is right or wrong about how they lay out lists. They use different default styles, and that's where the problems creep in. By making sure you style both the left padding and left margin of lists, you can find much greater cross-browser consistency in your list indentation.

Recommendations

  • When altering the indentation of lists, make sure to set both the padding and margin.

Rotate Text with no jquery Mozilla / IE

courtesy :w3schools

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
#rotateDiv
{
position:relative;
display:inline-block;
}
</style>

<script type="text/javascript">

function rotate(value)
{
document.getElementById('rotateDiv').style.top=document.getElementById('rotateDiv').offsetWidth/2 +'px'
document.getElementById('rotateDiv').style.webkitTransform="rotate(" + value + "deg)";
document.getElementById('rotateDiv').style.msTransform="rotate(" + value + "deg)";
document.getElementById('rotateDiv').style.MozTransform="rotate(" + value + "deg)";
document.getElementById('rotateDiv').style.OTransform="rotate(" + value + "deg)";
document.getElementById('rotateDiv').style.transform="rotate(" + value + "deg)";
}

if (document.addEventListener)
  document.addEventListener("DOMContentLoaded", function(){alreadyrunflag=1; rotate(90)}, false)
else if (document.all && !window.opera){
  document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>')
  var contentloadtag=document.getElementById("contentloadtag")
  contentloadtag.onreadystatechange=function(){
    if (this.readyState=="complete"){
      alreadyrunflag=1
      rotate(90)
    }
  }
}

window.onload=function(){
  setTimeout("if (!alreadyrunflag) rotate(90)", 0)
}

</script>

</head>
<body>
    <div id="rotateDiv">HELLO</div>
</body>

</html>

Rotate Text JavaScript+CSS transform jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<style type="text/css">

.normal
{
    position:relative;   
    display:inline-block;
    background-color:yellow;
}

.rotate
{
/* Rotate div */
    transform:rotate(90deg);
    -ms-transform:rotate(90deg); /* Internet Explorer */
    -moz-transform:rotate(90deg); /* Firefox */
    -webkit-transform:rotate(90deg); /* Safari and Chrome */
    -o-transform:rotate(90deg); /* Opera */
}
</style>
</head>
<body>

<div class="normal">Chandu Loves Snigdhu</div>
<!--
    <a class="clicktorotate" href="javascript:void(0);">rotate</a>
-->
</body>
<script>
    /*
    $('.clicktorotate').bind('click',function(e){
         var e = $('.normal');
         if(!e.hasClass('rotate')){
            this.innerHTML='normal'
            e.addClass('rotate');
            return;
         }
         this.innerHTML='rotate'
         e.removeClass('rotate');
       
    });
    */
   
    $(function(){
        var e = $('.normal');       
        e.addClass('rotate');
        e.css('top',e[0].offsetWidth/2+'px');
       
    }
    );
   

</script>


</html>

Dependency Injection

Dependency Injection is a way to make an object work with different implementations of an interface it is dependent on without recompilation of itself.

interface B{
work();
}

class Bimpl() implements B{
(){
  walking;
}
}

class A {
 public B b = new Bimpl();

doWork(){
 b.work();
}

}

For object of Class A to walk it needs Bimpl object.Say for example we need another another implementation of B to replace current Bimpl and that will require a code modification and recompilation of A.

3 types,
Constructor
Setter
Interface



Vertical Scroll Fixed list indentation

<html>
<head>
     <script src="jquery.min.js" type="text/javascript"></script>
   
     <style>
        body  *{
            margin:0px;
        }
   
        .containerScroll {
            width:150px;
            height:250px;
           
           
           
        }
       
        .containerScroll  div.items{                   
            height:220px;                       
            overflow:hidden;
           
           
        }
       
        .containerScroll > div.items ul{
       
        }
       
        .containerScroll  div.items ul li.first{
            color:red
        }
     </style>
   
</head>
<script>
var t_scroll;
        $(
            function(){               
                t_scroll = setInterval(function(){
                    //alert($('.containerScroll > div.items ul li:first-child' ).length);
                    //alert($('.containerScroll')[0].offsetHeight);
                    //alert($('.containerScroll > div.items')[0].offsetHeight);
                    //alert($('.containerScroll > div.items ul li:first-child')[0].offsetHeight);
                    if( $('.containerScroll > div.items')[0].offsetHeight < ($('.containerScroll > div.items ul')[0].offsetHeight))                   
                        $('.containerScroll > div.items ul li:first-child' ).appendTo($('.containerScroll > div.items ul'))           
                },500)
               
                $('.containerScroll > div.items').bind('mouseenter' , function(e){
                    clearInterval(t_scroll);
                    $(this).css('overflow','auto');
                })
               
                $('.containerScroll > div.items').bind('mouseleave' , function(e){                       
                    $(this).css('overflow','hidden');
                    t_scroll = setInterval(function(){                                   
                    if( $('.containerScroll > div.items')[0].offsetHeight < ($('.containerScroll > div.items ul')[0].offsetHeight))                   
                        $('.containerScroll > div.items ul li:first-child' ).appendTo($('.containerScroll > div.items ul'))           
                },500)
                   
                })
               
                           
        })
   
   

</script>
<body>
    <div class="containerScroll">
        <div class="items">
            <ul>
                <li class="first">item1</li>
                <li>item2</li>
                <li>item3</li>
                <li>item4</li>
                <li>item5</li>
                <li>item6</li>
                <li>item7</li>
                <li>item8</li>
                <li>item9</li>
                <li>item10</li>
                <li>item11</li>
                <li>item12</li>
                <li>item10</li>
                <li>item11</li>
                <li>item12</li>                               
            </ul>       
        </div>
    </div>   
</body>
<html>


*********************************************************************************
 Above code does not display list indentation.Fixed it in below code

<html>
<head>
     <script src="jquery.min.js" type="text/javascript"></script>
   
     <style>
        body  *{
            margin:0px;
        }
   
        .containerScroll {
            width:150px;
            height:250px;
          
          
          
        }
      
        .containerScroll  div.items{                  
            height:220px;                      
            overflow:hidden;
          
          
        }
      
        .containerScroll > div.items ul{
      
        }
      
        .containerScroll  div.items ul li.first{
            color:red
        }
      
      
        .ie.containerScroll {
            width:150px;
            height:250px;
          
          
          
        }
      
        .ie.containerScroll  div.items{                  
            height:220px;                      
            overflow:hidden;
          
          
        }
      
        .ie.containerScroll  div.items  ul{
            border:1px solid red;      

        }
      
        .ie.containerScroll  div.items  ul li{
            margin:0 0 0 25px;           
            border:1px solid blue;
        }
      
        .ie.containerScroll  div.items ul li.first{
            color:red;
        }
      
     </style>
   
</head>
<script>
var t_scroll;
        $(
            function(){              
                t_scroll = setInterval(function(){
                    //alert($('.containerScroll > div.items ul li:first-child' ).length);
                    //alert($('.containerScroll')[0].offsetHeight);
                    //alert($('.containerScroll > div.items')[0].offsetHeight);
                    //alert($('.containerScroll > div.items ul li:first-child')[0].offsetHeight);
                    if( $('.containerScroll > div.items')[0].offsetHeight < ($('.containerScroll > div.items ul')[0].offsetHeight))                  
                        $('.containerScroll > div.items ul li:first-child' ).appendTo($('.containerScroll > div.items ul'))          
                },500)
              
                $('.containerScroll > div.items').bind('mouseenter' , function(e){
                    clearInterval(t_scroll);
                    $(this).css('overflow','auto');
                })
              
                $('.containerScroll > div.items').bind('mouseleave' , function(e){                      
                    $(this).css('overflow','hidden');
                    t_scroll = setInterval(function(){                                  
                    if( $('.containerScroll > div.items')[0].offsetHeight < ($('.containerScroll > div.items ul')[0].offsetHeight))                  
                        $('.containerScroll > div.items ul li:first-child' ).appendTo($('.containerScroll > div.items ul'))          
                },500)
                  
                })
              
                          
        })
   
   

</script>
<body>
<!--[if IE]>
 <div class="ie containerScroll">
<![endif]-->

<!--[if !IE]><!-->
    <div class="containerScroll">
 <!--<![endif]-->
   
   
        <div class="items">
            <ul>
                <li class="first">item1</li>
                <li>item2</li>
                <li>item3</li>
                <li>item4</li>
                <li>item5</li>
                <li>item6</li>
                <li>item7</li>
                <li>item8</li>
                <li>item9</li>
                <li>item10</li>
                <li>item11</li>
                <li>item12</li>
                <li>item10</li>
                <li>item11</li>
                <li>item12</li>                              
            </ul>      
        </div>
    </div>  
</body>
<html>

Wednesday, April 25, 2012

HTML DocType

courtesy

http://htmlhelp.com/tools/validator/doctype.html

 

Choosing a DOCTYPE

According to HTML standards, each HTML document requires a document type declaration. The "DOCTYPE" begins the HTML document and tells a validator which version of HTML to use in checking the document's syntax.
If standard HTML does not meet your needs but you still wish to gain the benefits of HTML validation, see the section on using a custom DTD.
The following DOCTYPEs are commonly used:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
This declares the document to be HTML 4.01 Strict. HTML 4.01 Strict is a trimmed down version of HTML 4.01 that emphasizes structure over presentation. Deprecated elements and attributes (including most presentational attributes), frames, and link targets are not allowed in HTML 4 Strict. By writing to HTML 4 Strict, authors can achieve accessible, structurally rich documents that easily adapt to style sheets and different browsing situations. However, HTML 4 Strict documents may look bland on very old browsers that lack support for style sheets.
Newer browsers such as Internet Explorer 5 for Mac, Netscape 6, and Mozilla use a standards-compliant rendering for HTML 4 Strict documents. These browsers use a "quirks" mode for most other document types to emulate rendering bugs in older browsers.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
This declares the document to be HTML 4.01 Transitional. HTML 4 Transitional includes all elements and attributes of HTML 4 Strict but adds presentational attributes, deprecated elements, and link targets.
Newer browsers such as Internet Explorer 5 for Mac, Netscape 6, and Mozilla use a standards-compliant rendering for HTML 4.01 Transitional documents that include the URI of the DTD in the DOCTYPE. These browsers use a "quirks" mode to emulate rendering bugs in older browsers if the URI is omitted:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
This declares the document to be HTML 4.01 Frameset. HTML 4 Frameset is a variant of HTML 4 Transitional for documents that use frames.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
This declares the document to be XHTML 1.0 Strict. XHTML 1.0 Strict is an XML version of HTML 4 Strict.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
This declares the document to be XHTML 1.0 Transitional. XHTML 1.0 Transitional is an XML version of HTML 4 Transitional.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
This declares the document to be XHTML 1.0 Frameset. XHTML 1.0 Frameset is an XML version of HTML 4 Frameset.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
This declares the document to be HTML 3.2. HTML 3.2 is well supported by most browsers in use. However, HTML 3.2 has limited support for style sheets and no support for HTML 4 features such as frames and internationalization.
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
This declares the document to be HTML 2.0. HTML 2.0 is widely supported by browsers but lacks support for tables, frames, and internationalization, as well as many commonly used presentational elements and attributes.

Creating Triangle Arrows in pure CSS

courtesy:
http://hedgerwow.appspot.com/demo/arrows

 The old spice come back with a new flavor.
I was reading an interesting post(in chinese) about how to enable the transparent border in IE, and I thought it's worthy to spread this technique to more people. So below is my take.
This trick does not require using filter: chroma(color=pink) for IE.


Examples

The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog

HTML

&lt;span class="arrow-n"&gt;&lt;/span&gt; &lt;span class="arrow-e"&gt;&lt;/span&gt; &lt;span class="arrow-s"&gt;&lt;/span&gt; &lt;span class="arrow-w"&gt;&lt;/span&gt;

CSS

.arrow-n,
.arrow-e,
.arrow-s,
.arrow-w {
  /*
   * In Internet Explorer, The"border-style: dashed" will never be
   * rendered unless "(width * 5) >= border-width" is true.
   * Since "width" is set to "0", the "dashed-border" remains
   * invisible to the user, which renders the border just like how
   * "border-color: transparent" renders.
   */
  border-style: dashed;
  border-color: transparent;
  border-width: 0.53em;
  display: -moz-inline-box;
  display: inline-block;
  /* Use font-size to control the size of the arrow. */
  font-size: 100px;
  height: 0;
  line-height: 0;
  position: relative;
  vertical-align: middle;
  width: 0;
}

.arrow-n {
  border-bottom-width: 1em;
  border-bottom-style: solid;
  border-bottom-color: #666;
  bottom: 0.25em;
}

.arrow-e {
  border-left-width: 1em;
  border-left-style: solid;
  border-left-color: #666;
  left: 0.25em;
}
                    
.arrow-s {
  border-top-width: 1em;
  border-top-style: solid;
  border-top-color: #666;
  top: 0.25em;
}

.arrow-w {
  border-right-width: 1em;
  border-right-style: solid;
  border-right-color: #666;
  right: 0.25em;
}


IE Target HTML

If you read this blog, there is a 99% chance you've had a hair-pulling experience with IE. But if you are worth your salt as a CSS coder, you should be able to deal with it. I am of the opinion that you can handle anything IE can throw at you without the use of hacks. Hacks are dangerous, since they are based on non-standard exploits, you can't predict how they are going to behave in future browsers. The tool of choice for fighting IE problems is the conditional stylesheet. IE provides comment tags, supported all the way up to the current IE 8 to target specific versions, as well as greater-than/less-than stuff for targeting multiple versions at once.

Why use conditional stylesheets?

  • You got problems, they need fixin'
  • Keeps your code hack-free and valid
  • Keeps your main stylesheet clean
  • Perfectly acceptable technique, sanctioned by Microsoft
And remember, these conditional tags don't have to be used only for CSS. You could load JavaScript, or even use them down in the content of your site to display special IE-specific messages.

The Code

This would go in your <head> with all the other regular CSS <link>ed CSS files. The opening and closing tags should be familiar, that's just regular ol' HTML comments. Then between the brackets, "IF" and "IE" should be fairly obvious. The syntax to note is "!" stand for "not", so !IE means "not IE". gt means "greater than", gte means "greater than or equal", lt means "less than", lte means "less than or equal."

Target ALL VERSIONS of IE

<!--[if IE]>
 <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

Target everything EXCEPT IE

<!--[if !IE]><!-->
 <link rel="stylesheet" type="text/css" href="not-ie.css" />
 <!--<![endif]-->

Target IE 7 ONLY

<!--[if IE 7]>
 <link rel="stylesheet" type="text/css" href="ie7.css">
<![endif]-->

Target IE 6 ONLY

<!--[if IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6.css" />
<![endif]-->

Target IE 5 ONLY

<!--[if IE 5]>
 <link rel="stylesheet" type="text/css" href="ie5.css" />
<![endif]-->

Target IE 5.5 ONLY

<!--[if IE 5.5000]>
<link rel="stylesheet" type="text/css" href="ie55.css" />
<![endif]-->

Target IE 6 and LOWER

<!--[if lt IE 7]>
 <link rel="stylesheet" type="text/css" href="ie6-and-down.css" />
<![endif]-->
<!--[if lte IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6-and-down.css" />
<![endif]-->

Target IE 7 and LOWER

<!--[if lt IE 8]>
 <link rel="stylesheet" type="text/css" href="ie7-and-down.css" />
<![endif]-->
<!--[if lte IE 7]>
 <link rel="stylesheet" type="text/css" href="ie7-and-down.css" />
<![endif]-->

Target IE 8 and LOWER

<!--[if lt IE 9]>
 <link rel="stylesheet" type="text/css" href="ie8-and-down.css" />
<![endif]-->
<!--[if lte IE 8]>
 <link rel="stylesheet" type="text/css" href="ie8-and-down.css" />
<![endif]-->

Target IE 6 and HIGHER

<!--[if gt IE 5.5]>
 <link rel="stylesheet" type="text/css" href="ie6-and-up.css" />
<![endif]-->
<!--[if gte IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6-and-up.css" />
<![endif]-->

Target IE 7 and HIGHER

<!--[if gt IE 6]>
 <link rel="stylesheet" type="text/css" href="ie7-and-up.css" />
<![endif]-->
<!--[if gte IE 7]>
 <link rel="stylesheet" type="text/css" href="ie7-and-up.css" />
<![endif]-->

Target IE 8 and HIGHER

<!--[if gt IE 7]>
 <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->
<!--[if gte IE 8]>
 <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->

Universal IE 6 CSS

Dealing with IE 6 and below is always an extra-special challenge. These days people are dropping support for it right and left, including major businesses, major web apps, and even governments. There is a better solution than just letting the site go to hell, and that is to server IE 6 and below a special stripped-down stylesheet, and then serve IE 7 and above (and all other browsers) the regular CSS. This is been coined the universal IE 6 CSS.
<!--[if !IE 6]><!-->
  <link rel="stylesheet" type="text/css" media="screen, projection" href="REGULAR-STYLESHEET.css" />
<!--<![endif]-->

<!--[if gte IE 7]>
  <link rel="stylesheet" type="text/css" media="screen, projection" href="REGULAR-STYLESHEET.css" />
<![endif]-->

<!--[if lte IE 6]>
  <link rel="stylesheet" type="text/css" media="screen, projection" href="http://universal-ie6-css.googlecode.com/files/ie6.0.3.css" />
<![endif]-->

Hacks

If you must...

IE-6 ONLY

* html #div {
    height: 300px;
}

IE-7 ONLY

*+html #div {
    height: 300px;
}

IE-8 ONLY

#div {
  height: 300px\0/;
}

IE-7 & IE-8

#div {
  height: 300px\9;
}

NON IE-7 ONLY:

#div {
   _height: 300px;
}

Hide from IE 6 and LOWER:

#div {
   height/**/: 300px;
}
html > body #div {
      height: 300px;
}

Argument against conditional stylesheets

We shouldn't need them. They are against the spirit of web standards.

Argument for conditional stylesheets

Yeah, but we do need them.

Tuesday, April 17, 2012

Private Members in JavaScript Douglas Crockford


Private Members in JavaScript


JavaScript is the world's most misunderstood programming language. Some believe that it lacks the property of information hiding because objects cannot have private instance variables and methods. But this is a misunderstanding. JavaScript objects can have private members. Here's how.

Objects

JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly.
If a value is a function, we can consider it a method. When a method of an object is invoked, the this variable is set to the object. The method can then access the instance variables through the this variable.
Objects can be produced by constructors, which are functions which initialize objects. Constructors provide the features that classes provide in other languages, including static variables and methods.

Public

The members of an object are all public members. Any function can access, modify, or delete those members, or add new members. There are two main ways of putting members in a new object:

In the constructor

This technique is usually used to initialize public instance variables. The constructor's this variable is used to add members to the object.
function Container(param) {
    this.member = param;
}
So, if we construct a new object
var myContainer = new Container('abc');
then myContainer.member contains 'abc'.

In the prototype

This technique is usually used to add public methods. When a member is sought and it isn't found in the object itself, then it is taken from the object's constructor's prototype member. The prototype mechanism is used for inheritance. It also conserves memory. To add a method to all objects made by a constructor, add a function to the constructor's prototype:
Container.prototype.stamp = function (string) {
    return this.member + string;
}
So, we can invoke the method
myContainer.stamp('def')
which produces 'abcdef'.

Private

Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.
function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}
This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.
function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}
The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.

Privileged

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.
Privileged methods are assigned with this within the constructor.
function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        return dec() ? that.member : null;
    };
}
service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null. service calls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

Closures

This pattern of public, private, and privileged members is possible because JavaScript has closures. What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. This is an extremely powerful property of the language. There is no book currently available on JavaScript programming that shows how to exploit it. Most don't even mention it.
Private and privileged members can only be made when an object is constructed. Public members can be added at any time.

Patterns

Public

function Constructor(...) {
this.membername = value;
}
Constructor.prototype.membername = value;

Private

function Constructor(...) {
var that = this;
var
membername = value; function membername(...) {...}
}
Note: The function statement
function membername(...) {...}
is shorthand for
var membername = function membername(...) {...};

Privileged

function Constructor(...) {
this.membername = function (...) {...};
}
Copyright 2001 Douglas Crockford. All Rights Reserved Wrrrldwide.

Thursday, April 12, 2012

Externalizable Vs Serializable

  • Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization capabilities.
  • Externalizable extends Serializable.
  • Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.
  • Saving the state of the supertypes is responsibility of the implementing class.
  • You might have seen in my previouse article on how to customize the default implementation of Serializable. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject.
  • In object de-serialization (reconsturction) the public no-argument constructor is used to reconstruct the object. In case of Serializable, instead of using constructor, the object is re-consturcted using data read from ObjectInputStream.
  • The above point subsequently mandates that the Externalizable object must have a public no-argument constructor. In the case of Seriablizable it is not mandatory.

Tuesday, April 10, 2012

Design Principles

Software design principles represent a set of guidelines that helps us to avoid having a bad design. The design principles are associated to Robert Martin who gathered them in "Agile Software Development: Principles, Patterns, and Practices". According to Robert Martin there are 3 important characteristics of a bad design that should be avoided:

  • Rigidity - It is hard to change because every change affects too many other parts of the system.
  • Fragility - When you make a change, unexpected parts of the system break.
  • Immobility - It is hard to reuse in another application because it cannot be disentangled from the current application.

Open Close Principle

  • Software entities like classes, modules and functions should be open for extension but closed for modifications.
OPC is a generic principle. You can consider it when writing your classes to make sure that when you need to extend their behavior you don�t have to change the class but to extend it. The same principle can be applied for modules, packages, libraries. If you have a library containing a set of classes there are many reasons for which you�ll prefer to extend it without changing the code that was already written (backward compatibility, regression testing, �). This is why we have to make sure our modules follow Open Closed Principle.
When referring to the classes Open Close Principle can be ensured by use of Abstract Classes and concrete classes for implementing their behavior. This will enforce having Concrete Classes extending Abstract Classes instead of changing them. Some particular cases of this are Template Pattern and Strategy Pattern.

Dependency Inversion Principle

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.
Dependency Inversion Principle states that we should decouple high level modules from low level modules, introducing an abstraction layer between the high level classes and low level classes. Further more it inverts the dependency: instead of writing our abstractions based on details, the we should write the details based on abstractions.
Dependency Inversion or Inversion of Control are better know terms referring to the way in which the dependencies are realized. In the classical way when a software module(class, framework, �) need some other module, it initializes and holds a direct reference to it. This will make the 2 modules tight coupled. In order to decouple them the first module will provide a hook(a property, parameter, �) and an external module controlling the dependencies will inject the reference to the second one.
By applying the Dependency Inversion the modules can be easily changed by other modules just changing the dependency module. Factories and Abstract Factories can be used as dependency frameworks, but there are specialized frameworks for that, known as Inversion of Control Container.

Interface Segregation Principle

  • Clients should not be forced to depend upon interfaces that they don't use.
This principle teaches us to take care how we write our interfaces. When we write our interfaces we should take care to add only methods that should be there. If we add methods that should not be there the classes implementing the interface will have to implement those methods as well. For example if we create an interface called Worker and add a method lunch break, all the workers will have to implement it. What if the worker is a robot?
As a conclusion Interfaces containing methods that are not specific to it are called polluted or fat interfaces. We should avoid them.

Single Responsibility Principle

  • A class should have only one reason to change.
In this context a responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes.
Single Responsibility Principle was introduced Tom DeMarco in his book Structured Analysis and Systems Specification, 1979. Robert Martin reinterpreted the concept and defined the responsibility as a reason to change.

Liskov's Substitution Principle

  • Derived types must be completely substitutable for their base types.
This principle is just an extension of the Open Close Principle in terms of behavior meaning that we must make sure that new derived classes are extending the base classes without changing their behavior. The new derived classes should be able to replace the base classes without any change in the code.
Liskov's Substitution Principle was introduced by Barbara Liskov in a 1987 Conference on Object Oriented Programming Systems Languages and Applications, in Data abstraction and hierarchy

Command Pattern : Java

In object-oriented programming, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Three terms always associated with the command pattern are client, invoker and receiver. The client instantiates the command object and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is an instance of the class that contains the method's code.
Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters.





/*the Command interface*/
public interface Command {
   void execute();
}
 
 
/*the Invoker class*/
import java.util.List;
import java.util.ArrayList;
 
public class Switch {
 
   private List<Command> history = new ArrayList<Command>();
 
   public Switch() {
   }
 
   public void storeAndExecute(Command cmd) {
      this.history.add(cmd); // optional 
      cmd.execute();        
   }
 
}
 
 
/*the Receiver class*/
public class Light {
 
   public Light() {
   }
 
   public void turnOn() {
      System.out.println("The light is on");
   }
 
   public void turnOff() {
      System.out.println("The light is off");
   }
 
}
 
 
/*the Command for turning on the light - ConcreteCommand #1*/
public class FlipUpCommand implements Command {
 
   private Light theLight;
 
   public FlipUpCommand(Light light) {
      this.theLight = light;
   }
 
   public void execute(){
      theLight.turnOn();
   }
 
}
 
 
/*the Command for turning off the light - ConcreteCommand #2*/
public class FlipDownCommand implements Command {
 
   private Light theLight;
 
   public FlipDownCommand(Light light) {
      this.theLight = light;
   }
 
   public void execute() {
      theLight.turnOff();
   }
 
}
 
 
/*The test class or client*/
public class PressSwitch {
 
   public static void main(String[] args){
      Light lamp = new Light();
      Command switchUp = new FlipUpCommand(lamp);
      Command switchDown = new FlipDownCommand(lamp);
 
      Switch s = new Switch();
 
      try {
         if (args[0].equalsIgnoreCase("ON")) {
            s.storeAndExecute(switchUp);
            System.exit(0);
         }
         if (args[0].equalsIgnoreCase("OFF")) {
            s.storeAndExecute(switchDown);
            System.exit(0);
         }
         System.out.println("Argument \"ON\" or \"OFF\" is required.");
      } catch (Exception e) {
         System.out.println("Argument's required.");
      }
   }
 
}