Are there coding standards for whether procedural programs should have source code listed top-down or bottom-up? [closed]

Let’s say I have a basic procedural program which is well structured into decomposed functions. For example, a main() function which calls functions a and b, which in turn each call functions c and d, and e and f. In pseudo-Python, this could be written bottom-up like this:

def c():
    # Do stuff

def d():
    # Do stuff

def e():
    # Do stuff

def f():
    # Do stuff

def a():
    c()
    d()

def b():
    e()
    f()

if __name__ == "__main__":
    a()
    b()

However, it could also be written top-down like this:

if __name__ == "__main__":
    a()
    b()

def a():
    c()
    d()

def b():
    e()
    f()

def c():
    # Do stuff

def d():
    # Do stuff

def e():
    # Do stuff

def f():
    # Do stuff

In general, in many languages, both of these would be valid, but is there a preferred coding style? I’m primarily thinking of readability/maintainability here, not efficiency of compilation or execution. Does it vary between languages? I’m thinking firstly of Python here, but there are many other languages this question could apply to here, so I’m happy to make it broader.

Note: I am not thinking about the design of the program here (whether to think top-down or bottom-up first), I am specifically talking about the ordering of the source code.

5

Not much of coding in Python and its long time since I coded in C.

For C programs, I used to prefer top-down, because that is how I design my programs. If a calls b, b is listed after a. I also used to have a header for each .c file that lists all functions in it and included in the .c file.

I follow the same model in Java class methods now.

The point of writing a method is to do one thing in an obviously correct way. This principle is usually applied to explain why over-long methods are bad; a method should fit on your monitor in one piece.

But it also cuts the other way: a method should not be so small that several fit on your monitor at the same time! This means that it is quite irrelevant in which order they appear in the source. As long as your language does not require declaration-before-use, and you have a decent environmant that lets you jump from use to definition at a single keypress, there is simply no reason to care one way or the other. I’d go further and say: if you care which way your methods are ordered, then they are doing too little.

4

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *