I have implemented algorithm BFS(Breadth First Search) using a neighbors list ADT for scanning a graph and gathering information about it and answer questions.
I have function called BFS which implements the algorithm and i can answer questions(like: How many connected components the graph has ? Diameter of the graph ? and few more) by using the variables in the function.
For example, to find out how many connected components there are, i can print a variable int components (in the end of the function). To find out the diameter of the graph i'm using a int [] distances array and scanning it(in the end of the function) and getting the max value(precisely but not accurate), and so on.
My question is how can select/get the data from the function(and then i can wrap it within different functions)but still avoiding duplicate code ? is there a design pattern or different strategy for this type of problem ? solutions came in my mind:
- Print all the required data in the end - possible but ugly and none modular.
- Re-implement the function and every time return a different type of data(int, int[] etc) - code duplication.
- Return an object of all data, and then every different function will use it - overkill.
I can add some code if needed.