Question

Vendors commonly give me sprawling, oversized proxy classes to pass information. Often times to get to the actual content of the message I have to descend into a property like this:

var priceOfEggs = BeingItself.PossibleUniverses.Universe[0].Galaxies.Galaxy[0].Systems.System[0].[...].LocalEconomy[0].PriceOfEggs;

And it turns out that all of these classes inside this spawn of WCF only have one object that holds anything (it creates the illusion that things are well organized, you see).

The problem is any one of these classes could contain a null, and I get an exception.

Defensive coding here is prohibitive. Null checks can lead to deeply nested code. Arrays are twice as bad because I have to check for null and then check to see count > 0. Sometimes I have to foreach through the array.

I can try/catch, but then it's hard to know where it hit the fan in production because it's not in my debugger.

Is there a way I can surface via Trace which class is null?

Is there a way to de-reference to the leaf node of this monstrosity safely without creating a jungle of software verbage?

EDIT: Thanks for whoever put the link above! It is basically the question I couldn't find by googling.

No correct solution

OTHER TIPS

DataContracts are generated as partial classes without constructors. You can create a new partial class for each of the data contracts, and in its constructor initialize the properties to new objects or collections:

public partial class BeingItself
{
    public BeingItself()
    {
        this.PossibleUniverses = new List<Universe>();
    }
}

Still then you can't blindly 'dot into' the collection, as it's empty and PossibleUniverses[0] won't exist. There you'll still have to perform checks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top