DEV Community

Discussion on: What are the caveats of using global functions and/or classes with all-static methods?

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

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:

user.get_name()

get_user_name( user )

user_db.get_name( user )
Enter fullscreen mode Exit fullscreen mode

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:

random_int( 4, 10 )

random.next<int>( 4, 10 )
Enter fullscreen mode Exit fullscreen mode

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 instance r 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.