Consider this code:
private static Context myContext;
public static Context getInstance() {
myContext = myContext == null ? new Context() : myContext;
return myContext;
}
After refactoring like this, my app started to throw NullPointers:
private static Context myContext;
public static Context getInstance() {
return myContext == null ? new Context() : myContext;
}
Is it returning myContext and ignoring all after '=='? Can somebody explain?
EDIT: Did a bit more research on this, turns out that it was my mistake: seems that refactored code failed to assign the value to a Context class field.
Sorry for inconvenience.
If someone is still interested, here is the working code snippet:
package pckg;
import org.junit.Test;
public class TernaryTest {
@Test
public void testOK(){
Context.getInstance().initialize();
Context.getInstance().setReport(new Report());
Context.getInstance().getReport();
}
@Test
public void testFail(){
Context.getInstanceRefactored().initialize();
Context.getInstanceRefactored().setReport(new Report());
Context.getInstanceRefactored().getReport();
}
}
class Context{
private static Context myContext;
private boolean isInitialized;
private Report report;
public static Context getInstance() {
myContext = myContext == null ? new Context() : myContext;
return myContext;
}
public static Context getInstanceRefactored() {
return myContext == null ? new Context() : myContext;
}
private void checkInitialized() {
if (!isInitialized) {
throw new IllegalStateException("Not initialized.");
}
}
public void initialize() {
if (isInitialized) {
throw new IllegalStateException("Not initialized.");
}
isInitialized = true;
}
public void setReport(Report report) {
this.report = report;
}
public Report getReport() {
checkInitialized();
return report;
}
}
class Report{}