How to write “simple” code?
Before, I didn’t update the content because there were so many things in the company. My friend posted an article on my account, but recently I’m not busy anymore, so I continue to update the article.
When you’re doing real development, you’re bound to find people telling you, or you’re reading on the Internet: Write simple code. Write simple code.
This sentence is actually linked to the familiar kiss principle in design patterns. If you have learned design patterns, you will more or less encounter the following problems when learning kiss principle:
- Why do programmers around you tell you it’s important to keep your code “simple”?
- What is good “simple” code?
- How to write “simple” code?
- Is the Yagni principle the same as the KISS principle?
These questions seem simple, but the answers are not.
Why do you want to keep your code “simple”
For the current domestic some small and medium-sized factories, even some departments of the programmers, the code is written to run on the line, why to keep the code “simple” do not understand. There are actually three reasons:
-
Prevent code from corrupting. It’s easy to understand, when your company starts a project, the requirements are simple, the business is simple, maybe two or three of you do the back-end development. The code is simple to read and logical, but as time goes on, the lines of business become more and more complex, and more and more people are involved in the project. The amount of code grows exponentially, the logic becomes more complex, and the code becomes difficult to understand and maintain. At this point, the code begins to corrupt. Keeping the code simple, on the one hand, can reduce the difficulty of understanding the module, on the other hand, it also makes the scope of code modification more clear, which can effectively prevent code corruption.
-
Reduce the time cost of investment. We know that software complexity comes from three sources: code size, technical complexity, and implementation complexity. In general, the more complex the code, the more time it costs to invest in these three areas. For example, the understanding of the investment required to maintain 100,000 lines of code is different from the logic combing time required to maintain 1000 lines of code. Another example: The learning time required to use Redis as a cache is different from that required to use LRU local cache.
For developers, maintaining code requires time to modify, debug, understand the logic and make the code work properly. Once the code is very complex, it increases the cost of time, which in turn increases the development cost of the development team. If the code is kept simple and clear, the immediate effect is to reduce the time it takes to learn and maintain the code, which is a welcome result for many development teams.
-
Third, iterate quickly and embrace change. Although more and more teams now began to adopt agile development, but in reality, has been trapped in the “business needs to do forever infinite loop” is the current situation of the development team, which means that developers only have less time to write the code, even if has a heart, want to write a simple code of schedule pressure also can write code to work as soon as possible. Over time, the team’s code became more complex and less efficient, and the team’s intention to embrace change was forced to become less able to tolerate it. One effective way to change this is to keep things simple, such as better testability, better scalability, better understanding, more flexible design, etc.
What do you mean by “simple” in code?
Do you hear a lot about the KISS principle?
- Product requirements documents are out, you see how simple how to design it, the function to quickly go online.
- Isn’t there a library for this? Choose a simple library that encapsulates the functionality, and the customer will want it tomorrow.
- There are so many open source frameworks out there, just pick a simple one to implement. I don’t care about the technology, I care about the solution.
- You see how simple the design of XX factory is and how good the experience is. Why don’t you make it that simple?
You see, a lot of times we have the illusion of simplicity: simple analysis + simple design + simple programming = simple product. But in fact, does this simple combination lead to the ultimate simplicity?
In my opinion, simplicity is the ultimate state of software development. Management or end users really don’t need to care about the complexity of the code logic behind it, whereas developers have to think about the complexity behind it. In other words, the essence of programming is to control complexity.
So what exactly does “simple” mean in code?
First, simplicity! = Simple design or simple programming. Simplicity, when combined with verbs, is too easily misunderstood, especially in software development. For example, in many projects today, we do simple design or no design in order to complete the schedule, thinking that as long as it is necessary to refactor later, we will use simple programming when coding, and it is called iterative agile development. In practice, there is little time to refactor late in the project, and problems frequently occur (longer locating time, too deep logic nesting, constant patching, etc.), and the project often ends up failing. (This is a problem that will appear in most projects at present. In front of the design, we think about CV, and then go online quickly. In the back of the optimization, we think about the optimization, and then the demand becomes more and more.
So, keeping it simple is not just about doing simple design or simple programming, but designing or programming with the goal of making the final output simple, and it doesn’t matter if it’s complicated.
Second, simple! = Small number. We often associate simplicity with quantity. For example, fewer lines of code, fewer library components used, and fewer architectural designs seem to be simple. But in fact, the small number may just appear simple, but also introduce more complex problems. (For example, in the project, we often make the project simple in order to introduce less middleware. For example, in the case of big data, we are still using mysql to do some complex queries with large data volume.)
Finally, simple! = Overbrevity. If you’ve ever seen encrypted code, you know what overly concise code is. Such code is machine-readable, but almost unreadable to humans. In real life, we’ve probably all written code that doesn’t have any comments, doesn’t use any design patterns, uses the most straightforward data structures and algorithms, and names variables with acronyms. Then, after a while, you don’t even understand the clean code until you read it from beginning to end. Imagine how difficult it would have been for anyone else. So simple code can be concise, but it’s certainly not overly concise.
Now let’s see what “simple” means.
-
Simplicity should be sticking to practice. We often say that code should be simple, but we ignore the actions that are more important to keep simple. In other words, we all know this, but we don’t actually stick to it when we write the code. Keeping it simple is hard because most people focus on the benefits of doing it in the end and forget about the effort required to get there in the first place.
Really simple code usually hides a lot of hard work behind it, such as carefully analyzing requirements, choosing the right technical framework, designing more appropriate data structures and algorithms, keeping the code readable while implementing, etc., everything is not easy, and the final simplicity can be achieved only through long-term adherence.
-
Simplicity should be as simple as possible, but not too simple. In other words, manage the appropriate code context, and build the program within the boundaries with minimal knowledge, just to meet the requirements, with some restraint. A lot of times, it’s easy to overdevelop functionality because context boundaries aren’t taken into account, leading to requirements diffusion and knowledge expansion. For example, the requirements only ask you to develop an editor, but during development you discover a new feature you want to experiment with, and you end up developing an IDE. From the user’s point of view, all you need is a simple editor, and while you’re doing the right thing, you’re making something simple complicated.
-
Simplicity should make it easier for others to understand the logic of the code. After the code is written, 80% of the time it is read. The advantage of simple code is that it can be read at a glance. To do this, you have to set a higher standard for the person who wrote the code: Not only do you need to implement code logic with clear algorithms and data structures, but you also need to use object-oriented programming techniques to improve code reusability, and even write more unit tests and comments to improve maintainability. In short, good code is about giving simplicity to others and keeping complexity to yourself.
How to write “simple” code?
-
Don’t patch code for long periods of time. Because it would set a bad example to the team, when you’re in a patch of quick profits in the encoding (change fast, quick effect), will unconsciously give other people a kind of psychological hint – this code you just need to constantly patch can solve the problem, maintain the code would have preferred to choose this method, rather than refactoring it.
-
Don’t flaunt your programming skills. If your team is not familiar with Java 8’s Lamda expression syntax, you don’t want to start writing code like this, but you can help your team improve programming (and indirectly increase your technical impact) by sharing the strengths and knowledge of Lamda expressions. It’s important not to use techniques just to make yourself look good, especially if you use advanced syntax on maintenance projects, which can result in the maintenance person having to spend a lot of time and energy learning or studying your code.
-
Don’t simply program. Hard coding, one-shot coding, copy-and-paste coding, and search-oriented programming are all simple programming, and if you continue to write simple programming habitually, you may end up with more complex and costly refactoring and rewriting. Not only does this not improve code extensibility, it also makes the code unmaintainable and unrefactored at a later stage. Local simplicity leads to greater complexity of the whole, which is now recognized as a pyrrhic approach.
-
Don’t optimize too early. In order to make the code simple, optimization is essential, but premature optimization can cause a lot of the core code logic is hidden, and maintain code in order not to damage the original design (for the design of the sooner the better), only constantly modify an existing design to adapt to this constant, finally actually easy to cause the architecture may be damaged.
If the top is four don ‘ts, there are four more below.
-
Do regular Code reviews. If simplicity is hard to agree on, code that is easy to understand at a glance is always good code. When people read your code, they will naturally judge your code, good or bad, and this is a good time to think about whether your code is simple enough.
-
Choose the appropriate coding specification. Coding specifications are a summary of good coding practices that can help you write “simple” code and develop a simple programming style. However, many of the big companies’ coding specifications are too generic, and while good, they may not be suitable for you. This is where you need to tailor and refine your experience to develop a “simple” coding style that works for you.
-
Refactor when necessary. Is not to say that have to wait to refactor code completely unable to modify again, you can easily in each iteration version refactoring, for example, the separation of a class that is too much responsibility, abstract one last time before doing the universal service, reduce the if – else nested in the business layer, data objects on different business subcontract management, etc. When you do this in time, the code as a whole becomes simpler.
-
Aim for gradual optimization. Optimization must have a goal, otherwise it is easy to blindly optimize, or even consider optimization as a pure KPI. If the performance of the program does not reach a real performance bottleneck, no optimization is necessary. And optimization should be phased and step, do not do a one-time big optimization, big improvement, this will lead to frequent code modification, but easy to introduce more bugs.