I have producers that take data A, produce data B and send it
public interface Producer<T>{
void produce(T data);
void flush();
}
public class DataBaseProducer implements Producer<String>{
List<String> producedData = new ArrayList<>();
// create data
public void produce(String data){
producedData.add(transformData(data));
}
// send created data
public void flush(){
sendDataToDatabase(producedData);
}
}
public class MessageProducer implements Producer<String>{
public void produce(String data){
String line =transformData(data)
sendDataToMessageQueue(line);
}
public void flush(){
}
}
public static void main(String[] args) {
// get producer
Producer producer = getProducer(producerName)
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file..));
String line = reader.readLine();
while (line != null) {
producer.produce(line)
line = reader.readLine();
}
reader.close();
producer.flush()
} catch (IOException e) {
e.printStackTrace();
}
}
To demonstrate my question, imagine I have producers like above. One loads all data, and then bulk send it at once after it done, and second sends data right away (so it does not bulk send data, but whenever new data is created, it sends it right away)
Most of the producers will send the data after every data is loaded, but some of them will send them right away. If the producer sends data right away, than the flush()
method remains empty. This however seems like bad practice and may violates some OOP principles. What is the correct way to implement this?