1

I'm studying a tutorial and got in doubt about the use of "this" keyword. In the constructor of the class, isn't this.mContext a redundant use of the referred keyword? Wouldn't be the same to use simply mContext?

//package org.harrix.sqliteexample;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;

public class DatabaseHelper extends SQLiteOpenHelper {
  private static String DB_NAME = "info.db";
  private static String DB_PATH = "";
  private static final int DB_VERSION = 1;

  private SQLiteDatabase mDataBase;
  private final Context mContext;
  private boolean mNeedUpdate = false;

  public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    if (android.os.Build.VERSION.SDK_INT >= 17)
      DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    else
      DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";

    this.mContext = context;
    copyDataBase();
    this.getReadableDatabase();
  }

}

  • 2
    yes, it's redundant – Ruzihm Oct 18 '19 at 21:13
  • 2
    The only time using `this` to access a class member isn't strictly redundant is when you're avoiding a local scope member with the same name, though good programming practices should prevent that situation from ever taking place anyway. – Abion47 Oct 18 '19 at 21:16
  • 2
    Abion47, it's quite common situation in a setter function. – Dorian Gray Oct 18 '19 at 21:58

2 Answers2

3

Yes it is redundant But if we follow the proper Java naming convention it is needed

 private final Context mContext;

normally should be

private final Context context;
public DatabaseHelper(Context context) {
    this.context = context
}

Here it is needed so that instance variable gets assigned with parameter value.

zain
  • 284
  • 2
  • 10
0

"The only time using this to access a class member isn't strictly redundant is when you're avoiding a local scope member with the same name, though good programming practices should prevent that situation from ever taking place anyway."

@Abion47