0

I had written a piece of code along the lines of:

public abstract class TestService extends Base {
   protected final MappedObject<A, B> mappedObject;
   public TestService(Provider provider, ObjectMapper objectMapper) {
      mappedObject = new MappedObject.Builder<A, B>(...);
      ...
   }
   ...
}

However, I have been instructed to prefix this to mappedObject, as it is convention when it comes to setting instance variables. Is this true?

I was under the impression that this as a prefix would only need to be used if there were a parameter with the same name that could cause ambiguity. Hence, a this would be necessary to reference the instance variable rather than the argument passed.

Orange Receptacle
  • 1,173
  • 3
  • 19
  • 40
  • 2
    Who instructed you? If it’s company standard then even though it’s not required to work you stick to their conventions. – d.j.brown Apr 03 '18 at 17:51

1 Answers1

0

As you seem to be aware, it's not necessary, as long as there is no ambiguity between local and member variables of a class.

However, there are a number of different schools on this, and whether it's "convention" or not varies depending on who you ask (different developers have different preferences, different companies have different conventions, etc.). I would say it's mostly common in school courses. In the real world you might see it in a constructor from time to time, but in my personal experience it's quite rare.

Something that I find is more of a convention, and somewhat ties into this question, is prefixing member variables with m, as in mMappedObject, to indicate that it is a member variable. This is very common - in fact, one could argue that it's probably more common than prefixing this.

Magnus
  • 17,157
  • 19
  • 104
  • 189