What is the rationale for using static final strings for SQL statement strings?

Many places seem to include using class constants for SQL strings as best practice.

So, instead of:

String sql = "select * from users";
PreparedStatement stmt = conn.prepareStatement(sql);

He prefers to do:

private static final String SQL_SELECT_USERS = "select * from users";

void someMethod() {
  ...
  PreparedStatement stmt = conn.prepareStatement(SQL_SELECT_USERS);
  ...
}

What are the benefits of the latter? It seems to me less readable.

Thanks.

+4
source share
5 answers

A finalvariable cannot be changed, by mistake or otherwise. Declaring a statement line finalavoids this error:

String s = "select * from users";

// many lines of code
s = "temp";
// do something with s
// many lines of code
PreparedStatement stmt = conn.prepareStatement(sql);

, s, s final, , - .

, . , (sql, s). , , , .

, , , . final -, . , , final, .

private, . "" , ; , .

EDIT: . , SQL, SQL, . "selct * from users" - ; Java SQL, .

, SQL, . , - , , , .

private final String SELECT_STAR_FROM = "select * from ";
private final String USERS_TABLE = "users";

// many lines of code
PreparedStatement stmt0 = conn.prepareStatement(SELECT_STAR_FROM + USERS_TABLE);

// this line would fail at run time
PreparedStatement stmt1 = conn.prepareStatement("selct * from users");

// this line fails at compile time and the compiler points you at it
PreparedStatement stmt0 = conn.prepareStatement(SELCT_STAR_FROM + USERS_TABLE);

JNI, . , JNI . C, Java, , .

#define JSIG_CONSTRUCTOR "<init>"

"<intt>" , C ; (JNI ). JSIG_CONSTRUCTOR , , .

+3

, .

PreparedStatement stmt = conn.prepareStatement("select * from users");

JDK,

    if (is == null) {
        throw new IllegalArgumentException("InputStream cannot be null");
    }
+5

. final; ( , ), , , .

(static final) . someMethod(), . " ", IDE Javadoc , , , .

+3

( ) , . SQL_SELECT_USERS "select * from users".

( ) (, BUFFER_SIZE 4096) ( ). (.. , ) Java final.

" ". , , , . , , , , ( ), () ( ), , , .

, , , . , , . .

, .

+2

"" , . ( , , .)

, , , SQL . , ( ). , . , , , ( , .)

, " ", , .

+1
source

All Articles