I'm looking for a way to clarify the contracts of my Lua functions. In particular, which attributes there parameters are supposed to have.
To illustrate my problem, some code snippets with typical structure of my current code. A function that constructs a new "instance" with two public functions.
local function newTextPrinter(color)
return {
print = function(textToPrint)
PrintText(textToPrint, 20, color, 5, 'center');
end,
printBig = function(textToPrint)
PrintText(textToPrint, 30, color, 5, 'center');
end
}
end
A function that takes a parameter that is supposed to have the same signature (or a superset).
local function printSomeStuff(textPrinter)
textPrinter.print("some")
textPrinter.printBig("stuff")
end
Invocation of the later function
local textPrinter = newTextPrinter("ffffffff")
printSomeStuff(textPrinter)
The issue with this code is that you cannot tell what the textPrinter
parameter provided to printSomeStuff
is supposed to look like without looking at the implementation of printSomeStuff
. While with this example it's easy enough to do so, this is often not the case (and in my scenario forces hopping between files). There is also no hint that a suitable value can be obtained via newTextPrinter
, apart from the similarity in name.
Is there a way to make the code more self documenting and reveal the authors intent better?
I prefer an approach that is light and does not try to emulate class based inheritance. Similarly, code is preferred over documentation, and failing that, documentation in a format understood by tools is preferred over free form. Clearly I can just write a comment like "parameter textPrinter
needs print
and printBig
public functions", however this is very error prone if nothing tells you about mistakes you make in the documentation, or when you refactor the code and forget to update it.
I'm using Lua 5.0 and am quite new to the language.