On returning consistent data types

This post is ins­pi­red on an is­sue I on­ce foun­d, whi­le I was using a we­ll-k­no­wn li­bra­ry in Py­thon fo­r ­par­sing YA­ML fi­le­s. The pro­blem was that when it was loading the con­tent of the fi­le, the re­sult wa­s ­not co­he­ren­t, be­cau­se so­me­ti­mes it re­tur­ned the con­tent as a py­thon dict, but if the fi­le was emp­ty, the ­re­turn va­lue was No­ne.

Do you no­ti­ce so­me­thing odd he­re?

What if I want to use the re­sul­t? I can­not do it safe­l­y, for exam­ple:

content = yaml.load(...)  # with the correct parameters and file name
for tag, values in content.items():
    pass  # process as required...

If con­tent is No­ne, it wi­ll rai­se an Attri­bu­teE­rror sa­ying that No­ne has no­ a­ttri­bu­te ca­lled “i­te­ms” (whi­ch is true).

The­re­fo­re, the de­ve­lo­per should ca­tch the ex­cep­tion or avoid the cor­ner ca­se, by doing so­me­thing like the fo­llo­win­g:

content = yaml.load() or {}

That could be a ca­se of “co­ding de­fen­si­ve­l­y”, making su­re that the pro­gram wi­ll not fail un­de­r ­most con­di­tions (it would al­so re­qui­re to add an as­sert or to rai­se an ex­cep­tio­n ­perhap­s, but that is a di­ffe­rent to­pi­c). I ac­tua­lly agree wi­th de­fen­si­ve pro­gra­m­min­g, ­but I thi­nk it is be­tter if the li­bra­ry itself has a mo­re co­rrect be­ha­viou­r, res­pec­tin­g ­the in­ter­fa­ce (that is: if you are going to re­turn a dic­tio­na­r­y, and the­re is not con­ten­t, ­then the lo­gi­cal as­sump­tion is to ex­pect an emp­ty dic­tio­na­r­y). ­This must be the de­fault be­ha­viou­r, not so­me­thing to be set by pa­ra­me­ter­s.

This could be thou­ght as an ins­tan­ce of a mo­re ge­ne­ral pro­blem that oc­curs when so­me func­tio­n is in­ten­ded to re­turn “X or Y”. In my opi­nio­n, if X and Y do not sha­re the sa­me in­ter­fa­ce, ­the­re is a po­ten­tial bug (in the Ob­jec­t-O­rien­ted pa­ra­digm we would say that the­re is no po­l­y­mor­phis­m, or ma­y­be that the “con­trac­t” is not being res­pec­te­d).

This is an exam­ple that I wanted to hi­gh­li­gh­t, be­cau­se it mi­ght help you to wri­te clea­ner co­de.