So one benefit of working with people much smarter than me is gaining new insightful perspectives.
One topic discussed today is using this and base when calling methods / members from a derived class. I argued that I found it helpful to prefix a call with base when the method I was calling was on the base class. That when I read the class later in life, it is clear to me not to look for that method on this implementation and to go look at the inheritance chain. As an example:
{
public string Honk()
{
return "honk honk";
}
}
public class Truck : Vehicle
{
public void Turn()
{
base.Honk();
}
}
So here my truck is leveraging Honk from the base class in some other method. One brilliant co-worker went into how this is bad from a readability perspective because of how the mind processes things visually. In other words – what follows is very hard to read…
{
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
base.Honk();
}
Note the calling the same method over and over is not the point but that having the repeated base. prefix is just distracting. A more concrete way to look at it: if you are able to parse say 6 characters of each row as you scan through the code, the first 5 are taken up with base. leaving you with less room for the part that really matters.
While I think this holds a lot of weight in an argument to avoid prefixing with this, I still stand by my comment that the base. is helpful and is used sparingly (generally) to not really be a visual distraction.
But – in comes another brilliant co-worker with a totally different perspective. “What happens ,” he says, “when you override that implementation in your derived class...” Now that would kind of suck. A change (overriding honk) with have side effects on everything in the derived class that was calling it (like Turn).
So in conclusion, I stand by my argument, that I think prefixing with base adds readability, I now respect that it must be used sparingly for visual reasons, and the added value isn’t worth the cost if you might end up implementing that method in your derived class later. I love working with people smarter than me!
No comments:
Post a Comment