DEV Community

loading...

Discussion on: 1 small tip to improve your code readability

Collapse
glsolaria profile image
G.L Solaria

Why call a method if it does nothing? Sure if you are protecting the boundaries of the application to an external interface you need to guard the boundary but even then you should collate consolidated error stats (accounting for potential security/dos events if relevant). If the code is not protecting the system from external systems wouldn't these conditions be better reflected in internal code as exceptions or assertions i.e. preconditions? Even in change detection algorithms I would comment the else branch to say "no change has been detected so do nothing". Commenting the else branches makes it clear you have considered all cases. If I find I am starting to nest too deeply, I use it as a trigger to refactor.

Collapse
winstonpuckett profile image
Winston Puckett

I think there are certain cases where this is really useful though. For instance, writing a publicly used library or public API. If a developer doesn't know the internals of your project, they shouldn't be expected to call it correctly the first time, right?

Collapse
glsolaria profile image
G.L Solaria

If the API code simply does nothing when a user of the API does not satisfy preconditions, how can the API user figure out they are not using it correctly? Wouldn't an exception be more appropriate?

Thread Thread
winstonpuckett profile image
Winston Puckett

Totally, but all too often I see things like,
If (acceptable)
{
// Lots of code
}
Else
{
Throw exception
}

Vs what the article talks about of

If (!acceptable)
Throw exception