DEV Community

OCaml interface files–hero or menace?

Yawar Amin on February 02, 2020

FROM time to time the question comes up in the OCaml/ReasonML communities: Why do I need two files–an implementation file and an interface file...
Collapse
 
johnridesabike profile image
John

Great post. I think it's also worth mentioning another benefit to interface files: they let the compiler do more optimizations. When the compiler knows that certain values are only internal to a module, it can compile them more efficiently.

And related to that, the compiler can also give you more warnings about unused values. That's especially useful if you have a large module with lots of internal helper functions and you want to clean them up.

Collapse
 
anler profile image
Anler • Edited

In other words–a module can wear many masks, depending on who is using it. I'll explore this technique more in a future post.

Do you know if there's a way of telling the compiler which interface file to use depending on the environment? For example:

  • testing: keep all definitions public to allow unit testing
  • release: use a more strict/production-oriented interface file

This is one of the things I miss most from Rust

Collapse
 
yawaramin profile image
Yawar Amin

Yes–apply the signature to the module at its point of use, not its point of definition. This keeps the module definition as general as possible but you can expose different facets of the module to different consumers.

Personally I don't recommend that, however. I think that unit tests should test using the exact same interface that's exposed in production. They shouldn't become deeply coupled to implementation details, because that leads to fragile tests.

Collapse
 
yawaramin profile image
Yawar Amin

Ha, ReWeb will have to wait a bit more :-) for the modules post, I am still mulling the idea in my head.

 
yawaramin profile image
Yawar Amin

Thank you! I'm enjoying building it up piece by piece. Please let me know if you have any questions.