Sunday, February 1, 2015

Code Better - One Simple Rule For Writing Better Methods

Here's one simple rule for writing better methods. More of a guideline or incantation if you will. Describe what the method does in ubiquitous language. If you use the word AND the method needs to be refactored.


It's not so wrong that a method is the entry point to doing multiple things though. The difference is that a method that is this entry point should "coordinate the actions and activities involved in doing x and y and z.
For example, a method that is the entry point for initializing and saving some entity could have a signature Person InitializeAndSavePerson(). The method should therefore call two methods as is implied by the name, perhaps a constructor also.


public static Person InitializeAndSavePerson()
{
var person = new Person();
person.Initialize();
person.Save();
return person;
}


All of the work to initialize is done in the initialize method and all the work for saving is done in Save().


Perhaps you prefer procedural style to DDD for this sort of thing, here's an example for that.


class PersonManager
{


public Person InitializeAndSavePerson()
{
var person = this.personFactory.GetPerson();
person = this.personInitializer.Initialize(person);
return this.personDataWriter.SavePerson(person);
}


}


Notice that the Initialize returns person. It's probably not technically necessary to do so since person is likely a ref type, but stylistically it better shows intent. This leads to greater readability.


Whatever style you use, the bottom line is that a method does one thing - coordinate or do work.

No comments:

Post a Comment