The Daily Parker

Politics, Weather, Photography, and the Dog

M is for Method

Blogging A to ZAlphabetical order doesn't actually put topics in the best sequence for learning, so we've had to wait until Day 13 of the Blogging A-to-Z challenge to talk about one of the most basic parts of an object-oriented program: methods.

A method takes a message from an object and does something with it. It's the behavior part of the behavior-plus-data pairing that orients your objects in the OO universe.

In .NET, even though you define fields, events, properties, and methods on your classes, under the hood the CLR sees only fields and methods. Properties and events are basically special flavors of methods that C# syntax makes easier to understand for humans. (See Monday's post.)

Take this simple C# snippet:

public string Name { get; internal set; }

The compiled code for that property will look almost the same as the compiled code for this pair of methods with a backing field:

public string get_Name()
{
	return _name;
}

internal void set_Name(string value)
{
	_name = value;
}

private string _name;

In fact, the method pair should look very familiar to Java developers, since that language hasn't really kept up with the times, you know? (Java developers would call the simplified version "syntactic sugar," which is what people call things that make life simpler when their salaries depend on it being complicated. It's essentially every argument a Rails developer has with her .NET counterpart until the first time she needs to decouple the database from the front end. That's when the .NET guy shows her a coding horror from the VB3 era with a mournful warning not to let this happen to her. But I digress.)

To sum up: Methods change the data or behavior of an object, but C# prefers that you use properties to change data, events to express behaviors to external consumers, and methods to ask the object to do something.

The A-to-Z challenge is off tomorrow, but it will return next week with a basic tool of organizing your software, a basic tool of performance testing, a basic principle of OO design, and three other posts I haven't thought about yet.

Add comment

Loading