[erlang-questions] Why we need a -module() attribute?

Richard A. O'Keefe ok@REDACTED
Fri Feb 19 05:58:07 CET 2016

On 18/02/16 6:38 am, derek wrote:
> that -module(). line sound like redundant, if it can be mismatched,
> why can't it be omitted?
> compiler can derive the module name from the filename anyway;
No it cannot.  I *have* had this happen to me.
I write a module 'search' and put it in a 'search.erl' file.
I copy it to a memory stick.
I plug the stick into another machine.
Both machines have case-sensitive file systems, but
the file name was changed to SEARCH.ERL

Now, just given the file name SEARCH.ERL, was the module name
or something else?

Deriving module names from file names is like
holding a chain-saw by the blade.
Usually OK but from time to time you'll lose a hand.

>   Java
> also made that filename has to match class name, that is a design
> mistake and unnecessary requirement, to my opinion;
Why?  A Java source file may contain MANY classes.
Here is an AWK script that generates a file that defines 10 (as in TEN,
as in twice FIVE) public classes.

     c = "Hemulen"
     f = c ".java"
     print "public class " c " {" >f
     s = "Hattifattener"
     for (i = 1; i <= 9; i++) {
         k = s i
         print "    public static class " k " {" >f
         print "        public static final int v = " i ";" >f
         print "    }" >f
         print "    public static final " k " v" i " = new " k "();" >f
         print "" >f
     print "}" >f
     print "" >f

Run that script, then compile Hemulen.java, and you get ten *.class files.
Those classes cannot ALL get their names from Hemulen.java

Actually, the coupling between Java file names and class names IS a
major pain in the posterior.  I recently picked up a repository of source
code for analysis  There are *hundreds* of .java files, and
because the file names got mangled.  I am going to have to read
hundreds of files and manually change their names.  Sigh.
The one and only thing that will make this situation salvageable
is that the files *DO* contain the class names.
> or on the other hand, if -module() is proved to be useful, why not
> just ignore the filename, and always use what's defined in -module()?
> in many modern language design like Go and Elixir, it's allowed to
> define multiple Class/Module in one file
Or you could mention Simula67, which allowed many classes in a source 
file, and
didn't care what the source file was called.

We can't just ignore the file name yet, for the same reason that Java 
Java and Erlang use the file name to *find* the compiled module.
It is really amazingly useful to have some confidence that you have 
found the
*right* file, given the horrible things file systems can do to you.

File name syntax is far more diverse than people realise.

More information about the erlang-questions mailing list