DEV Community

Cover image for Code Smell 93 - Send me Anything
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

2 1

Code Smell 93 - Send me Anything

Magic functions that can receive a lot of different (and not polymorphic arguments)

TL;DR: Create a clear contract. Expect just one protocol.

Problems

  • Fail Fast principle violation

  • Error prune

  • Readability

  • If polluting

  • Nulls

  • Bad Cohesion

Solutions

  1. Take just one "kind" of input

  2. Arguments should adhere to a single protocol.

Sample Code

Wrong

<?

function parseArguments($arguments) {
    $arguments = $arguments ?: null;
    //Always the billion-dollar mistake
    if (is_empty($arguments)) {
        $this->arguments = http_build_query($_REQUEST);
        //Global coupling and side effects
    } elseif (is_array($arguments)) {
        $this->arguments = http_build_query($arguments);
    } elseif (!$arguments) { //null unmasked
        $this->arguments = null;
    } else {
        $this->arguments = (string)$arguments;
    }
}
Enter fullscreen mode Exit fullscreen mode

Right

<?

function parseArguments(array $arguments) {
    $this->arguments = $arguments;
    //much cleaner, isn't it ?
}
Enter fullscreen mode Exit fullscreen mode

Detection

We can detect this kind of methods when they do different things, asking for the argument kind

Tags

  • If Polluter

Conclusion

Magic castings and flexibility have a price. They put the rubbish under the rug and violate fail fast principle.

Relations

Credits

Photo by Hennie Stander on Unsplash


Referential transparency is a very desirable property: it implies that functions consistently yield the same results given the same input, irrespective of where and when they are invoked.

Edward Garson


This article is part of the CodeSmell Series.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay