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’:
Enginethe class. Engine seems like a good, natural name.Enginethe public property. Seems silly to call it MyEngine or TheCarsEngine.enginethe private field backing the property. Some naming schemes will recommendm_engineor_engine, but others say that all prefixes should be avoided.enginethe 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.)
See also: Am I immoral for using a variable name that differs from its type only by case?
In this case, I would name them exactly as they are in the example.
This is because the naming is clear as to what data each element holds and/or will be used for.
The only thing I would change for C#3 is to use an auto-property which would remove the local variable.