2020 I want to write code like

In early 9102, a roommate asked me a question, how can enhance the ability to write code?

Unfortunately: it was only reply to some of his ideas, such as to look at open source, more books, more learning, more attention to industry trends and practices, but also listed a number of principles. But these did not have summed up, or that there is no example of a language is always vague. So at the end of this year on the occasion, the code corresponding to the kinds of problems encountered in this year explain one by one.

Usefulness of the code of good

The book is actually built on a fairly unreliable premise: good code is meaningful. I've seen too ugly code to their owners earn a lot of money, so in my opinion, the software to commercial success or widespread use of "good code quality" is neither necessary nor sufficient. Even so, I still believe, in spite of code quality can not guarantee a better future, he still has his sense: With the good quality of the code after the business needs to be confident in the development and delivery of software the user can adjust direction in order to respond to opportunities in a timely manner and competition, the development team can challenge again to maintain high morale and frustration before. All in all, compared to poor quality, heavy error code, good code is more likely to help you achieve business success.

The above text excerpt Preface to "achieve mode", has been translated from the book the first time in 10 years, but the book still has great value. While for the remarks, I do not deny that hold views. But I think, bad code than good code more of the financial costs (ah, not wrong, I'm sure). For the same business needs, bad code requires the effort, more time, but output will be less. At the same time according to the broken window theory (the theory that negative phenomena in the environment if there is laissez-faire, will induce people to follow, and even intensified), the bad code that will produce worse code. This is a vicious circle, if not controlled, complete the requirements of the time will slowly lose control. Demand needs to be done and who will lose leave.

In other words, good code can achieve win-win, allowing users to cool, to let cool boss, allows developers to cool. In short, everyone is really cool cool.

How to write good code is

Even little more than

Time to relieve pressure from the service line open out using design and code.

The best way to write secure and reliable applications. Write nothing; deploy nowhere.

Above is taken from one of the most github project nocode on fire. Laziness is one of the virtues of a programmer. So learning the business, understand the business, refusing compulsory homework unnecessary demand is also a programmer. For more information please refer to how to eliminate the word needs? This is a blog, of course, in most scenarios, we do not have the ability to say no and demand for power, but in any case, the depth of understanding of the business, the customer is more demanding empathy for programmers . To solve the problem is a programmer needs to be done. Better able to understand the meaning of problems to solve the problem.

For software development, the time must be the most valuable, the most valuable resource. Accordingly, as far as possible the time spent in solving new problems, rather than exact solutions to a problem that already exists in the same old tune. So, try not to write their own code, but the design and implementation of others to borrow. In fact, you can hardly designed and completed more appropriate than the open-source code under a very short time pressure.

Of course, certain open source author wanted his products to a larger audience, so from the design, it will adopt a more universal design, if your needs are more specific and you think you can not convince authors to help you "work for free" ( author or rejected), then you only need to be packaged and rewritten in a particular place, but much simpler than a complete rewrite too much.

Of course, research and the use of new technology solutions to the project is the ability, but do not because of a small feature to add a very large project.

I had encountered before other small partners because they can not use digital rounding. He said fixed a problem with the method used math.js junior partner.

(11.545).toFixed(2)
// "11.54"

If you want to know why the fixed method in question, Why can refer to (2.55) .toFixed (1) equal to 2.5? The author v8 source to explain why there is such a problem, as well as providing a fixed part of the revised program.

In fact, if there is no great demand for accuracy, use a front-end function completely problem will be solved, and all without complex math libraries such precision.

function round(number, precision) {
    return Math.round(+number + 'e' + precision) / Math.pow(10, precision);
}

Of course, there are also small partners come to the table to ask me a lot of data optimization, my first reaction was React Infinite or vue-infinite-scroll such solutions. But the other party to provide more information, including context, the use of the technology stack, the current amount of data size, the size of the future may need to reach, whether you need to modify the current table and so on. Get this information, combined with business point of view, compared to the increase of a library, more convenient and fast way whether as follows.

// because of vue model, can be of great use Object.freeze performance gain 
this.xxx = Object.freeze (xxx);

With the accumulation of business, the growth of the code. The increasing complexity of cost management, reduce the dependence. The use of open source makes the task easier. Time is cost. The key is to make profit can be maximized.

Learn more to do less.

Unite

Because different people experience different coding and coding preferences projects with a feature of the implementation code may vary. But if not constrained, let everyone write their own modules according to their own preferences, I am afraid it will turn into a disaster.

So every time learning new techniques, I always wanted to see more of the code examples, how the author's understanding of the community and how to understand. In order to implement the code style will not deviate from the community too much, so can improve the efficiency of communication and collaboration. Similar to "Ali Baba Java Development Manual" vue style guide or the voice of experience from this large company or community, to be read several times. Because they encounter problems and business more complex.

For internal development company, write a component when the life cycle of the above code in a file or on the bottom, how to code a function point centrally located. Universal modify code. Limit the number of lines of code. Able to list a unified scheme, Dolly and less harm.

Simplify (abstract)

Abstract refers drawn from specific things, summarized their common aspects, such as the nature of attributes and relationships, and the individual, non-essential aspects, attributes and relationships give up the thought process.

If you face a large system, you will find that reconstruction does not solve the fundamental problem, it can only reduce the complexity of the code and the number of lines of code a little, only the abstract can resolve substantive issues.

Whether it is a database design, architecture, design, business design, code design, anything abstract design are inseparable. Strong ability to abstract the difficulties faced by the weaker will be much less than capacity.

Or some abstract weak junior partner even encounter some problems need to re-design the overthrow of then, this is the time and business development is not acceptable.

Here to talk about the code, the following is also an example, as axios library has interceptors and their business, did not see the source code before, I always thought he was treated in three stages:

  • Request Interceptor

  • Business Process

  • In response to intercept

But if you look at the source code, you will find that in fact, in the author's opinion, these three stages are actually dealing with a Promise queue only.

// 业务处理
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);

