r/badcode • • Feb 02 '22

c# Oh hey, its more of my code.

Post image
902 Upvotes

95 comments sorted by

View all comments

Show parent comments

2

u/R3D3-1 Feb 05 '22

... still confused what you mean.

Maybe 2 is FILE_NOT_FOUND?

1

u/[deleted] Feb 05 '22

Anyway, that doesn't matter, since the code will never Input a value that is not 0 or 1

1

u/R3D3-1 Feb 05 '22

I'd disagree... If it never will receive anything other than 0 and 1, that would anyway be all the more reason to raise an Exception in that case.

Who knows, maybe later down the line the same function will be reused with a different data source, where "True" is only guaranteed to be non-zero, and the function gets reused by a collaborator.

I've seen the "ignore unexpected inputs silently" anti-pattern in our own production code. E.g. (made up example)

SELECT CASE (type)
CASE(TYPE_A, TYPE_C, TYPE_D)
    CALL handle_typeclass_1()
CASE(TYPE_B, TYPE_E)
    CALL handle_typeclass_2()
DEFAULT ! TYPE_F, TYPE_G
    CALL handle_typeclass_3()
END SELECT

Guess what will happen when TYPE_H is introduced and should be handled by handle_typeclass_2? Better would be to have

CASE(TYPE_F, TYPE_G)
    CALL handle_typeclass_3()
DEFAULT
    ERROR STOP "unexpected type"
END SELECT

The approach I've found in the code shifts detection of the missing case to detailed evaluation of the results during testing, with no indicator of the source of the issue; The "error message" variant makes it much more obvious, that something is wrong, and where.