mardi 13 juillet 2021

How to implement "general variable" in Java?

Assume we have a program with many classes that provides multiple services, but it also needs to keep track of all the details in one big list (or some data structure), e.g. saving intermediate calculations done by various function calls in the program.

Every time the main method is running it should keep track of all the methods/functions by having all methods/function update it when they are called with some value/calculation and when (just before) the main method terminates it should be saved to a DB (the save details are not important here) and can be emptied.

I thought of two approaches to maintain the list:

  1. initialize the list in the beginning of the main function and make each and every method/function receive it as an argument.

  2. Define a class for the list (or data structure) having a static field holding the data structure and write code to update it in every method/function.

The second one seems better because it is more maintainable and maybe easier to implement but there seems to be some problems with multithreading and maybe other things I didn't think about.

Is there a best practice for this case or a design pattern that fits here?

Aucun commentaire:

Enregistrer un commentaire