• RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
Home > Development Best Practices > Making The Most Of Your Code by Hiding Information

Making The Most Of Your Code by Hiding Information

May 12th, 2009

Recycling code is by far the best way to make the most of your code. Recycling…it’s not just for the environment anymore. Making sure your code is prepped and ready for reuse and it will save you a lot of time.

Hiding Information

Reusable code should be plug and play. Ideally you should be able to just drop in some code and it should work. At least that’s the goal. So how do you go about doing that. Hide your information like a dirty magazine from your mother. What do I mean by hide information, perhaps an example will help demonstrate.

1
2
3
4
5
var global = "global variable";
    function display(){
        alert(global);
    }
    display();

This is an example of how not to hide information. The display relies on a variable named global to be declared outside of the function. So if you were to take the function and drop it into another piece of code it wouldn’t work unless there was a variable named global. Outside the function has to know what’s inside for this to work, and we don’t want that.

So what should we do….view another example of course.

1
2
3
4
5
6
function display(value){
        alert(value);
    }

    var passedVariable = "Passed Variable";
    display(passedVariable);

This time around the outside code has no clue what’s going on inside the function. All it knows is that it passes in a variable and it displays it. You could take this code and drop it into any other code and it would work the same. You don’t have to worry about if a global variable is declared or not. Everything within the function is self contained.

Another good example of this is the Math Class in Javascript.

1
var min = Math.min(10,20);

You don’t have to worry about how the Math.min method works. All you know is you give it two values and it will return the one with the smallest value. No prerequisites, no fuss.

Hopefully this might save you some time.

Related Info

http://en.wikipedia.org/wiki/Information_hiding

  • RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
  1. June 14th, 2009 at 23:19 | #1

    That’s quite interesting. I thought you were going somewhere with this then suddenly an abrupt halt. I’m lucky those social icons weren’t the edge of some cliff.

Comments are closed.