I am building a multiplayer game using Java for server. Currently, I am using a single class file to store player data and process the data. I am a beginner, so I had no idea that this is a bad practice. http://howtodoinjava.com/best-practices/5-class-design-principles-solid-in-java/ This article helped me to understand I am breaking the rule of 'Single Responsibility principle'.
This is how my code looks now.
public class PlayerSession{
String playerId;
String playerName;
// 20+ player data fields, which I am trying to reduce
// and keep only the most used data
public void messageProcessor(JSONObject clientRequest) throws JSONException{
switch(clientRequest.getString("task")){
case "login": loginProcess(); break;
case "logout": logoutProcess(); break;
//50+ different actions
}
}
public void populateSessionData(String playerId){
// populate player data from database
}
private void loginProcess(){
//Process login
}
private void logoutProcess(){
//Process logout
}
//20+ other methods which do entirely different tasks.
}
As we add more features, the class will become extremely difficult to maintain and modify. Now I am trying to decouple this class into two different class. One, just to store Player data and an another one to handle behavior as shown below.
public class PlayerSession {
final TaskHandler taskHandler = new TaskHandler();
public void messageProcessor(JSONObject clientRequest) throws JSONException {
switch (clientRequest.getString("task")) {
case "login":
taskHandler.loginProcess();
break;
case "logout":
taskHandler.logoutProcess();
break;
// 50+ different actions
}
}
}
public class PlayerData {
String playerId;
String playerName;
// 20+ player data fields, which I am trying to reduce
// and keep only the most used data
public void populateSessionData(String playerId) {
// populate player data from database
}
}
public class TaskHandler {
final PlayerData player = new PlayerData();
private void loginProcess() {
// Process login
}
private void logoutProcess() {
// Process logout
}
// 20+ other methods which do entirely different tasks.
}
And this design results in 2 additional object creation for a single client i.e, PlayerData and TaskHandler. For a server of 10,000 concurrent client, will this become an issue? Is this the right way to do it? If not, what is the best approach for a scenario like this?
Somewhere I read that objects just to save data is not a good approach. Is that right?