2009-11-12

Using jQuery to solve problems: automatic checkbox checking

Recently I have really been getting into the javascript library jQuery. The more I learn the more excited I get about how slick it is and so easy to use. It can really provide some rally cool features to your website and also provide a good way for me as a programmer to circumvent some tasks that can be hard to accomplish using server side programming.

Today I was presented with a task on an existing website using the DotNetNuke publishing platform. The customer has created a form using a module in the framework. The form is used to order some stuff and the visitor has to click a number of check boxes depending on what they want to order. There is also ha a bunch of pages with information about the products. Each page has a direct link on i to get to the order page. Now, if the visitor clicks this link the check box for that particular product should be checked, just to make thing easier.

I have no intention on going in to the framework to change the behaviour of the module so I thought I'd try some jQuery on this.

First off the only thing I really know is that the order form will have a header like this "<h1>Order form</h1>" (potentially the module can exist on multiple pages, even multiple times on the same page) and that the product page will have the product name in the url, which is also the text of the check box.

My idea was that first check if the order form exist on the page by looking for the header then check the referrer url and compare this to the check box names. This is the code:

$(document).ready(function()
{
if($("h1:contains(Order form)"))
{
setOrderCheckboxes();
}
});

// Automatically set checkboxes if the visitor previously viewed
// a page named the same as the checkbox
function setOrderCheckboxes()
{
$("input[type='checkbox']").each(function()
{
// The text element is always a sibling directly following the checkbox
var checkboxName = $(this).next().text();

// DNN url replaces characters in PageName
checkboxName = checkboxName.replace(" ", "").replace("-", "");

if(document.referrer.indexOf(checkboxName) != -1)
{
$(this).attr("checked", true);
}
});
}

Pretty slick right?

Using jQuery: Looping an array of objects misstake

I recently spent some time to get some jQuery code to work, but I just couldn't. After a while I realised my mistake and thought this would make a great blog post (mostly so I'll remember this myself).

The task was to find out how many paragraphs contained a certain text. For the purpose of this example lets say "xxx".

Here is the
jQuery I started out with (sorry about missing the indenting):

$(document).ready(function()
{
var pArray= $("p");

for(var i = 0; i <
pArray.length; i++)
{
if(
pArray[i].text().indexOf("xxx") != -1)
{
// Do something...
}
}
});


This crashed since
text() wasn't a function. Strange since it's in the jQury reference. I got it to work with textContent() instead but not in IE. After a while I realised my mistake. The pArray[i] is not a jQuery object, so adding $() did the trick. This was the result:

$(document).ready(function()
{
var
pArray= $("p");

for(var i = 0; i <
pArray.length; i++)
{
if($(
pArray[i]).text().indexOf("xxx") != -1)
{
// Do something...
}
}
});


Now don't forget this!

But wait! Sometimes you have to stop and think what you are doing. jQuery is more powerful than you think. Consider the following code, which accomplishes the same thing:

$("p:contains(xxx)")

Reminder to self: always stop and think and read the spec...

2009-09-03

TweetMyMac

While surfing around the other day I ran into a really cool tool called TweetMyMac. The tool enables you to send commands to the computer through Twitter to make it take a picture with iSight, say something funny or send a screen shot of whats going on at the moment. Really fun to play around with, but when I stretch my mind to find something useful to do with this I come up blank. But never the less, it's really fun.

It's quite easy to set up. You'll need to set up a new Twitter account only used for this task (prefereably one with a hidden timeline) and then see to it that you follow your main account from the new one. Then download TweetMyMac from the website and install. Now you're ready to go. Follow the instructions on TweetMyMac to be sure to get it all right. A misstake could actually let others send commands to your computer. I would not recommend anyone to allow custom shell commands though (optional) since this seems a bit unsecure.

A full list of commands can be found on the website (although some from the latest update are not inluded, but just look at the changelog).

Some commands can be quite useful, like "battery" which returns the current battery status or "shutdown" which powers down the computer. But for me, these are still just fun to play around with since I carry my MacBook with me almost all the time and it's my main computer at home. But for a desktop computer I guess it could be great to see if the task is finished (by screenshot) and then power it down. But even there a RDC is far better.

