Search code examples
javaextensible

Making a layer modular/extensible in Java


I'm new in the Java world and struggle a little bit with my application. I divided my application into several layers (UI, controller, ...). The bottom layer is responsible for gathering data from sensors.

My goal is to make this layer extensible, such that external users/programmers could easily add new sensors in it.

Do I only have to separate each sensor in a distinct class or is there any other solution for it?

My apologies if it's a 'weird' question, I'm just a newbie :)

Thanks!


Solution

  • Essentially what you are building is a framework. The sensor code would follow the Hollywood Principle: "don't call me, I'll call you"

    This is achieved by applying the Dependency Inversion Principle.

    You create an interface Sensor.java:

    public interface Sensor {
        Reading getReading();
    }
    

    And a Reading.java (making this general is an Open Closed Principle challenge related to how much generality you need from sensor data structures):

    public final class Reading {
    }
    

    And a a SensorReader.java:

    public final class SensorReader {
        private final Iterable<Sensor> sensors;
        public SensorReader(Iterable<Sensor> sensors) {
            this.sensors = sensors;
        }
        public void readSensors() {
            for (Sensor sensor : sensors) {
                Reading reading = sensor.getReading();
                // so stuff with reading
            }
        }
    }
    

    Everything above here is framework, everything past here is application/client code.

    And a MotorEncoder.java:

    final class MotorEncoder implements Sensor {
        @Override
        public Reading getReading() {
            // do stuff to actually read motor encoder
            return new Reading();
        }
    }
    

    And an Application.java:

    import java.util.Arrays;
    
    public final class Application {
        public static void main(String[] args) {
            Sensor sensor = new MotorEncoder();
            SensorReader sensorReader = new SensorReader(Arrays.asList(sensor));
            sensorReader.readSensors();
        }
    }