[cs631apue] coding style
Jan Schaumann
jschauma at stevens.edu
Fri Oct 18 13:46:05 EDT 2024
Hello,
Some of you have had questions about how to improve
your coding style. This is unfortunately something
that really only can be learned with practice and in
collaboration with others, but we can try to get in
the habit of a few practices.
Note that "coding style" is more than just where we
place our braces, how we indent, or how we name our
variables, but includes logic flow.
As you write your code, you should consider
_readability_. That is, remember that _other people_
will have to read your code and be able to make sense.
Try not to write code that's clever, but code that
makes it easy to understand what it does.
Descriptive variable- and function names are one
thing, factoring repeating code blocks into their own
functions another. Avoid nesting and long
if-else-else-else-else blocks and instead favor
"return early".
Try to keep your code complexity as low as possible,
so that when you look at a given block, you actually
know it does without having to jump into other
functions or page up and down to see where a given
error condition is triggered or handled.
This is a very good video explaining some of these
aspects:
https://youtu.be/CFRhGnuXG-4
There is more useful advice in the other videos from
this channel.
As you write your code, periodically ask yourself
whether you would understand this code if you hadn't
been immersed in it for the last few hours. Does it
read naturally, logically? Or does it require being
aware of multiple different states?
Does it follow a "happy path"? (See e.g.,
https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88)
Thinking about this as you write your code or as you
revisit your code after some time can make a
significant difference in the readability and quality
of your code.
-Jan
More information about the cs631apue
mailing list