Wednesday, May 23, 2012

I <3 LINQ


The Myth of the Method

I remember learning about classes in college.  I remember being taught about properties and methods, and how they are encapsulated into the objects of a class.  I even remember the classic example given below:

public class Dog
{
 public String name;
 public int age;
 
 public void Bark()
 {
  Console.WriteLine("Woof!");
 }
}

There is a bit of a misconception with this example. The use of Bark as a method for Dog is misleading. It explains a common myth among younger programmers (my former self included) that the method is an action that the object performs. In reality, the method is an action that is performed against a its object by an external entity. In the above example, the dog doesn't bark. Something else barks the dog. The object is literally the object of its method not the subject. Another way to think about it is that methods are entry points into the scope of an object. Without being invoked from without a class can do nothing. This is a very subtle distinction, but it is the cause for a create many bad architectures.

With this distinction in mind, it clarifies one of the most common purposes of classes; that is, to store, aggregate, and generally organize data.  The data is the state of the object.  It is what makes it unique.  Methods only support this state.   In fact, without state, instantiation is a wasteful.  Why would one create an instance for a class that doesn't maintain a state. This is what static methods are for.