I encountered this problem several times, so I m asking here what is the best practice
I have process that goes true several objects, modifies them and rises some flags.
boolean erros = false;
for(MyData data: allData){
//...
//@ToDo move this to a function titleCheck()
if(data.getTitle().isEmpty()){
data.setTitle('none');
erros = true;
}
if(data.getTitle().equals('BIG')){
data.setTitle('small')
}
if(data.getTitle().equals('error')){
errors = true;
}
//...
}
I need a function to update the data and change one or more flags so the preferred syntax is something like this:
MyData updatedData = titleCheck(MyData data, &erros){...}
but booleans cant be passed by reference so they was it works is:
boolean errors = titleCheck(MyData dataForUpdate){...}
Witch is way less intuitive .. (at least for me ... coming from PHP background) The problem gets bigger if you have several flags to update.
So .. what is the proper Java way to handle such structure.
When you do this:
titleCheck(MyData data);
given your code above, you're actually changing the data object - not a copy of this. Hence you can return the success/failure boolean and you don't have to return the passed object. So now you can OR these values together.
boolean error = false;
error |= titleCheck(...);
error |= nameCheck(...);
etc.
If you want to pass the object and a status back, you can trivially declare a return class thus:
class ReturnResult {
public boolean error;
public MyData data;
}
(I've made the fields public since I'm using it as a simple structure). The advantage of this approach is that you're making use of OO to tie together related objects, and you can put methods on the above class to make it easy to merge successive results.
Finally I note that you're calling lots of methods on the MyData
object and determining success/failure outside that object. I would rather put this within the MyData
object. Then the MyData object can store its own valid/invalid state and you can ask it for its own state via an isValid()
method or similar. This seems like a very OO method of doing things here.