According to Why is Global State so Evil?, as I understand, global state is bad and I should use dependency injection instead. That means, for example, a mobile app that use bundles of app level data as follow:
public class UserData{
private static UserData userData=new UserData();
public UserData getInstance(){
return userData;
}
private String sessionId;
private String surname;
... (other fields with setter and getter)
}
public class SomePage{
private UserData userData;
public MainPage(){
this.userData=UserData.getInstance();
}
public void onLogoutButtonPressed(){
Http.post(Constant.LOGOUT_URL,"?sessionId="+userData.sessionId);
}
}
is an bad example and need to be fixed to use dependency injection.
However, as far as I know and according to https://softwareengineering.stackexchange.com/a/319609, the "spirit" of dependency injection is , an object receives target objects externally instead of that object creates target objects by itself, eg:
non dependency injection version:
public class SomePage{
public UserData userData;
public SomePage(){
this.userData=new UserData();
}
}
dependency injection version:
public class SomePage{
public UserData userData;
public SomePage(UserData userData){
this.userData=userData;
}
}
Then, I think my "global state" version:
public class SomePage{
private UserData userData;
public MainPage(){
this.userData=UserData.getInstance();
}
}
also doesn't create UserData at all. And I think the "spirt" of using global state and injecting object from constructor is quite similar : getting required objects externally, just their ways to get that external objects are different. So my question is, why is using global state doesn't consider as dependency injection even if it gets object externally?