Question

I'm designing a hospital integration system which consumes data from various hospitals (our customers), and then applies specific business rules to said data based on reading configurations from a database. If I were using Java, my first instinct would be to build a series of interfaces representing the various business rules, and then inject concrete instances (using Spring/guice) to compose a fully configured object. This would allow me to achieve a clean separation between configuration logic (what biz rules should apply to Hospital Foo?) and the actual business rules themselves.

Unfortunately, I'm not using Java, I'm using Lua. I've immersed myself in Lua literature over the last few days, and the closest analogue to DI appears to be the use of modules. Furthermore, it appears that the rules that govern how lua modules are resolved at run-time are based entirely on interrogating the local file system.

Is the "module pattern" the best/only way to achieve what am I after (separation of configuration logic from biz logic)? If so, how can one leverage Lua's module loading rules to vary the actual module(s) loaded at run-time?

Was it helpful?

Solution

Step 1: Stop thinking like a Java programmer.

You're in Lua now. There are no classes with explicit and compile-time fixed prototypes. Functions are first-class objects; they are values. So break the problem down in that way.

You have a bunch of "rules" (ie: functions). You want to apply some of those rules to certain data. You have a configuration system that says, "When applying rules to data from location X, use this set of rules." So... do that.

You detect that data comes from location X. So you call your configuration logic to build a Lua table for location X that contains your rules (ie: functions) to apply to that data. The configuration logic for location X loads the rules from wherever they are stored, and returns them. If the configuration is in a database or something, then the database entry for location X would probably refer to rules by name.

How you convert that rule name into an actual Lua function is up to you, but there are many ways. You could have a registry that preloads all of the Lua files from a directory into a table, and then pick the rule based on names in that table. Or perhaps you have a database of named Lua files/scripts, each of which is a separate rule. There are any number of ways to implement this.

In Lua, "dependency injection" is just "deciding how to build collections of functions." It's not a special thing because Lua is a much more free-form language than Java. It's just a matter of where the functions come from, how to put them together in a table, and then how to apply that table to some data. And all of those are up to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top