i have a method that checks is the object properties fulfill some requirements, it returns true if yes, false otherwise. But the function is returning always false even if the parameters are correct. Here is the original code and a workaround i made and that did the job, but i still don't know the origin of the problem, so i posted it here to see if someone can understand the problem.
The Class contains an ArrayList of Class SacVariable, which also has a method isValid(). If all SacVariable objects in the arrayList are valid then the big guy is valid too. During testing the SacVariable.isValid() works perfectly returning true or false according to the case. But the if inside the for loop always read false...
public boolean isValid()
{
if (!this.getList().isEmpty())
{
for (SacVariable var : this.getList())
{
if (!var.isValid())
{
return false;
}
}
return true;
}
return false;
}
I think the logic is clear but i will explain it for clarity's sake.
If the arrayList is empty (size==0) i do nothing and return false straight away.
if there is something in the arrayList, i check each one to see if they are valid, if at least 1 is false then i immediately return false. if the for loops ends then i return true because it means all objects SacVariable are valid.
public boolean isValid()
{
int validConditions = 0;
if (this.getList().isEmpty())
{
return false;
}
for (SacVariable var : this.getList())
{
if (var.isValid())
{
validConditions++;
}
}
if (validConditions == this.getList().size())
{
return true;
}
return false;
}
The work around is the same, i initially separated the conditions to improve legibility in hope of finding the problem, that failed so i decided to add a counter, if validConditions==this.getList().size() then i know all SacVariables are valid. It worked... why it didn't the other way? it may be something incredible small or trivial but for the life of me i can't see it.
SacVariable.isValid() does not return always false. That i checked. The mystery here is that despite the fact that the method is indeed returning true the loop is broken.
I was not asking for people to give me alternative code, I only wanted to show this method to everyone here to see if someone spotted a problem with the code.