I do not know VB so will try to explain using C# if it helps.
Three levels of if/else if fine but more than that is a no. This is something you could do to get rid nested of ifs.
Assume following class structure:
class ParentClass
{
public ChildClass ChildProperty { get; set; }
}
class ChildClass
{
public int SomeProperty { get; set; }
}
Say, you need to do this kind of processing:
ParentClass parentObj1 = new ParentClass();
ParentClass parentObj2 = new ParentClass();
ParentClass parentObj3 = new ParentClass();
if (parentObj1 != null && parentObj2.ChildProperty != null && parentObj2.ChildProperty.SomeProperty != null)
{
ParentClass parentObj4 = new ParentClass();
if (parentObj4 != null)
{
if (parentObj3 != null && parentObj4.ChildProperty != null)
{
if (parentObj4.ChildProperty.SomeProperty != null)
{
}
else
{
}
}
else if (parentObj3 != null && parentObj3.ChildProperty != null && parentObj4.ChildProperty.SomeProperty != null)
{
}
else
{
}
}
}
This can be re-written as following:
if (parentObj1 != null && parentObj2.ChildProperty != null && parentObj2.ChildProperty.SomeProperty != null)
{
ParentClass ob3 = new ParentClass();
switch (ValidateObjects(parentObj3, ob3))
{
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
}
ValidateObjects method could look like this:
private static int ValidateObjects(ParentClass ob4, ParentClass ob3)
{
int result =0;
if (ob3 != null && ob4 != null && ob4.ChildProperty != null && ob3.ChildProperty.SomeProperty != null)
{
result = 0;
}
else if (ob3 != null && ob4 != null && ob3.ChildProperty != null && ob3.ChildProperty.SomeProperty != null)
{
result = 1;
}
else if (ob3 != null && ob4 != null && ob3.ChildProperty != null)
{
result = 2;
}
else if (ob3 != null)
{
result = 3;
}
return result;
}
You can opt for switch case in the method above too.
Still, you have a better understanding of the application so can think of better solutions. :)