Should I put many functions into one file? Or, more or less, one function per file?

后端 未结 9 888
故里飘歌
故里飘歌 2021-01-02 02:54

I love to organize my code, so ideally I want one class per file or, when I have non-member functions, one function per file.

The reasons are:

  1. When

9条回答
  •  迷失自我
    2021-01-02 03:59

    We use the principle of one external function per file. However, within this file there may be several other "helper" functions in unnamed namespaces that are used to implement that function.

    In our experience, contrary to some other comments, this has had two main benefits. The first is build times are faster as modules only need to be rebuilt when their specific APIs are modified. The second advantage is that by using a common naming scheme, it is never necessary to spend time searching for the header that contains the function you wish to call:

    // getShapeColor.h
    Color getShapeColor(Shape);
    
    // getTextColor.h
    Color getTextColor(Text);
    

    I disagree that the standard library is a good example for not using one (external) function per file. Standard libraries never change and have well defined interfaces and so neither of the points above apply to them.

    That being said, even in the case of the standard library there are some potential benefits in splitting out the individual functions. The first is that compilers could generate a helpful warning when unsafe versions of functions are used, e.g. strcpy vs. strncpy, in a similar way to how g++ used to warn for inclusion of vs. .

    Another advantage is that I would no longer be caught out by including memory when I want to use memmove!

提交回复
热议问题