I have 3 classes in my application:
1. Runner / Main (calls the service class)
2. Service class (carries out buisness logic)
3. Repository class (called by service to make DB queries)
I am unsure of the best way to implement the variables in the service class. Which is the best way of the 2 below and why?
E.g. should I have instance variables:
public class DogService{
List<Dogs> dogList= new ArrayList<Dog>(); //instance var
public DogService(){}
public List<dogs> getAllDogs(){
dogList=dogRepository.getAll();
return dogList;
}
}
or local variables in method:
public class DogService{
public DogService(){}
public List<dogs> getAllDogs(){
List<Dogs> dogList= new ArrayList<Dog>(); //local var to method
dogList=dogRepository.getAll();
return dogList;
}
}
Example of using the service class:
public class Runner {
List<Dogs> listOfAllDogs = new ArrayList<Dog>();
DogService dogService = new DogService();
public static void main(String[] args) {
listOfAllDogs = dogService.getAllDogs();
}
getAllDogs, the variable is overwritten anyways. Use a local variable until there's a reason against it.dogListin singleton pattern.