I have a code with the following sequence of lines:
Socket echoSocket = null;
... something ...
echoSocket = new Socket("taranis", 7);
I do not understand why we want to have a first line. Well I know that Java is unable to define a type of the variable from its value. It's why first we need to tell that echoSocket is variable which has Socket type (the first line) and than we tall that echoSocket has a certain value (an object of a class Socket).
But what I do not understand is why we need to assign a value two times? Why do we want to say that echoSo开发者_StackOverflow中文版cket is equal to null?
The general principle I use is this: declare a variable as late as possible.
There is one very useful case for not initializing a variable however:
String someString;
if (/* some condition */) {
someString = "foo";
} else {
someString = "bar";
}
Because someString
is unitialized on declaration if, say, the else
clause didn't set a value the Java compiler would complain about unitialized values. That wouldn't be the case if you did this:
String someString = null;
if (/* some condition */) {
someString = "foo";
} else {
// do nothing
}
It's a good sanity check. The above isn't a compile error but this is:
String someString;
if (/* some condition */) {
someString = "foo";
} else {
// do nothing
}
You do not need to assign a value to a local variable is it is not used. Code should generatlly not declare variables until necessary. There is a somewhat dull chapter in the JLS on definite assignment.
You problem seems to be with try-blocks. Resource handling should be written as:
acquire();
try {
use();
} finally {
release();
}
In this case:
final Socket echoSocket = new Socket("taranis", 7);
try {
... something ...
} finally {
echoSocket.close();
}
Catching of exception should go around the lot. Don't try to save on try blocks.
If you find yourself repeating a lot of boilerplate, try the Execute Around Idiom.
Why are you declaring the variable earlier than you have a useful value for it anyway? Occasionally this is necessary if it's going to be assigned in two different branches, but generally it's better to wait until you have a value, and declare and assign in one statement:
Socket echoSocket = new Socket("taranis", 7);
You don't need to give echoSocket
the value of null. (Where did you read that?)
You can go with either
Socket echoSocket;
... something ...
echoSocket = new Socket("taranis", 7);
or do it in one line
... something ...
Socket echoSocket = new Socket("taranis", 7);
Hope it helps..
Technical writers don't always write the best code.
Personally I only write initial values when the compiler tells me to.
精彩评论