Search code examples
typesluareadabilitycode-documentationself-documenting-code

Self documenting parameters in Lua


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 textPrinterparameter 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.


Solution

  • Yes. First, naming is key. Next, comments can describe the contract. Further, formatted, tagged, processed and contextually presented comments are how many people program. Finally, hyperlinks in the formatted comments provide an avenue to access complete documentation.

    There are a few formatted-comment processing systems: LuaDoc, LDoc, LDT Documentation Language,…. Unfortunately, there is no standard and the choice would be primarily driven by the capabilities of user's IDE. Some IDE will even assist the author in formatting the comments.

    Even without processing, the tagging and formatting—for the most part—improves human readability. So as long the source is easy to pop up, it does help.

    Popover documentation for the print function