Within the last one year of my three-year journey into web development (on the LAMP stack), I've seen a lot of articles, blog posts etc., where programmers all but liken using global functions and static methods to deploying a nuclear warhead aimed at the server(s) where your application is hosted, but (most of them) without really explaining why that may be the case.
I don't have a CS background (yet), and I just saw another such post some 20 minutes ago so I was wondering whether we could shed some light on this topic here on dev.
Top comments (3)
The choice to use global functions, namespace functions, or static class functions, is forced by the language. I actually see no large fundamental difference between them and it comes down to naming conventions.
Consider the following function calls on an object:
Given a proper naming convention they are all clear to read. Most programs will end up having a mixture of these approaches. This is due to limitations in the OOP paradigm, like being unable to extend 3rd party classes, or a quirk of the language (can't have globals, but can have static member functions). Obviosuly you'd want to be as consistent as possible within a project.
Functions that don't have a context (don't take a type instance), are usually clearer as static functions:
Many languages require you instance something, like
var r = new random()
, and that often bugs me. Forcing instantiation is also a problem since it implies something more than you want. Does this random instancer
have meaning? Do I need to share it, or have hundreds of them. Static functions resolve this problem.NOTE: This is all about global and/or static functions. Global variables are a whole other beast entirely, and Ben Halpern's post applies.
I feel like this article explains it well:
This more applies to global variables though, not global functions, does it not?