Search code examples
javaclassoopstatic-methodsobject-oriented-analysis

Avoiding static methods and variables in a Java Class file that handles config.properties


I am working on a simple Java Application and I've created a class called Config.java in order to handle the Application properties, thus, avoiding hard-coding.

The Config.java class is not a static class, and I am creating an instance of the Config.java class in another class called Serial.java.

The main method is located in another Class called App.java. So I have 3 Classes in total:

  • App.java
  • Serial.java (Instance of Config class is located here as a private variable)
  • Config.java

At this stage, all is fine and there are no flaws within the OOP Design. However, I need to create another class in which I have to call methods from the Config.java class. What would be the best approach in order to have just one instance of the Config.java class:

  1. Changing the methods of the Config.java class from public to static?
  2. Creating getters and setters for the Config instance which is located in the Serial.java class?

Are there any more options/techniques I can use in order to reach my goal.

Any help or suggestions are highly appreciated.


Solution

  • Sounds like a job for dependency injection


    It sounds like you're instantiating Config in Serial:

    class Serial {
        private Config config = new Config();
    }
    

    Instead of creating it in Serial, pass it in:

    Config config = new Config();
    Serial serial = new Serial(config);
    

    The Serial class would look like:

    class Serial {
        private Config config;
    
        public Serial(Config config) {
            this.config = config;
        }
    }
    

    That way you can also pass it to the other object that must call methods from Config:

    OtherObj other = new OtherObj(config);
    

    With OtherObj defined as:

    class OtherObj {
        private Config config;
    
        public OtherObj(Config config) {
            this.config = config;
        }
    }
    

    This well help you avoid static.