SomeClass contains many methods, one of them, X ,fetches multiple pieces of data from a database using DbContext , X uses those pieces for processing, as well as calling another method, Y , multiple times.
Y needs access to the some of the data that was fetched by X.
Y is called many times inside X , specifically, 8 times.
Y is a small loop, it has only one job which is to populate a List , T is a generic type.
Conceptually, it is like this:
class SomeClass
{
private readonly ApplicationDbContext _context;
public SomeClass(ApplicationDbContext context)
{
_context = context;
}
public X()
{
var data1= //fetch data using _context
var data2= //fetch data using _context
var data3= //fetch data using _context
var data4= //fetch data using _context
///etc..
// X performs some processing using this data...
// X calls Y multiple times; Y needs access to some of the data.
Y();// needs some of the data
Y();// needs some of the data
Y();// neeeds so
}
public Y()
{
//simple for loop....
}
}
Given the above, which is considered a better design:
1- X sets the data as a private field so that Y can later access the data using the dot notation.
2- X passes the data to Y as a parameter .
3- Inline the implementation of Y within X, since Y is a relatively small loop that populates a List, and extracting it into a separate method would require passing several parameters and introducing generic type parameters, which complicates the interface of the Y method. but Inlining has the disadvantage that a similar code will be repeated multiple times, because it's not generic any more.
EDIT
There is a change that the data will be used by another method in the future, I can't say that for sure, but while I'm doing, I'm sure that at least X and Y need to access the same data, and of course, I do not want to query the database every time I need the data, to reduce the round-trip time, I want to query the database once.