Reading experience 1 How to avoid dirty code

conclusion first

1. Eliminate repetition
2. Create a more expressive name
3. Lighten the burden on objects and methods, and each perform its duties and only do one thing
4. Try to protect the fields and methods in the class from being accessed by the outside world to force yourself improve quality

my experience and thinking

    1. When a piece of code appears twice or more in your project, maybe we should be vigilant. The most direct way is to extract it and write a method. In the past, I often didn’t care about it. I It is believed that writing a method will bring additional overhead, because when the program calls a method, it needs to save the current state of the program, which is often referred to as the save scene. Here is mainly the local variable value of the current function, and the bottom layer is saved in Inside the register; after saving the scene, it is necessary to prepare the parameters required by the function and execute the jump instruction, which is much more expensive than executing sequentially from top to bottom. When the execution is completed, the program internally fetches the address of the previous instruction and returns, and restores the scene to continue the following statement. But as the scale of the project expands, I find that such a small province will bring more trouble: when you work with a team, others can't find the method needed to achieve this function, and finally have no choice but to write one by yourself , which in turn leads to code duplication. What's even more frightening is that if you plan to modify the requirements and the code you wrote needs to be modified, then you have to search for the duplicate code you wrote in thousands of lines of code and modify them one by one. Once you miss a place and forget to change it, it may bring tens of minutes or even hours of Debug time to your subsequent work. This is the problem I encountered writing repetitive code.

Experience : Modularize functions , try not to write the same function in different places, make method calls unified, and reduce subsequent modification costs .

    2. Many books are usually named randomly for typesetting or to reduce beginners’ fear of English or for some other reasons that I can’t think of. Of course, a,b,c,dtheir editors may have their own thinking. I also have this habit. When I wrote the code myself, I also had a naming frenzy. I always couldn’t think of a suitable name, and then I thought, no one will read it anyway, so it doesn’t matter. But when I was sorting out the projects on the computer recently, I suddenly found that the code I wrote before didn't know what it meant. It was probably written by my sophomore. It took me 3 minutes to read it repeatedly to understand what it was doing. It was a moment of pleasure when I wrote it, and the crematorium after I wrote it is indeed like this. This hazard is magnified a lot when you're working with a team, just imagine being handed a few thousand lines of unformatted code and being asked to refactor it. I have always paid attention to this in the company, because I am worried that when others refactor the code or read the code to add new requirements, they will be confused.

Experience : try to understand the meaning as much as possible, and then comment appropriately to reduce the reading cost of others and yourself ( don't think that you will be able to understand the code you write now in a few months!!! )

    3. I believe that many people who have a deep understanding of C linguistics will have such a problem. I was a mathematics major before, and then I taught myself C language, and I had a deeper understanding of C at that time. C is indeed great, but the process-oriented nature of C is also particularly easy for interdisciplinary students like us who don't know much about other computer disciplines to fall into the abyss of low-quality code. For a long time and even now, the code I write has a strong process-oriented flavor. I am used to adding functions one by one from the front to the back. I am used to writing many things in a class without object-oriented thinking. This habit also caused me a lot of trouble. In my previous solo development process, I implemented most of the functions of our project in one class, and then I went to work in the company, and I handed over the project to another friend of our team, who read my code It is very difficult, because although the functions are available, it is not logical. In a class, there are movement and rotation of the camera, interaction methods, creation and preservation... He couldn't figure out how to realize those functions at all. In the end, we explained each method in the video, and then refactored the code. This is also the most painful lesson I have learned so far. Since then, I have reminded myself that a class puts related things, and a method implements a function. This is not only a specification, but also makes the logic of the project clearer and enhances the reusability of the code.

Experience : A class only does what it should do, and a method is only responsible for a single function.

    4. The fourth one is what I saw not long ago, and it really makes sense. When I was developing, I used to set almost all methods to public so that I could use them elsewhere. This means: I have opened up most of the functions, and others can easily get the data from my class. It is too easy to cherish. To give a simple example, if we are developing a gunfight game, we need to deduct the blood when we shoot and hit the enemy. If we open the method of modifying the blood volume to the individual class, we may write it without thinking:

enemyHp = enemyHp - mySelf.weaponDemage;

    Is such a code ok? Anyone who has learned a little code may know that this is not bad, but terrible. This is too easy, and the thinking of writing code is easy to be biased. Let’s take another example, or this gunfight game, we need to judge how many enemies are around at this time and know the distance between them and ourselves. If our individuals can get all the individual lists, we may write like this:

float minDistance = mySelf.ViewDistance;
float tempDistance = 0.0f;
Agent target = null;
List<Agent> agentList = GetAllAgent();
foreach(Agent agent in agentList)
{
    
    
	tempDistance = Vector3.Distance(transform.position,agent.transform.position);//得到自己和对方的距离
	if(tempDistance < minDistance)
	{
    
    
		minDistance = tempDistance;
		target = agent;
	}
}
if(target != null && minDistance <= mySelf.attackDistance)
{
    
    
	mySelf.Attack(target);
}

    It seems that there should be no big problem here. Let's not focus on whether the logic is reasonable (an example of my random thinking), and look at the performance. Assuming there are n surviving individuals, each individual has to traverse all the individuals in his refresh cycle to calculate the distance and judge whether it is within his field of vision, A calculates himself and B, and C, and D, and B calculates himself With A, with C, with D...and we have obtained the authority of the individual and closed it to the individual, how would you write it? Let me write, I should use a singleton manager to do it, let it calculate the distance, so that in a refresh cycle, the number of times to calculate the distance can be reduced by half, it can be seen that we only need to calculate half of the distance matrix That's it.

Experience : Of course, different people may have different views on this point. I agree with this passage and look back to write it. And when I went to practice, I also found that it is true that you should close your internal methods and don't let others access easily, hide your data and don't let others modify it easily , otherwise one day there is a problem with the value on your side. Check the references, Mommy, how come there are hundreds of references, read or print one by one, Debug to find out the problem!

If you are interested, welcome to pay attention to my WeChat public account, let's discuss together!

insert image description here

Guess you like

Origin blog.csdn.net/l1606468155/article/details/104890174