Anyway, I now keep a list of all commands with me in my mobile so I can have fun when I leave the room and then have my computer say something like "Hello, I am a computer and I can talk". It suprises people quite a lot.

Try it out and have fun and please comment this post if you find some cool way to use this.

2009-08-13

Flush DNS on the Mac

If you want to flush the DNS on you mac it's pretty simple. Open the Terminal window and type

dscacheutil -flushcache

This command applies to all user of Leopard. For other users you use

lookupd -flushcahe

This command is the equivalent of the Windows command "ipconfig /flushdns".

2009-08-03

Mac OS X Terminal Commands

I am a programmer and therefor I just have to have control over what's happening under the cover on my computer.

Mac OS X is really Unix-based and when using the Terminal window you can use different commands from the Unix world to talk to your computer and make it do things under the cover. I am not really a Unix/Linux programmer, although I have had some experience in this. This made me look for a simple chart of some sort that shows the most simple commands accessible to me when using Terminal. I found a quite good pdf containing just what I needed. So now I am looking under the cover of Mac OS X. I don't really know I'll be doing, but maby I'll do some posting of stuff I do here.

You can view the pdf here.

Taking a screenshot on the Mac

Sometimes I'm in need of making a quick image of my screen to show to someone, or maby capturing an error message. On a PC keyboard I use the "Print Scrn", but on my MacBook?

A quick search gave me an excellent solution to the problem here. Here you go:

Apple (Command) Key +Shift+3
Captures entire desktop to a file on the desktop as 'picture #' . This option lets you capture the whole screen. If you want just one window on your screen, you will have to edit the picture using image editing software.

Apple (Command) Key +Shift+4
Allows you to use your mouse to select a specific part of your desktop for capture. This will turn your mouse pointer into a cross, please hold down the mouse button and drag to select the part of the screen you want. When you release the button the screenshot will "snap" that part of the screen. Press 'Esc' to release.

Apple (Command) Key +Shift+4 then press Spacebar
Allows you to select which window to capture.

Even better than on my PC!

2009-07-26

Installing new memory units on the Mac

I've just installed my new memory units on the Mac and this was actually quite easy.

My MacBook Pro came with two 1 GB memory units and since I'll be using some quite memory intensive applications and also use a virtual PC I wanted more memory. So I ordered a 4 GB memory pack, which comes as two 2 GB memory units.

The first step was to remove the bottom cover for accessing the contents of the computer. My first attempt didn't work though. I was using a very small screw driver, but apparently this was to large. I managed to release three screws but not the others. I was perhaps a bit to careful but a the same time I really didn't want to break the screws and thereby not being able to remove them at all. A few days went by and finally I managed to get hold of a screw driver with the right size.

After removing the screws and then the cover the memory units were placed almost in the middle (sorry for not providing images of this). I saw that these where fastened with screws so I started removing these too. I later realized that this was totally unnecessary since all you have to do is expand the constraints to remove the top memory unit. Under this the second unit is placed and you remove this by expanding the constraints again.

After this you just click the new units into place, put the cover on again and you are all set. Not that hard at all.

After restarting the computer I noticed an improvement in speed, especially while using the virtual PC.

2009-07-16

Quicksilver application launcher for Mac

I wrote in another blogpost about launching applications on the MacBook and how I've always used a program on Windows called Launchy. After a tip in the comment section of this blogpost I have now tried out a program called Quicksilver.

