The 3 Laws of Writing Readable Code

Kantan Coding
4 Jun 202405:28

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

00:00

📚 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.

05:00

🔍 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

Nested code refers to a structure where one block of code is placed inside another. In the video, deeply nested logic is identified as a hallmark of inexperienced developers. It is challenging to reason about because the more layers of conditions there are, the more difficult it becomes to hold all necessary information in your mind while understanding the core logic.

💡Inversion

Inversion in this context refers to flipping the logic of a conditional statement to reduce nesting. Instead of executing code inside layers of conditions, the inverted approach can exit early if a certain condition is met, simplifying the code. This technique helps collapse the nested structure, making it more readable.

💡Conditionals

Conditionals are the 'if' statements used to check whether certain conditions are true or false before running certain blocks of code. The video suggests reducing the complexity of conditionals by inverting them or merging related ones, making the flow of the code easier to follow.

💡Merge Related Conditions

Merging related conditions involves combining similar 'if' statements to streamline the logic. For instance, the video gives the example of merging checks for user authentication and authorization, which are both related to user validation. While it may sacrifice some specificity, it simplifies the code.

💡Extraction

Extraction refers to the practice of pulling out complex logic from a code block and placing it into its own method or function. This technique enhances readability by giving sections of code descriptive names, allowing developers to focus on high-level logic without being distracted by details.

💡Code Duplication

Code duplication occurs when similar or identical code is repeated in multiple places within a program. The video highlights that this is problematic because changes in logic need to be made in multiple locations, increasing the chance of errors. Avoiding duplication by extracting shared logic into reusable functions is one way to improve code readability.

💡Readable Code

Readable code is code that is easy to understand and follow by other developers. The video introduces three laws for writing readable code: avoiding deep nesting, eliminating code duplication, and using meaningful naming conventions. These practices help ensure that code is clear and maintainable.

💡Naming Conventions

Naming conventions refer to the guidelines for naming variables, functions, and other elements in a program. The video stresses the importance of using meaningful names that clearly communicate what each element does, making the code easier to understand for future developers.

💡Granularity

Granularity refers to the level of detail provided in a code structure. The video mentions that merging related conditions can reduce granularity, as it may hide some of the detailed checks (e.g., user authentication versus authorization), but it balances this loss by improving readability.

💡Core Logic

Core logic refers to the primary functionality or behavior that a block of code is meant to perform. In the video, it is discussed in the context of how deeply nested structures can obscure the core logic, making it harder for developers to grasp the main purpose of the code.

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

play00:00

one of the main giveaways of an

play00:01

inexperienced developer is deeply nested

play00:04

code logic like this is difficult to

play00:07

reason about because as you're reading

play00:09

through each subsequent level you're

play00:11

needing to hold in your mind the

play00:13

condition that allows us to Traverse

play00:15

deeper into the nested structure by the

play00:18

time you get to the core logic your

play00:20

brain is likely pushing the limits of

play00:22

its capacity but you still need to

play00:25

understand the core logic while taking

play00:27

into consideration the things that

play00:28

you're already holding in your mind for

play00:31

this reason the first law of writing

play00:33

readable code is to avoid deep nesting

play00:37

we can simplify this code by first

play00:39

making use of inversion that is we

play00:42

invert the

play00:45

conditionals so instead of doing this

play00:47

inner logic only if it is not a

play00:49

maintenance period and doing the else

play00:51

logic if we can't do the inner logic we

play00:54

can simply say that if it is in fact a

play00:56

maintenance period then we don't move on

play00:58

to the next step

play01:00

as you can see that collapses the nested

play01:03

structure one level we can do the same

play01:05

with the other

play01:16

conditionals now whoever is reading your

play01:18

code will find that they are no longer

play01:21

needing to hold these conditions in

play01:23

their head while reading the core logic

play01:25

they simply know that if the code is

play01:27

executed Beyond a certain point this

play01:30

point for example then the previous code

play01:32

no longer needs to be taken into

play01:34

consideration they can discard it from

play01:36

their mind and focus on the next code

play01:38