this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
    // 前置请求拦截
    chain.unshift(interceptor.fulfilled, interceptor.rejected);
  });
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
    // 后置响应拦截
    chain.push(interceptor.fulfilled, interceptor.rejected);
  });

  while (chain.length) {
    promise = promise.then(chain.shift(), chain.shift());
  }

  return promise;

This is a kind of code abstraction. So that my code can accommodate more scenes programmers need to think about. Machine code is not to see, is posters, and higher requirements are: The code is not just posters, but also gives people use. We need to take into account the cooperation of people and things, flexible configuration and must be taken into account. Take a virtual front-end for dom. You can fit more platforms.

Of course, abstraction takes time and experience to learn a lot of design.

Note:! Do not premature abstract business code, not even abstract business code. Write more code that does not matter, do not give yourself look for a job to do. In business and try to keep it simple stupid. Unless you are a business expert to confirm the current business less likely to change.

Rights and responsibilities (split and merge)

The responsibilities and obligations essentially equal, more stable and more equal. In recent years, micro-service architecture, middle, front-end micro theory after another, in essence, is to equal rights and responsibilities, the foundation for more service, more business investment in higher output of human and material resources to ensure more stable operation one thing is quite normal. But not before a big pot (single application).

From the code point of view, whether a module to assume things it should not do, or a module is too simple, and inviting complexity.

Of course, the fact that some things can not be done at present is to make everyone feel satisfied, by one point is fat, minus one points is thin, just right is difficult to define. Like Dan Abramov say:

Flux libraries are like glasses: you’ll know when you need them.

Only one thing

Unix philosophy, this is well understood, as I want to do too many things this year, but have nothing to do (or have done, but not good).

On the code point of view, not because of performance reasons a little bit, put a few things together to do it. For example resolve a loop for all the questions, or to write all the code in a function, for example:

Created () { 
  const {a, b, c, d} = this.data
  // ... There are three things need to interact with each other at the same time a, b, c, d
  
  logic after completion //
}

After transformation:

Created () { 
  const the doA Axx = ()
  doB ()
  const = Cxx DOC ()
  logic after completion //
}

// isolated three functions
the doA () {
   const {A, B, C} = this.data
  / / ... there are three things need to interact with each other at the same time a, b, c, d
  
  logic after completion //
}
// other code

Compared to the first one only needs to take a few, once setData, second personality can certainly lower, but the maintainability becomes higher, three things have to be split up, modify the code behind, I can append a doD rather than once again finishing first code logic clearly modify the code again carefully.

Naming and comments

There are only two hard things in Computer Science: cache invalidation and naming things.

Naming and cache invalidation are two problems, this year a lot of talk about caching issues, while naming is indeed a very difficult thing. In one sentence to explain you to do something, to explain a thing of intent by a word.

Do not say in the program in the world, in the real world as well. For example: "actually shocked xxx xxx!" And other news, although after watching will want scolded, but, as this name in order to attract people click to enter, people can not help but cheated again and again. Therefore, before the project was not released, to take a simple and easy to remember name.

But in internal procedures, we do not need to "cheat" other people's hits, but is pragmatic to the point, do not cheat the other fellow, for example, I wrote a simple name, but the result of internal package a lot of business code. And I think this is a function of the written reasons for the shorter, because everyone is difficult to explain the intent of that big lump of code by name. Therefore, the need to write code that can be self-explanatory, and this Best Practices Code is a good name.

For the open-source code, you will often find that these documents will be the beginning of a series of Notes, the comments tell us the intent and purpose of this module. So that you do not need to look at the code can be developed.

For business development, where you can not only through the code clearly explain its meaning, just write a comment. In a number of conditions can not explain your code.

  • Item name

  • Module name

  • File name (class name)

  • Function name (method name)

