I often find I want to write code something like this in C#, but I am uncomfortable with the identifier names:
public class Car
{
private Engine engine;
public Engine Engine
{
get
{
return engine;
}
set
{
engine = value;
}
}
public Car(Engine engine)
{
this.engine = engine;
}
}
Here we have four different things called "engine":
Engine
the class. Engine seems like a good, natural name.Engine
the public property. Seems silly to call it MyEngine or TheCarsEngine.engine
the private field backing the property. Some naming schemes will recommendm_engine
or_engine
, but others say that all prefixes should be avoided.engine
the parameter name on the constructor. I've seen naming schemes that recommend prefixing an underscore on all parameters, e.g.,_engine
. I really dislike this, since the parameter is visible to callers via Intellisense.
The particular things I don't like about the code as written are that:
- If you change the parameter name in the constructor but miss a use of it in the constructor body, you get a subtle bug that the compiler probably won't be able to spot.
- Intellisense has a bad habit of autocompleting the wrong thing for you, and sometimes you won't notice it's changed the case. You will again get a subtle bug if the constructor body accidentally ends up
this.engine = Engine;
It seems that each name is appropriate in isolation, but together they are bad. Something has to yield, but what? I prefer to change the private field, since it's not visible to users, so I'll usually end up with m_engine
, which solves some problems, but introduces a prefix and doesn't stop Intellisense from changing engine
to Engine
.
How would you rename these four items? Why?
(Note: I realise the property in this example could be an automatic property. I just didn't want to make the example overcomplicated.)