I declare some constant variables in my SQLiteOpenHelper
class:
public static final String USERNAME = "user_name";
public static final String PASSWORD = "password";
In an Activity
where I create SQL queries, I import these fields:
import com.mygame.ui.login.LoginInfoSQLiteOpenHelper.*;
Is this a good practice?
Or the traditional way of referring to constants better?
LoginInfoSQLiteOpen.USERNAME
If you look at someone's code and see a field like
foo.do(baz, USERNAME);
wut(!), where did that var come from ?
search, grep, where is it declared ?
Using it as ClassName.FIELD
makes things much clearer and cleaner.
You avoid confusion, and sometimes it makes more sense to have a proper classname that denotes the field, than a field that came out of nowhere.
well, not everyone uses an IDE, and not everyone reads code through an IDE(maybe through a repository on the web), and even some consider VIM an IDE, and I do use vim a lot(although I don't think of it as an IDE).
So, it's not about what an IDE can or can't do, but more of what code reading is about. Code reading, code quality, expressing ideas in your programming language of choice, in a way through abstractions that make sense and tie well together.
A few years late to the party... but I feel it is worth providing the opposite point of view. There is a reason why Java was designed to have static field imports, and the reason is to hide how the class is implemented to users of the class. This is an important design principle for outwardly facing code. I would agree with c00kiemon5ter take on it, however, there might be situations in which it is worthwhile.
More info on static field importing can be found here: https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
I recommend the second method, only importing classes not fields. So prefixing your constants with the owning class, like LoginInfoSQLiteOpen.USERNAME
. It can become highly redundant, but it is much more readable and maintainable in the long run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With