This is not so that you do not write comments. But I think more comments should be placed in the data structure instead of the code logic. Smart data structures and code than the clumsy work better with the opposite. More often, I look at the data structure is to understand how to run a business, but just can not see the code and the actual imagination.

In fact, over time, made many changes to the code, but the comment did not subsequently modified, this is a big problem. Notes but has become more deceptive.

There are also providing an export default harmful articles. I think the export default export can name a module is a kind of deceptive Code (Over time, the intention of the module will change).

SCENE

Do not look fits-all solutions, so we have to take into account the problem of the scene, we always say that you can modify, readability is the first one (often readable, you can modify the code performance is not bad). But if it is urgent demand performance scene at some things need to be considered.

if the business is the most commonly used treatment, before each use to consider the following, which is more suitable as a host, which is more suitable for determination on the front. If there are arguments on both dimensions, it is a role, one event. Must first determines the role of parameters, and then go to judge the event parameters, and vice versa necessarily bad. Because the former is more in line with people's thinking. In the same dimension as to which earlier put, more must be better use of the parameters on the front, because it is more in line with the implementation process of the machine.

Like if you really are in use or else return. Business logic exclusive use else in most cases, the use of a processing error return. Because this code in line with most people's logical thinking.

But here I would also like to cite examples from the "Code of the United States," the fifth chapter, the author Elliotte Rusty Harold designed an xml validator, which has a period of verification numeric characters:

public static boolean isXMLDigit(char c) {
  if (c >= 0x0030 && c <= 0x0039) return true;
  if (c >= 0x0660 && c <= 0x0669) return true;
  if (c >= 0x06F0 && c <= 0x06F9) return true;
  // ...
  return false
}

After this optimization is as follows:

public static boolean isXMLDigit(char c) {
  if (c < 0x0030) return false; if (c <= 0x0039) return true;
  if (c < 0x0660) return false; if (c <= 0x0669) return true;
  if (c < 0x06F0) return false; if (c <= 0x06F0) return true;
  // ...
  return false
}

Global thinking, good communication

The era of software development is not a man to conquer the world, you have to constantly touch up the borders. The rear end of the previous era of separation, the front end may not know how to optimize the database, backend can not clear the browser's rendering mechanism, but can not understand what the other is doing. Otherwise equal speak the same language, it will be a waste of time. In the development time, put some logic in thinking that the end depends on the security and simplified logic.

Good communication is the ability to give enough context when communicating with others, so that your leader to communicate, to let her know your difficulties. And small partners to communicate and persuade others to advance the way you want, at the same time, good at listening in order to progress.

algorithm

I am not an algorithm of people (leetcode moderate topics are strenuous), but this nothing to say, you take your O (n ** 3) algorithm to play against other people O (n * logn) algorithm is the fee money. So, we know that they are not good enough to work on certain aspects on the line.

Accessibility

TypeScript

Although early exposure and practiced, but in the past are AnyScript. This year also considered heavy use. I did not realize the good of the tool. A good development tool does not allow you to write less code for that little bit, but to give you time to deliver the code to be more confident.

The greatest advantage of TypeScript is to make you think first before writing the code, do first design. As said before. Smart data structures and code than the clumsy work better with the opposite.

TypeScript but also allows the compiler error becomes most runtime, and can reduce the use of defensive programming (but still trust verification). You are not alone in writing code, collaborative priority.

In development, if you come into contact with the complexity of the data structure, and also to ongoing data conversion module, you will constantly encounter: My data? In the end we lost in that step? And even if the code is right, you still afraid, still skeptical. I've passed that, "because I want to write bug are not enough, thorough enough," the age.

Functional thinking

js is functional in origin, the year has been heard functions are first-class citizens, but was completely unable to understand.

Pure functions, data and code that is immutable data is I think these three points is a function of thinking on capacity building codes maximum three points.

I do not want to talk about this expansion, because I have not mastered any one pure functional language. But I must have functional code shadow, and it did make my code more beautiful.

other

Unit testing, code review, security, and so have not mentioned, I also need to learn enough to be output. But here are some information for them to learn and understand:

Google Code Review Guide

SaaS-based start-ups Security 101

Reasoned the code is good

Work is in bad code that someone else left behind a common thing, while facing the actual development needs table, for compatibility, we have to write some not so good code. But the face of doubts of others, we need to give reasons for others to do so, that is, you write down every line of code must have a good reason and basis.

Epilogue

Obviously does not mean simple, it is clear that above all things, but to do take a long time to learn and experience.

So how to write code? That is to look at open source, more books, more learning, more attention to the movements and practice of the industry. Continuous learning, evolving code is good code.

Recently, some small partners (in no SUNYOUNG) asked why is it called my name jump_jump. I was to make myself and see my little friends keep in mind exercise more, retired and sit when multi-hop hop. Good for the body.

Guess you like

Origin www.cnblogs.com/colorchild/p/12132327.html