A bit late to the party, but I thought I’d chip in.
I use a lot of enums in meep and shade, here’s my approach to help the API user, here’s a real function from shade:
/**
*
* @param {ShadeMaterial[]} output Where the output goes
* @param {number} output_offset Where to start writing
* @param {TransparencyMode} alpha_mode
* @param {ShadeDrawMode} draw_mode
* @param {ShadeDrawSide} draw_side
* @param {ShadeMaterial[]} materials inputs to filter
* @param {number} count number of inputs to read
* @returns {number} number of materials that were filtered
*/
export function filter_materials_by_bucket(
output,
output_offset,
alpha_mode,
draw_mode,
draw_side,
materials,
count
) {
assert.enum(alpha_mode, TransparencyMode, 'alpha_mode');
assert.enum(draw_mode, ShadeDrawMode, 'draw_mode');
assert.enum(draw_side, ShadeDrawSide, 'draw_side');
assert.isNonNegativeInteger(count, 'count');
assert.isArray(materials, 'materials');
assert.isNonNegativeInteger(output_offset, 'output_offset');
assert.isArray(output, 'output');
....
The let’s look at just one enum here, the TransparencyMode
assert.enum(alpha_mode, TransparencyMode, 'alpha_mode');
The enum is defined as
/**
*
* @enum {number}
*/
export const TransparencyMode = {
Opaque: 0,
AlphaTested: 1,
/**
* Blended
*/
Transparent: 2,
}
So if the user supplies anything other than 0,1 or 2, they get an asertion error, let’s assume the user provided value 3, they would get an error:
alpha_mode(=3) is not a valid enumerable value, valid values are: [0, 1, 2]
Assertions can be compiled out, most packaging modules out there support those, here’s an example for vite:
// vite.config.js
import strip from '@rollup/plugin-strip';
export default defineConfig({
plugins: [{ ...strip(), apply: 'build' }]
});
I remember when three.js used to do more input validation, with assertions you get best of both worlds - more validation and no production overhead.
It’s a different philosophy, but good error checking/messaing is a valuable thing in an API.
Well, there’s also TypeScript, but that’s for the weak of will
Just in case anyone find it confusing, the assertions here are from @woosh/meep-engine/src/core/assert