The 3 Laws of Writing Readable Code
Summary
TLDRThis video explains three essential laws for writing readable code. First, avoid deeply nested logic by inverting conditions and simplifying structure. Second, reduce code duplication by extracting shared functionality into reusable functions, making future updates easier. Lastly, use meaningful naming conventions to ensure code clarity, making it easier for others to understand and maintain. By following these practices, developers can produce cleaner, more maintainable code that's easier for others to work with.
Takeaways
- 😀 Deeply nested code logic is difficult to understand and maintain, as it overloads the reader's mental capacity.
- 💡 Avoid deep nesting by inverting conditionals, allowing simpler and more readable code.
- 🧠 Simplifying conditions helps readers focus on the core logic without holding previous conditions in mind.
- 🔗 Merge related `if` statements, like authentication and authorization checks, to reduce complexity, though at the cost of some logging granularity.
- ✂️ Extract complex logic into well-named functions to improve readability and make the code's purpose clearer at a glance.
- 📜 Code extraction also helps to summarize the overall functionality, allowing readers to quickly grasp the main purpose of the code.
- 🚫 The second rule of readable code is to avoid duplication, as repeated logic can lead to maintenance challenges.
- 🔄 Extracting duplicated code into shared functions simplifies future updates and improves code readability.
- 🔍 The third rule of readable code is to use clear, meaningful naming conventions that others can easily understand.
- 📘 Well-chosen names for functions and variables make code self-explanatory, improving the reader's comprehension and maintainability.
Q & A
What is the main problem with deeply nested code logic?
-Deeply nested code logic is difficult to reason about because it requires the reader to hold multiple conditions in their mind as they traverse deeper into the nested structure. This makes it harder to understand the core logic and adds unnecessary complexity.
How can inverting conditionals help in simplifying nested code?
-Inverting conditionals simplifies nested code by allowing early exits when certain conditions are met. This reduces the need for deeper nesting and makes the remaining code easier to follow.
What is the benefit of collapsing nested structures in code?
-Collapsing nested structures reduces cognitive load, allowing the reader to discard unnecessary conditions once they move past them, and focus on the core logic without holding all previous conditions in their mind.
Why is merging related `if` statements beneficial, and what trade-off might it involve?
-Merging related `if` statements, like authentication and authorization checks, improves code readability by grouping similar logic. However, this approach may reduce the granularity of error or log messages, as it combines multiple checks into one.
What is the technique of extraction, and how does it improve code readability?
-Extraction involves moving complex logic into separate functions or methods with descriptive names. This improves readability by giving the reader a clear overview of the main function's purpose without getting bogged down in details.
How does extracting a switch statement into its own function benefit the reader of the code?
-By extracting a switch statement into its own function, the code becomes more readable, as the reader can focus on understanding the high-level flow without being distracted by the internal details of the switch logic.
What is the second law of writing readable code, and why is it important?
-The second law is to avoid code duplication. This is important because duplicated code makes maintenance difficult, as changes need to be made in multiple places. By extracting shared logic, the code becomes easier to update and less error-prone.
How can avoiding code duplication simplify making changes to a program?
-Avoiding code duplication simplifies changes by centralizing shared logic into single functions. This allows modifications to be made in one place, reducing the risk of missing duplicate code that may exist elsewhere in the application.
What is the third law of writing readable code, and what mistake does it address?
-The third law is to avoid using naming conventions that only the original developer understands. It addresses the common mistake of using unclear, ambiguous, or meaningless names that make the code difficult for others to read and understand.
Why is meaningful naming important in code?
-Meaningful naming helps other developers understand what the code is doing without needing to decipher unclear names or spend extra time figuring out its purpose. It improves maintainability and collaboration.
Outlines
📚 The First Law of Readable Code: Avoid Deep Nesting
The paragraph discusses the challenge of deeply nested code logic which can be difficult to understand and maintain. It emphasizes the importance of the first law of writing readable code, which is to avoid deep nesting. The speaker suggests simplifying code by inverting conditionals and merging related if statements to reduce complexity. Additionally, the technique of extraction is introduced, where complex logic is moved into its own methods or functions to improve readability. The paragraph concludes by emphasizing that readable code should be easy to understand at a glance, allowing the reader to quickly grasp the overall functionality.
🔍 The Second Law of Readable Code: Avoid Code Duplication
This paragraph focuses on the second law of writing readable code, which is to avoid code duplication. The speaker explains that duplicated code can lead to maintenance issues, as changes need to be made in multiple places, increasing the risk of errors. The solution proposed is to extract duplicated logic into its own function, which can then be called by the parent functions. This not only simplifies the code but also makes it more maintainable. The paragraph also touches on the importance of meaningful naming conventions to ensure that code is understandable to anyone who might read it.
Mindmap
Keywords
💡Nested Code
💡Inversion
💡Conditionals
💡Merge Related Conditions
💡Extraction
💡Code Duplication
💡Readable Code
💡Naming Conventions
💡Granularity
💡Core Logic
Highlights
Deeply nested code logic is difficult to reason about and makes the code hard to read.
Avoid deep nesting by inverting conditionals, simplifying the structure and reducing mental load.
By collapsing nested structures, we make the code easier to follow and understand.
Merge related conditional checks to reduce redundancy, though it may reduce granularity in logging.
Extract complex logic into its own function to improve readability and provide descriptive names for better understanding.
Creating standalone functions for complex conditions allows readers to quickly grasp the core logic.
Top-level functionality should be easily discernible at a glance to make reading and maintaining code simpler.
Avoid code duplication by extracting common logic into reusable functions.
Refactoring duplicated code makes it easier to implement future changes without missing parts.
Readable code is achieved through simplicity, which can be attained by reducing convoluted structures.
Use meaningful naming conventions for functions and variables so others can understand the purpose of the code.
Following any meaningful naming convention is better than using names that only make sense to the original author.
Code with unclear or arbitrary naming becomes difficult to understand and maintain.
Clear and concise naming, combined with well-organized logic, ensures the code's purpose is transparent.
The three laws of writing readable code are: avoid deep nesting, avoid code duplication, and use meaningful naming.
Transcripts
one of the main giveaways of an
inexperienced developer is deeply nested
code logic like this is difficult to
reason about because as you're reading
through each subsequent level you're
needing to hold in your mind the
condition that allows us to Traverse
deeper into the nested structure by the
time you get to the core logic your
brain is likely pushing the limits of
its capacity but you still need to
understand the core logic while taking
into consideration the things that
you're already holding in your mind for
this reason the first law of writing
readable code is to avoid deep nesting
we can simplify this code by first
making use of inversion that is we
invert the
conditionals so instead of doing this
inner logic only if it is not a
maintenance period and doing the else
logic if we can't do the inner logic we
can simply say that if it is in fact a
maintenance period then we don't move on
to the next step
as you can see that collapses the nested
structure one level we can do the same
with the other
conditionals now whoever is reading your
code will find that they are no longer
needing to hold these conditions in
their head while reading the core logic
they simply know that if the code is
executed Beyond a certain point this
point for example then the previous code
no longer needs to be taken into
consideration they can discard it from
their mind and focus on the next code
block another technique that we can
incorporate is we can merge related if
statements for example checking if the
user is authenticated and checking if
the user is authorized are both
validations related to off so we can
actually merge these two keeping in mind
that you lose some granularity here with
the log message now that our code is
starting to look more readable we can
make use of another technique called
extraction that is we'll extract some of
the complex logic to its own methods or
functions starting with this slightly
confusing if statement at a glance it's
a little bit difficult for a reader to
quickly determine what this condition is
for and good coders are always keeping
in mind the experience of whoever might
need to read their code so let's extract
this complex logic into its own function
and give it a description Ive name note
that in the function we're returning
whether or not both conditions are true
and in the if statement we check if the
user is valid as determined by the logic
in the function lastly we can extract
this entire switch statement here into
its own function now what we've done
here is we've made it so that the reader
of our code can get a summary of the
overall functionality by just glancing
at the main function that is the reader
can now easily see that this code simply
calculates the taxes of the user's
shopping cart if it's not a maintenance
period And if the user is an authorized
user but that very simple top level
functionality was difficult to determine
or understand when the code looked like
this the second law of writing readable
code has to do with the way you organize
your code we're presented with two
functions here both belonging to the
same program although what these
functions are doing might be pretty
straightforward the issues start to
reveal themselves when you consider the
case where the reader of your code needs
to make changes for example let's
imagine that the reader of your code is
tasked with removing the caching
behavior from the application since the
same caching behavior is found in
multiple locations throughout the
application the reader of your code is
going to need to search everywhere
potentially missing spots where this
Behavior might exist this is a direct
result of this application having lots
of code duplication for this reason and
many others the second law of writing
readable code is to avoid code
duplication we can extract this logic
into its own function to be called by
both of the parent
functions while we're at it let's go
ahead and extract this duplicated code
for writing the response to the client
as well now the reader of your code
would only need to make changes to the
single shared point this also makes the
code less convoluted in turn making it
more
readable the final
law here we have an example of some code
what this code does is anybody's guess
because the writer of this code has
committed the ultimate sin which brings
me to the third and final law of writing
readable code don't use naming that only
you understand now there are a lot of
different naming conventions out there
but to be honest as long as you're
trying to follow some naming invention
and keeping in mind that the names you
use should be meaningful to potential
readers of your code you will
unfortunately be doing better than a lot
of people out there you'll see that if
we simply revise this code a bit to have
some more meaningful names it becomes
clear what this code is actually trying
to do and it's as simple as that so
there you have it the three laws of
writing readable code if you found this
video helpful don't forget to leave a
like and I'll see you in the next one
Weitere ähnliche Videos ansehen
Write Better Code
React Naming Conventions You should follow as a Junior Developer - clean-code
42. OCR A Level (H046-H446) SLR8 - 1.2 Introduction to programming part 3 procedures & functions
How to code like Senior Engineers!?
10 Tips Menulis Code JavaScript yang Clean
Constants | Godot GDScript Tutorial | Ep 03
5.0 / 5 (0 votes)