Search code examples
javastringconventions

Best practice: where should user prompt messages reside in Java classes - main or method class?


I'm creating a Java class with methods, setters, and getters. I have a createTrain method that prompts the user with a message like 'Create how many trains?' in the form of a string. Should this text message be defined in the main class or within the class where the createTrain method is executed for better code organization and best practices?

I wondering regarding best practices, head different views, a bit confused.


Solution

  • It is generally recommended to keep the responsibilities of each class well-defined and separate.

    Defining the text message within the class allows for better cohesion and encapsulation. By keeping the text message within the class, you keep related code and logic together, making it easier to read and understand.

    public class Train {
        // ...
    
        public void createTrain() {
            String createMessage = "Create how many trains?";
            // Prompt the user with createMessage
            // ...
        }
    
        // ...
    }