Wednesday, November 11, 2009

A Quick Tip: Operations are not Methods.

In the industry of software development people always use the terms Operation and Method interchangeably. Often time this is true, other times it's not!
To begin let's define what the two terms exactly mean --in terms of Object Oriented Design?

[From Fowler's UML Distilled]

      An operation is something that is invoked on an object --the procedure declaration.
    A method is the body of the procedure.
I guess it's obvious how related and close the two terms are. But sometimes they can be quite different.
For example if you have A super class Employee that defines an abstract operation Work() and 3 sub classes of Employee (Manager, Programmer, and SalesRep) that override the inherited operation Work() then in this case you have 1 operation and 3 methods. 1 defined operation in the base class and 3 different implementations.

Monday, November 9, 2009

Opps! A Leak! In .NET!!

Are you a smart, happy, hard-working C guy?

If yes then, well ..  you probably want to skip this post.
Do you use .NET? Are you aware of the magician called GarbageCollector? Do you like it? Because I do!

Past -- Rewinding a little ... <<<
In the times before dawn, every-day programmers needed to do a lot of work to manage their application's memroy. My hero C guy -I used to be a hero too by the way- was forced to keep track of every malloc to free it when it's no longer needed.

Now -- Fastforwarding ... >>>
Everyone (Well, almost everyone) uses a lanaguage that supports automatic memory management tools. For me as a .NET guy, I use C# and I'm very happy with what the GarbageCollector does for me (I think most .NET guys are). However, unlike everyone (again almost) else thinks, it's trivially easy to introduce memory leaks in .NET.

First let's ask Wikipedia, What is Memory Leak?  Let me quote the answer here.

A memory leak or leakage in computer science is a particular type of memory consumption by a computer program where the program is unable to release memory it has acquired

I used to think that as long as I don't use unmanaged resources (explicitly) I'm safe. The GC will free all the managed objects from memory once I'm done using them (or when there is no references to these objects). Guess what? I was mistaken!!

One more point from this Wikipedia article:
Languages that provide automatic memory management, like Java, C#, VB.NET or LISP, are not immune to memory leaks. For example, a program could create a circular loop of object references which the memory manager is unable to recognize as unreachable.

GC frees only objects that has become unreachable. If the object is still reachable, somehow (probably your mistake), then GC will not free it. Which introduces a leak ...

To be honest, with nowadays super computers, usually leaks are not a problem unless your app is really big, and runs continously for a really long period of time; this is when those tiny drops can fill the cup.

What causes those leaks?
There are quite a few reasons why a .NET app migh leak memory. The main reasons are:
1- Static References
2- Event With Missing Unsubscribtion
3- Dispose method not invoked.

In this post, I will talk about the most famouse one (the one that got me bitten): Events.
Yes, people always remember to subscribe to events, but few unsubscribe from their events.

What happens when an observer subscribes to a publisher's event is that the publisher maintains a reference to the observer in order to call the event handler on that observer. This means that unsubscribtion from events is required to delete this reference. And that is what got me bitten hard!

So, how to detect memroy leaks?
There are plenty of tools that can help you track your application progress and take snapshots and analyze the memory status of your application. Here's a list of some of those tools:
  1. JetBrains dotTrace
  2.  .NET Memory Profiler
  3. ANTS Profiler
And many others ...

I will post about other types of memroy leaks in .Net in the coming posts. So stay tuned!

Tuesday, November 3, 2009

Bitten by the dynamic Keyword and Overload Resolution in C#

I came a cross a very scary piece of code Today on the web, take a look at the following C# 4.0 code:

using System;
using System.Dynamic;

namespace DynamicDemo
    class Program
        static void Main(string[] args)
            dynamic d = new ExpandoObject();
            d.Shoot = "Booom!";

        void DoSomeThing(dynamic d)

How would the previous code work?
Well, you would say that this code wouldn't compile because the static method "Main" is calling an instance method "DoSomething", right?
Wrong! This code will actually compile!! Yes, it will fail at runtime, but let's say why this piece of code behaved so freakingly scary. First let me show you another example:

using System;
using System.Dynamic;

namespace DynamicDemo
    class Program
        static void Main(string[] args)
            dynamic d = new ExpandoObject();
            d.Shoot = "Booom!";
Unlike the first example, this last example will not compile. All of this is related to how C# resolves method overloads.

If you examined section of the C# 3.0 specification, you will learn about the Overload Resolution mechanism that C# follows, here's the steps in short:

  1. Each overload is examined, and the best overload is selected according to the arguments. 
  2. C# determines whether the overload is accessible from the current instance or static context.
  3. If the overload selected from step 1 is not accessible then a compile-time error is thrown.
This overload resolution is done through compilation, but with dynamic, overload resolution is delayed until runtime, and it happens in the very same way as the above three steps (but at runtime of course).
So, at the first sample, the runtime has found the best overload to be the instance method "DoSomething" and then, determined that the selected target is not accessible for that call --as it's not accessible for static calls-- so the runtime threw a RuntimeBinderException exception.

For the second sample code, with no dynamic, the compiler finds out that "DoSomething" doesn't exist in the current context, so it will generate a compile-time error.

If you want to learn more about Overload Resolution, read the C# Specification.

Do you think this was scary enough, or am I being just too coward?

C# 4.0 Now Consumes Indexed Properties

If you dealt with COM Interop before, then you probably know what Indexed Properties mean. If you don’t, hang on with me and you will know in the coming few lines. Consuming Indexed Properties is a new feature to C# 4.0 Beta2. This is used to improve syntax like the following:
var excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
This syntax can now be improved to get rid of get_Range(“A1”) and use an indexer accessor instead, here’s how C# 4.0 Beta 2 can do for you to improve this:
var range = excel.Range[“A1”];
So now, every time you use COM Interop and have to call get_x() and set_x(), you can now replace this with the new indexer syntax. I have to tell you –Well, you might have guessed it- that this is just a syntatic sugar, the compiler will do emit calls to get_x() and set_x() ultimately.

I think this little syntax improvement is pretty neat, however, people shouldn’t ask the very expected question “Well, now we can consume indexed properties in c#, why can’t we create it? we wanna create indexed properties! Indexed properties is a legal right! blah blah .. “. If C# allowed us to create indexed properties then I think, this will add an ambiguity that isn’t worth anything here. I mean take a look at the following code and tell me what would it mean to you, if C# enables you to create indexed properties?
Does it mean that SomeProperty is a type that implements an indexer, or SomeProperty is a property that requires an indexer? See the ambiguity?

What’s your thoughts on this, dear reader?

Monday, November 2, 2009

Moved to Blogger

Yes, though this is my first post here, I’ve been into blogging before! I’ve been maintaining my old blog for a while now. I decided to go on and try Blogger. I’m not unsatisfied with Wordpress at all, actually, I quite like it. I just wanted to try Blogger. And since the best way to try something is, well, actually try it, I decided to move my latest blog posts to here.

Blogging for Cowards 101:

  1. What is a coward?
    A coward is an intelligent trained professional, armed with a powerful brain and likes to explore new things, wastes his time banging onto a modern typing machine, hates compilers, loves WoW, and ultimately is scared of the world ending without him learning enough

  2. What is Programming?
    We will figure it out together!

  3. How can this blog help you?
    Sharing is caring, you know? Yeah, I’m scared too. I will share any new stuff I learn about onto this blog, I will even share my own thoughts (don’t waste your time on those)

So, are you with me, are you a coward? I hope so. Life is not fun without learning, and 2012 is so close, we have a lot work to do! Time is running out, life is running out. So let’s get started, shall we? Ladies and Gents!?