DEV Community

Cover image for Code Smell 17 - Global Functions
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

Code Smell 17 - Global Functions

Discouraged by Object-Oriented Programmings, Many mixed languages support it. And developers abuse them.

TL;DR: Global function bring a lot of coupling. Don't use them.

Problems

  • Coupling

  • Readability

  • Maintainability

  • Testability

Solutions

  • Wrap the function in a context object.

Examples

  • External Resources Access, Database access, Time and Operating System resources.

Sample Code

Wrong

<?

class Employee {
    function taxesPayedUntilToday() {
        return database()->select(
            "SELECT TAXES FROM EMPLOYEE".
            " WHERE ID = " . $this->id() .
            " AND DATE < " . currentDate());
    }
}
Enter fullscreen mode Exit fullscreen mode

Right

<?

final class EmployeeTaxesCalculator {
    function taxesPayedUntilToday($context) {
        return $context->SelectTaxesForEmployeeUntil(
            $this->ssn,
            $context->currentDate());
    }
}
Enter fullscreen mode Exit fullscreen mode

Detection

Many modern languages avoid them. For the permissive ones, scope rules can be applied and automatically checked.

Tags

  • Global

Conclusion

Structured programming considers global functions harmful. Yet, we can observe some bad practices cross paradigm boundaries.

Relations

  • Singleton and Classes are global points of access.

More Info

Credits

Photo by Mae Mu on Unsplash


The road to programming hell is paved with global variables.

Steve McConnell


This article is part of the CodeSmell Series.

Last update: 2021/06/26

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay