I have a special case, as shown below. I have Listener class, and an Uploader class. Listener class listens to messages over the network, processes them and creates another small object from that.
public class Listener {
Uploader uploader;
Listener(String location) {
uploader = new Uploader(location);
}
public void listen(Message msg) {
ProcessedObject obj = process(msg);
uploader.add(obj);
}
public void terminate() {
if (null != uploader) {
uploader.finish();
}
}
}
The Uploader class takes one object via add method, and decides when to uploader. For this, it maintains a list. It also has location string, which is specific to one listener. Here's the gist:
/**
* This class is not thread safe, and an object should not be shared across threads
*
*/
public class Uploader {
String location;
List<ProcessedObject> objects;
Uploader(String location) {
this.location = location;
}
void add(ProcessedObject obj) {
objects.add(obj);
if (objects.size() > PARTITION_SIZE) {
uploadObjects(objects);
objects.clear();
}
}
void finish() {
uploadObjects(objects);
}
}
So, it uploads if the number of objects is greater than PARTITION_SIZE. There are multiple listeners in the application, each running on a separate thread. Each listener will have it's own uploader object. I have clearly mentioned that this class is not thread safe, in the javadoc.
Now my question is, is it a good practice?
Some of my colleagues say that this is not a good practice, and suggest to use a static method for uploading, and not create an instance of uploader. But my argument is, that will make my listener class messy (because then listener will have to maintain the counts, and check and upload again at the end before terminating for remaining objects)
With my approach, the whole partitioning and uploading logic is available in uploader class, so it improves readability as well as maintainability.
My question is, is my approach a bad practice (considering also that I specifically call out that uploader is not meant to be thread safe) ?
Also, is there any design pattern for what I am trying to do here? If yes, which one?
Aucun commentaire:
Enregistrer un commentaire