Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good programming practice to use import static fields? [duplicate]

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
like image 357
linisax Avatar asked Jun 28 '11 01:06

linisax


3 Answers

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.

like image 59
c00kiemon5ter Avatar answered Sep 20 '22 06:09

c00kiemon5ter


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

like image 31
TolkienWASP Avatar answered Sep 23 '22 06:09

TolkienWASP


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.

like image 36
Courtney Christensen Avatar answered Sep 23 '22 06:09

Courtney Christensen