The program works much like Launchy and gives me a quick way to start applications without having to go to Dock (as it's called on the Mac). It's really neat and I think I'll stick with it and use Spotlight for searchng documents and stuff like that.

Give it a try and write me a line of what you think.

A must have: VLC media player

After trying to watch some movies on the MacBook using either QuickTime or FrontRow (both preinstalled on the computer) I gave up and downloaded my favorite player of all time: VLC.

It plays almost every format you can imagine and it's free under the GNU General Public License. So go download it now. Just a tip. And for all you Windows users out there: Yes, there is a download for you to.

As soon as I get home I'll try installing another media player - Plex. A friend of mine (Mathias again) has recommended it and I suppose it's more like a media center, playing movies, music and showing photos and such. A nice thing about it is that it atomatically downloads information about the movies from IMDB and displays really cool imagery together with the information about the movie. But more about this as soon as I have had the chance to try it out.

2009-07-15

Some useful keyboard commands on the Mac

One thing that irritates me is when I can't find the right keyboard combinations for my favorite commands. I can tell you right away that the copy, paste, regret, mark all, save and other simple commands are a real pain on the Mac when comming from a PC. I'm used to the ctrl button on the end of the keyboard and then Z for regretting the latest command. On the Mac most of these commands still work but now in combination with the cmd button, placed next to the SPACE-bar. This makes the combination very hard to make using my left little finger, since I'm used to the ctrl-button. I've had my Mac a couple of days now and I have made this misstake a hundred times.

Before you hit me with "get used to it" I know this i just something I have to learn. But I still think it's annoying.

Anyway some other useful keyboard commands are these:




















ENDcmd + right arrow
HOMEcmd + left arrow
END OF PAGEcmd + up arrow
BOTTOM OF PAGEcmd + down arrow
PAGE UPctrl + up arrow
PAGE DOWNctrl + down arrow
DELETEfn + BACKSPACE
STEP ONE WORD RIGHTalt + right arrow
STEP ONE WORD LEFTalt + left arrow
BACKSLASH \shift + alt + 7
PIPE |alt + 7
[alt + 8
]alt + 9
{shift + alt + 8
}shift + alt + 9
$alt + 4
@alt + 2 (pretty obvious)
TILDE ~

fn + alt + ¨ (the key left of ENTER)


Commands on a Virtual PC or Remote Desktop PC



















ENDfn + right arrow
HOMEfn + left arrow
END OF PAGE?
BOTTOM OF PAGE?
PAGE UPfn + up arrow
PAGE DOWNfn + down arrow
DELETEfn + BACKSPACE
STEP ONE WORD RIGHTctrl + right arrow
STEP ONE WORD LEFTctrl + left arrow
BACKSLASH \ctrl + alt + + (the key right of zero)
PIPE |right alt + < (vmware)
[ctrl + alt + 8
]ctrl + alt + 9
{ctrl + alt + 8
}ctrl + alt + 9
$ctrl + alt + 4
@ctrl + alt + 2
TILDE ~
ctrl + alt + ¨ (the key left of ENTER)



I'll probably update this post acouple of times with other useful commands, so please check back. I know I'll check back every now and then before I've leart all this stuff.

Got some other tips? Please post a comment.

Remote Desktop on Mac to Windows

One thing I just can't live without is remote desktop connections. I use them all the time at work for connection to servers and other stuff, and also at home for easily connection to the computers I have.

To connect to other Mac computers you use something called sharing of screens. To connect to Windows machines you go to Microsofts Mac page (a bit ironic don't you think) and download the remote desktop program there. Then you just have to enter the ip or computer name to connect to and you're all set. Usually you have to connect through VPN before using this, but as long as you're on the network the other computer is on (like at home) you probably won't have to bother.

Thank to Mathias for this info.

2009-07-14

Launching applications on the Mac

I've always used a nice application on Windows XP called Launchy. For me, a real keyboard shortcut geek, this has been an absolute dream. This application allows you to use a combination of keys, like alt-SPACE to open the Launchy window. From here you can start typing a program name and you get a list of applications to launch. Without using the mouse. When you've used it some time you can launch your favorite applications with just a couple of keystrokes. A real timesaver. I can't even remember the last time I actually opened the program menu under the start menu.

On Vista/Windows 7 you can get the same functionality just by pressing the Windows button and start typing. But since I've always used Launchy I have continued using it.

On the Mac this functionality can be achived by using crtl-SPACE (default keyboard combination) and start typing. This opens Spotlight, which on first impression is quite good. Like the Windows button on Vista/Windows 7 this also searches recently used documents and other stuff. You can even change the order in which stuff appear by accessing the Spotlight settings and changing the order.

I'll try this out for a while before downloading Launchy (I don't even know if Launchy runs on a Mac).

Editing the Hosts file on a MacBook Pro

For someone in my line of work the Hosts file on a windows system has been essential in some cases. In short the file works as a DNS just for my computer. This means that I can use file to change the destination ip of a certain address. As an example I can change http://www.google.com to point to 127.0.0.1 or whatever if I want. All I have to do is add the ip and url in my host file and then clear the cache by opening a command promt and typing "ipconfig /flushdns".

I have now set out to do the same thing on a Mac and this is how it is done:
  • Open a terminal window
  • Type "sudo nano /private/etc/hosts"
  • Enter administrator password
  • Do the changes you want to the hosts
  • Press ctrl-X to save and confirm this and then ENTER to confirm saving
To try this out you can type "ping www.google.com" and check what ip the answer to the request comes from.

2009-07-12

Switching to MacBook Pro part 3 - Using the computer

This is part three in a series about switching from PC to MacBook. You can also read part 1 and part 2.

Usability
After going through some settings on the MacBook I have to say they have really succeeded i usability. When dealing with the settings for the mouse pad there is a short instruction video that describes each setting and how it affects the using of the mouse pad. Really good.

Using the mouse pad is also a real delight after going through the different settings. Switching programs and getting an overview is real good with four fingers on the pad and so on. This is one thing I really like about the MacBook. The mouse pad knows how many fingers you are using on the pad and can change how it works depending on this. For instance drawing one finger from top to bottom moves the pointer across the screen. Using two fingers for the same action scrolls the screen. Three fingers can switch between different images (when applicable) and four fingers gives an overview of all programs. Quite useful.

Since I'm writing this post in the evening I just noticed that the keyboard lights up nicely. Didn't notice it before in full light. I don't know how many times I have used a computer in a dark environment and I'm constantly forced to pull the screen down in order to light up the keyboard to see what I'm writing. Now it's all built in to the computer. Thank you very much.

Another thing about the light is that when you turn of all lights the screen automatically decreases its light, not to create to great a contrast. Pretty good stuff. How come I haven't had this before on a computer?

I have always been fond of shortcuts on the computer. I use them all the time for copying, pasting, switching programs, opening file explorer, closing windows and so on. Especially when using a laptop with no external keyboard and mouse. A lot of them seem to work on the Mac too, just by switching to the Apple key instead of the alt key. But not all of them. As soon as I get hold of a good Internet connection I'll try to find a chart over all keyboard shortcuts for a Mac. I just can't live without them.

Confusions
One thing that confused me in the beginning was the fact that all menus for each program is located not within the actual program window itself but at the top. This means that the top menu is specific for each program. This takes a bit of getting used to. For instance in iTunes, that I have been using on my PC too the menu bar is located at the top. When opening iTunes for the first time on the Mac I just couldn't find the menu to make my settings and so on. I started looking in the complete wrong place. After a while I noticed my mistake and felt quite dumb. It just takes a bit of getting used to.

Did I break it
When putting a CD in the drive my first thought was that it broke. I had the computer in my lap and the way it felt and the sound made me feel that it all broke. But everything was working fine. A bit scary though.

Switching to MacBook Pro part 2 - Starting the computer

This is part two in a series about switching from PC to MacBook. You can also read part 1.

Hitting the on button
The start up screen that is presented shows only a blank white screen with the apple on it. After waiting 30 seconds I am prompted to choose the language.

With some hesitation I choose Swedish as my main language. I am a user of many Google products and when using the original language of US English I always get the latest updates quicker. But I guess this doesn't apply to the world outside the web (or Google if you want).

The introduction video that follows welcomes me the the world of Mac and it hits me how clear the screen is.

The next screen wants med to choose my country. Sweden is preselected and automatically my finger drops down to the mouse pad to select continue when I notice there are no right-left mouse buttons. Luckily the bottom left corner works like the left button and so on. But some panic started to spread through my body.


After selecting my keyboard layout I am asked to transfer information from another Mac or TimeMachine copy (the backup program for Mac). Since this doesn't apply to me I jump this step.

Next screen wants me to connect to a wireless network. Since I am on vacation and don't have access to any network at the moment I skip this step to.

But the Mac won't let me. I have to set a network to connect to. I find the solution under "Other network settings" where I can set "no network".

I then have to fill in a form for registering the computer.

This is the first time I come in actual contact with the keyboard and it feels quite nice. Different from a PC, but still nice. The thing I found though was I use all keyboard combinations for a PC. Tab still works for moving around in a form, but there is no "Alt gr" for producing the @. After trying a few combinations "alt" works for this, but it's placed differently from on a PC. I'll probably come back to this later on though.

The next step is to choose a local account for logging in to the computer. This has always been a problem for me. Both me and my wife use the computers at home. Even my son uses the computers for playing games on. I started out using different accounts for everyone since my son wanted one setup of bookmarks in the browser and shortcuts on the desktop and my wife another. But logging in and out all the time when switching proved to be a bigger problem than finding the shortcuts, so I went to having only one account. Multiple accounts also prove to be a problem when using one program for handling photos and music. When adding new music I had to switch accounts to get the new music on to my wifes' account so she could sync with her iPod. No I'll try to go for one account this time (although my son will probably not be allowed to use this computer).

Next stop is to take a picture of yourself. A nice touch, but I came out looking like a geek of some sort.

After choosing timezone, time, date I'm all set to start using the computer.

Switching to MacBook Pro part 1 - First impressions

I have decided to spend some time blogging about my first impressions of my new MacBook Pro. I have never used a Mac before and the decision to pass over to the "dark side" was not easy I can hounestly say, but I finally came around. My friends at work use Mac and I have seen what they can do. So for my own sake and for all others interested I will write some blog posts about all my impressions. I will use the MacBook as a home entertainment center and my main computer at home. But also for doing some .NET development.

Hardware
13-inch MacBook Pro with aluminium casing
2.26 GHz Intel Core 2 Duo processor
500 GB hard disk
2 GB RAM (but I have ordered a 4 GB unit and it will arrive in a month)

External gear
Mini DisplayPort to VGA Adaper (for external screen or projector)
Mini DisplayPort to DVI Adaper (for external screen or TV)
Apple Remote (for watching movies)

My intentions
My first intention was to only install Windows on the Mac, but I quickly put this aside. I want to experience the Mac and in the process learn something new. This was quite hard for me since I am an absolute novice when it comes to a Mac. Only a month ago I sat down at a Mac at work trying to help a customer. I was looking for a file that my co-worker had saved somewhere. The conversation ended with med saying "I'll have to call you back". I just couldn't figure out how to find the file. So a novice. I am used to have absolute control over my computer and what I can do, so this feels like starting over again.

I will run Mac OS with all the good stuff it brings. But when I feel something doesn't work I will switch to Windows. I guess the first thing I'll be installing on Windows will be Visual Studio development environment.

I went with the smaller 13-inch because I'll probably be using an external screen at home, and I have regretted buying a 15-inch computer for quite some time now. It's just not as easy to bring with me.

The question is if I'll be running Windows on dual boot or a virtual copy. I must confess I'm not really sure which is better but a lot of developers seem to run a virtual Windows for these sort of thing. The drawback with dual boot is that I have to actually start my computer with either Windows or Mac OS. I'd rather run Mac OS and just start up Windows when needed. If I have understood this correctly I don't have to partition my hard drive into one Windows and one Mac part when running only virtual. But I'm not sure of this. Since I'm not sure I can't choose how much space the Windows part would get and so on, so I'd rather not choose at all.

First impressions
When first getting the box in my hand It felt like a religious moment. So clean. Almost as if I wasn't supposed to open it. The box seemed to say "don't break me and never, ever throw me away".


The same feeling after opening the lid. "Am I really supposed to remove the computer from the box?" Even the inside of the box is fitted with foam rubber. Why can't the PC world understand that the design and feeling is quite important. And you don't have to litter both box and computer with markings of all sorts. The mobile wold has learned the hard way that design is almost everything. When we get more and more connected and carry around our technical stuff, it's actually quite important how it looks. A couple of months ago I just couldn't care less how my computer looks. But now that I have this computer in my possession I feel like one of the cool guys.

Except for the computer I got the power cord, a book that says "Everything about Mac", some Cd's which I guess contain Mac OS and some applications and some kind of black cloth probably for wiping the screen with (although I'll probably lock this cloth in my safe since it's so clean and nice).

I'm a PC guy and when using a PC laptop there is no question which way is up, since the bottom of the computer seems to be a playground for how much stuff you can fit in one small area. I'm not saying I can't find the top of the Mac but it's ridiculously clean. Everything that doesn't fit the design has had to go. Weather this is a good or bad thing from a user perspective I'll have to see, but so far so good.

The computer was wrapped in some kind of plastic and before being able to remove this I had to break the seal. This contributes to the feeling that I'm not opening an ordinary technical gadget where the goal is to rip open everything as quickly as possible. This is a moment between me and my new computer. Cherish the moment.

Before switching on the computer I go against all my instincts and actually open the little booklet to read the instructions. It seems I owe this to my computer. Not to abuse it the first thing I do.

The first this that hits me is how they actually try to amplify the feeling of me and my computer as a team. On the first page: "Congratulations, you and your MacBook Pro are made for each other".

They are also very aware that they are winning a lot of PC owners over (including me) since everything seems to be addressed to a new Mac user, not a new computer user. So now I am using a Mac, not a computer. This is a Mac.

Getting the computer to run
The power cord comes with two connections. Either I connect the adapter straight to the socket or I can use the extended cord. My first impression is however that the shorter adapter will be completely useless since I have about 1,5 meters of cord, which is hardly enough for reaching up on and ordinary table.

The short power cord.

The long power cord.

When connecting the power to the computer I am used to the ordinary PC connector - you look for the hole and then insert the connector. On the Mac you use the MagSafe which is fitted with a magnet and easily connects with a click. This can come in handy for all the times you trip over the power cord (i have done it several times). On the Mac the connector will just plop out without the risk of dragging the computer to the ground.

Now I am ready to start the computer.


My new MacBook Pro compared to my 15-inch HP 6710b.

2009-04-19

Medicine for migraine can cause headache

This is just hilarious. I know this is a blog post that's a bit out of place for me, but I just had to get this in writing.

I sometimes get this splitting headaches, something like a migraine. Usually I take some ordinary mild medicine, and lie down for half an hour and that's it. But under some circumstances I have to keep on going and that's been a problem. Therefor I got this new medicine called Zomig Nasal. On the package it says "for treating headache/migraine" and it's some kind of spray to be inhaled in the nose. It's quite expensive but for those times I really need it this could be a great thing.

So today, after exercising my enormous skills as a carpenter (NOT!) I got this splitting headache. Unfortunately we were going to a party during the evening and I didn't want to stay at home. So I decided to take the medicine. I opened the box and just had to read the instructions before inhaling.

Imagine the surprise when I read about the side effects and it says that more than 1 out of 100 people will have a headache as a side effect. HA! Yea, you read it correctly. Headache!


Unfortunately the text in the picture of the side effects is in Swedish.

And the worst part of this is that apparently I was one of the people that experienced this side effect. Now I'm not completely sure of this. The medicine could have no effect at all and my ordinary headache continued, in which case the medicine was totally useless. But my sensation was that my headache actually increased after taking the medicine. 

Somehow I feel that it is strange for a medicine that is supposed to treat headache to actually have headache as a side effect, especially for such a large number of persons (1 out of 100). Maybe I should just feel unique and special to be amongst such a chosen group. Maybe I should think twice before inhaling something that could just as easily increase my headache, and the instructions clearly specify this.

Sometimes things like this just amazes me. 

2009-04-14

Bug in IE: duplicating characters

I've come across a bug in IE over the years and it's become one of those things I never write down, which means that I never remember how to solve the problem.Now it's time to write it down...

When using CSS float elements round text sometimes IE duplicates the last characters on a separate line beneath the end of the text. This is really confusing since the characters don't really exist if you check the HTML code. Another annoying thing about this problem is that the characters are not visible in Firefox, so you can't use Firebug for this. IE have some similar developer tools, but they are not even close to what you can do in Firebug.

Anyway the problem is not really connected to the CSS at all, even though you could solve it by changing your CSS style and not use floats. The problem lies in the use of many HTML comments. I found a great article by the CSS idiots describing the problem and the solution.
"Characters will get repeated when there are multiple HTML comments placed in between floated elements, also called as ghost text bug. First two comments have no effect, but each consecutive comment causes two duplicate characters. Three comments will duplicate three characters, four comments cause four repeating characters & six duplicate characters for five comments."
So the fix to the problem is really not to use too many comments in your code, alter your CSS not to use floats or make some kind of CSS fix as explained in the article.

I'm really getting fed up with these browser issues. I've worked with this stuff a long time now and checking the layout in five different browsers for bugs like this every time just doesn't feel like 2009, more something you would experience in the early 90's. I want a CSS standard that really works and can be used in all browsers. I can't wait to build real applications using Silverlight - I'll just have to speed up my own efforts in learning Silverlight before I use it in a live project.

2009-04-11

OOP: is-a is not inheritance

I've been off work for a couple of days during Easter and I've been catching up on my blog reading and at the same time listening to some podcasts I've missed. When listening to an episode of Hanselminutes some of my concepts of OOP where shaken. Scott Hanselman interviews "Uncle Bob" about SOLID Principles. I really enjoy Hanselmans podcasts and the length of them suits me perfect, since my walk to work in the morning takes about 30 minutes.

Anyway, apart from bringing up some great topics about programming principles in general, 22 minutes into the podcast they bring up inheritance and remembering my education in object oriented programming I've always learned that inheritance is a "is-a" relationship. When deciding if class A should derive from class B you can always ask yourself if "A is a B".
Example: I have two base classes called Vehicle and Person. Now I am to create a class called Car and another one called Employee. A Car is a Vehicle and therefor Car should derive from Vehicle. An Employee is not a Vehicle but is a Person and will derive from Person. Pretty simple.
But according to Uncle Bob it's just not that simple. He brings up the old example with the Rectangle and Square. A Square is a Rectangle and according to the above mentioned rule a Square should derive from the Rectangle. But a Rectangle has a height and a width, and the Square only needs one variable. So the Square will inherit the wrong set of variables. Not a big problem maby, we just work around the problem so when you set the height of a Square the width is set too. But then the creator of the base class Rectangle wants to build a function that depends on the height and not the width. He knows that when you set the height, the width is not affected in a Rectangle. So he builds his function. But then you get problems with the Square, since this sets both the height and with at the same time. A Square is a Rectangle sounds right, but something is wrong.

In geometry the two objects are related, but not in code. They have completely separate behavior and therefor are not related at all. So inheritance really has nothing to do with is-a relationships it's just "a declaration of methods and variables in a sub scope" according to Uncle Bob.

I'll have to think about all of this for a while but for the time being I'll have to watch myself when dealing with inheritance, especially if I try to follow the SOLID principles. But somewhere I can't help to wonder if I would have grasped the basics of object oriented programming without the is-a. In most cases it really works.

Go ahead and check out the podcast and send some comments my way on this subject.

2009-04-10

And now for some English

I'm switching to English on my blogg. It just feels more natural while blogging about mostly technical stuff.

My activity on this blogg has been close to nothing the last few months, but now my ambition is to be more frequent in my writing. I've been reading a lot of blog posts during the last week and I've been inspired by people who use the blog as a way to learn. By blogging about something they are in the process of learning they also get a lot of comments and thoughts on what they are doing. And also the blogg becomes an archive of things they have learned. Maby this is something for me. At least I'll give it a try.