DEV Community

Discussion on: Sometimes, the elegant implementation is just a function

Collapse
 
kungtotte profile image
Thomas Landin

One of my favourite videos on YouTube is the talk Stop Writing Classes by Jack Diederich. He shows a clear example where they go from a full library down to a single function that still does everything the library did.

I am very much a fan of the building upwards method of constructing programs where you start with just the code that you then lift into procedures and then into classes or modules if the need arises. Sometimes the best solution is a class, but it's really hard to know that from the outset and if you start out by writing the classes you think you'll need you will end up with classes like the first one Jack shows in that video (Greeter) that are what he calls obfuscated function calls.

This is why I think multi-paradigm programming languages are the bees-knees and any language that strictly forces a certain paradigm on you are not that fun to use. This goes both for OOP languages like C# or Java and functional languages like Haskell. Their strictness lead to hairy corner-cases where you can't write the best possible code because the language forbids it. Sometimes a global function (Python's len() comes to mind) is the ultimate solution, but if your language can't do it you do something like a Singleton which really is just a hidden global variable in most cases.

Tell someone you're using global variables and they'll jump down your throat telling you you're a shitty coder. Tell them you're using Singletons and they'll applaud you for being a diligent practitioner of the Patterns as proscribed by the holy Gang of Four...

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

I agree that multi-paradigm languages are definitely the preferred approach. I think it's essential that people can write in all paradigms and learn to use the right one.

To followup from your other comment here as well, I think it's helpful when a language gives multiple ways to define operations on data. Either as standalone functions, or as member functions of a type, preferably allowing both. Some functions just work better as globals, some work better as member functions.

Collapse
 
kungtotte profile image
Thomas Landin • Edited

I agree completely. Languages should enable the programmer, not hamper them. This is one of the reasons why my new favourite language is Nim. It lets you do pretty much whatever you want and with its Unified Function Call Syntax you can mix freely between OOP-style code and functional-style code without changing your coding style.

Example:

# These two are equivalent and will result in 
# some_procedure being called with arg1 and arg2
# as the first and second argument respectively
# 
# This works for independent procedures and class
# methods alike.
some_procedure(arg1, arg2)
arg1.some_procedure(arg2)