According to Why is Global State so Evil?, I believe we should avoid global state, so suppose I have an App that count user clicks in all pages like it:
public class GlobalState{
public int clickCount=0;
}
public class Page1{
public void onButtonPressed(){
GlobalState.clickCount++;
}
}
public class App{
public static void main(String[] args){
Page1 pageOne=new PageOne();
pageOne.show();
}
}
I know it is bad, I should change the GlobalState as parameter:
public class Page1{
public IGlobalData globalData;
public Page1(IGlobalData globalData){
this.globalData=globalData;
}
public void onButtonPressed(){
globalData.setClickCount(globalData.getClickCount()+1);
}
}
public class App{
public static void main(String[] args){
IGlobalData globalData=new GlobalData();
Page1 pageOne=new PageOne(globalData);
pageOne.show();
}
}
Which requires us to add additional code (eg:parameters) to access the click count, reduce the chance of unrelated pages change click count accidently.
However, what I don't know is, why is it called "alternative of global state"? Because I think "clickCount" state still exists in the memory of computer at the life time of the app running, which global states still exists. And I think the global state is essential for a user requirement and cannot be removed, otherwise how can I record the user click during the app using? I think the consequence of avoid global state in this case is (say to the users): "Don't create an app that counts user clicks of all pages" !
So my question is, why is Dependency Injection called "alternative of global state"?I think Dependency Injection is just helping us to access global states in better way, but not "avoid global state" actually because the global state still exists. Access global states in better way doesn't mean no global states. Or am I missed something about Dependency Injection?