0

I need to create a class which will have the following structure:

public class MyClass {
    ArrayList<File> myList = new ArrayList<>();

    public void addFile(File f) {
        myList.add(f);
    }

    public void DoHeavyWork() {
       for (File f: myList) {
          /// ...
       }
    }
}

I was thinking on this as maybe a Facade or maybe some kind of container. Would that be correct?

  • This is definitely a collection / container. I wonder why don't you allow the caller to use an arbitrary collection and not pass it to DoHeavyWork(). – 9000 Jun 24 '16 at 18:26
  • Looks like a batcher. – Kasey Speakman Jun 24 '16 at 18:34
  • @9000 so maybe killing off the ArrayList entirely and just leaving the processing part to the class, right? That's an idea. It wouldn't be a collection anymore, then. – user2018675 Jun 24 '16 at 18:35
  • @KaseySpeakman that's interesting, didn't know about this one. It looks right to me. – user2018675 Jun 24 '16 at 18:37
  • @user2018675: Yes, that might be beneficial (or not, depending on other things your class does). – 9000 Jun 25 '16 at 2:39
3

It seems like a batcher. So you could name it like this.

public class HeavyWorkBatch {
    ArrayList<File> myList = new ArrayList<>();

    public void AddToBatch(File f) {
        myList.add(f);
    }

    public void DoHeavyWork() {
        for (File f: myList) {
            /// ...
        }
    }
}
// Note there is a conspicuous lack of cleanup...
// What happens when AddToBatch is called again after DoHeavyWork?
// Is the class reusable so that DoHeavyWork should clear the ArrayList?

However, having the collection internal is not necessary based on the sample given. And given the questions I posed above, you could simplify it to just this:

public static void DoHeavyWork(File f) {
    /// ...
}

And then build the list separately, and iterate separately from doing the work. That way, your file operation can be reasoned about and reused separately from the collection. Because building a batch is a separate concern from operating on a file.

myList.forEach((file) -> {
    HeavyWork.DoHeavyWork(file);
});

If you need to build a batch from a larger list, then you could do so in other ways.

  • This is exactly what I was looking for. Having the method static and managing the list separately will be easier indeed. Thank you. – user2018675 Jun 24 '16 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.