Search code examples
language-agnosticprogramming-languagesheader

What are the benefits and drawbacks of using header files?


I had some experience on programming languages like Java, C#, Scala as well as some lower level programming language like C, C++, Objective - C.

My observation is that low level languages try separate out header files and implementation files while other higher level programming language never separate it out. Those languages use some identifiers like public, private, protected to try to do the jobs of header files. C++ also have both identifiers and header files as well

I saw one benefit of using header file (in some book like Code Complete), they talk about that using header files, people can never look at our implementation file and it helps with encapsulation.

A drawback is that it creates too many files for me. Sometimes, it looks like verbose.

It is just my thought and I don't know if there are any other benefits and drawbacks that people ever see and work with header file

This question may not relate directly to programming but I think that if I can understand better about programming to interface, design software.


Solution

  • I'm not sure exactly what question you are asking, so I will try to rephrase it:

    What is the benefit of putting public information in a separate (header or interface) file, as opposed to simply marking information as public or private wherever it appears?

    The main benefit of having a separate interface or header file is that it reduces the cognitive load on the reader. If you are a trying to understand a large system, you can tackle one implementation file at a time, and you need to read only the interfaces of the other implementations/classes/modules it depends on. This is a major benefit, and languages that do not require separate interface files (such as Java) or cannot even express interfaces in separate files (such as Haskell) often provide tools such as Doxygen or Haddock so that a separate interface, for people to read, is generated from the implementation.

    I strongly prefer languages like Standard ML, Objective Caml, and Modula-2/3, where there is a separate interface file available for scrutiny. Having separate header files in C is also good, but not quite as good because in general, the header files cannot be checked independently by the compiler. (C++ header files are less good because they allow private information, such as private fields or the implementations of inline methods, to leak out into the header files, and so the public information becomes diluted.)

    It's folklore in the language-design world that for typical statically typed languages, only about 10% of the information in a module is public (measured by lines of code). By putting this information in a separate header file, you reduce the reader's workload by roughly a factor of ten.