I am just wondering if there is a better solution to the following problem. I want to validate all items in a list first, and then store them with additional values in a database. The problem here is that I iterate through the same list twice. The data should only be saved if all entries are correct. Now I wonder if there is a way to save the second iteration or a similar possibility.
Here is some rough source code:
public void saveItem(List list){
checkList(list);
for (ListItem item :List list) {
Optional <Item> aItem = aRepository.findByName(item.getName);
saveFunctions(aItem);
}
and
public void checkList(List list){
for (ListItem item: List list) {
if (!checkValue){
throw new Exception("Value is Wrong");
}}}
public void saveFunctions(ListItem item){
devicFunctionRepo.save((item.getInventoryNumber(), item.vpnip()));
devicFunctionRepo.save((item.getInventoryNumber(), item.wanip()));
//more values are here
}
Also, I'm wondering if maybe you should return a boolean with something like checkList so you have the exceptions in the main method. Similar to what I would do with the (!checkValue). What would be a clean way to implement this?
CodePudding user response:
Note: I agree with the comments that suggest this might be a premature optimization. But in the interest of actually answering the question and not assuming the asker hasn't already considered that, here is my answer.
Since you happen to show that you're doing repository saves, my first thought would be to wrap the entire iterate/validate/execute process in a transaction. Do the writes as you iterate, but if any validation fails, just roll back the transaction (or thrown an exception, which usually implies an automatic rollback).
If you had asked the question in a more general context (without revealing that you are dealing with repository writes, or in some repo context where there are no transactions), I'd suggest transforming the items in the List
into lambdas or Functions
/Consumers
(depending on your input/result needs) (or, if you want to get fancy, Future
instances), which only get invoked after the entire list has been validated. Again, a validation failure of any item causes all the lambdas/Functions/Consumers/Futures/whatever to be discarded and never executed.