block another technique that we can

play01:40

incorporate is we can merge related if

play01:43

statements for example checking if the

play01:46

user is authenticated and checking if

play01:48

the user is authorized are both

play01:50

validations related to off so we can

play01:53

actually merge these two keeping in mind

play01:55

that you lose some granularity here with

play01:57

the log message now that our code is

play02:00

starting to look more readable we can

play02:02

make use of another technique called

play02:04

extraction that is we'll extract some of

play02:07

the complex logic to its own methods or

play02:10

functions starting with this slightly

play02:12

confusing if statement at a glance it's

play02:14

a little bit difficult for a reader to

play02:16

quickly determine what this condition is

play02:18

for and good coders are always keeping

play02:21

in mind the experience of whoever might

play02:23

need to read their code so let's extract

play02:26

this complex logic into its own function

play02:28

and give it a description Ive name note

play02:31

that in the function we're returning

play02:33

whether or not both conditions are true

play02:35

and in the if statement we check if the

play02:37

user is valid as determined by the logic

play02:40

in the function lastly we can extract

play02:43

this entire switch statement here into

play02:45

its own function now what we've done

play02:47

here is we've made it so that the reader

play02:49

of our code can get a summary of the

play02:52

overall functionality by just glancing

play02:54

at the main function that is the reader

play02:57

can now easily see that this code simply

play02:59

calculates the taxes of the user's

play03:02

shopping cart if it's not a maintenance

play03:04

period And if the user is an authorized

play03:07

user but that very simple top level

play03:09

functionality was difficult to determine

play03:12

or understand when the code looked like

play03:16

this the second law of writing readable

play03:19

code has to do with the way you organize

play03:22

your code we're presented with two

play03:24

functions here both belonging to the

play03:27

same program although what these

play03:29

functions are doing might be pretty

play03:30

straightforward the issues start to

play03:32

reveal themselves when you consider the

play03:34

case where the reader of your code needs

play03:36

to make changes for example let's

play03:39

imagine that the reader of your code is

play03:41

tasked with removing the caching

play03:43

behavior from the application since the

play03:46

same caching behavior is found in

play03:48

multiple locations throughout the

play03:49

application the reader of your code is

play03:52

going to need to search everywhere

play03:54

potentially missing spots where this

play03:55

Behavior might exist this is a direct

play03:58

result of this application having lots

play04:00

of code duplication for this reason and

play04:03

many others the second law of writing

play04:05

readable code is to avoid code

play04:07

duplication we can extract this logic

play04:10

into its own function to be called by

play04:12

both of the parent

play04:14

functions while we're at it let's go

play04:16

ahead and extract this duplicated code

play04:18

for writing the response to the client

play04:20

as well now the reader of your code

play04:22

would only need to make changes to the

play04:24

single shared point this also makes the

play04:27

code less convoluted in turn making it

play04:29

more

play04:31

readable the final

play04:35

law here we have an example of some code

play04:38

what this code does is anybody's guess

play04:41

because the writer of this code has

play04:43

committed the ultimate sin which brings

play04:45

me to the third and final law of writing

play04:48

readable code don't use naming that only

play04:51

you understand now there are a lot of

play04:54

different naming conventions out there

play04:56

but to be honest as long as you're

play04:58

trying to follow some naming invention

play05:00

and keeping in mind that the names you

play05:02

use should be meaningful to potential

play05:04

readers of your code you will

play05:06

unfortunately be doing better than a lot

play05:08

of people out there you'll see that if

play05:10

we simply revise this code a bit to have

play05:13

some more meaningful names it becomes

play05:15

clear what this code is actually trying

play05:17

to do and it's as simple as that so

play05:19

there you have it the three laws of

play05:21

writing readable code if you found this

play05:23

video helpful don't forget to leave a

play05:25

like and I'll see you in the next one

Rate This

5.0 / 5 (0 votes)

相关标签
Readable CodeCode RefactoringNestingCode DuplicationClear NamingBest PracticesProgramming TipsCode QualityDeveloper GuideSoftware Engineering
您是否需要英文摘要?