Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: should I use "this" keyword or "m_" prefix? [closed]

To refer to instance variables, should I use the "this" keyword...

class Foo
{
    private int bar;

    public Foo(int bar)
    {
    this.bar = bar;
    }
}

OR the "m_" prefix (Hungarian naming convention where m means "member variable")...

class Foo
{
    private int m_bar;

    public Foo(int bar)
    {
    m_bar = bar;
    }
}

Are there any situations where one provides an advantage over the other?

like image 644
Niko Bellic Avatar asked Jul 21 '14 23:07

Niko Bellic


People also ask

Should I always use this Java?

In answer to "Are there any cases where you should always use this ?" You should use it when it is needed to avoid ambiguity, for example if there is another variable with the same name in scope.

Why do variables start with M?

'm' means the variable is a member variable of the class... Save this answer.

Can we use underscore in method name in Java?

Method names should always begin with a lower case character, and should not contain underscores.

Can Java variables have underscore?

A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".


1 Answers

this is standard, more readable, and less error prone.

It will help you when you are mistakenly shadowing variables or and trying to access non-static field in static code.

i.e to avoid this

int m_bar;
public Foo(int m_bar)
{
  m_bar = m_bar;
}

and static int m_bar;

int m_bar;
public Foo(int bar)
{
  this.bar = m_bar; // a warning static field being accessed as non-static
}
like image 113
jmj Avatar answered Nov 03 '22 08:11

jmj