How to reasonably create bugs in iOS development and develop bugs in ios

Source: Internet
Author: User

How to reasonably create bugs in iOS development and develop bugs in ios

What is a BUG? Simply put, the program does not run as expected. I prefer to divide bugs into two categories:

  1. Crash

  2. No Crash

In normal programming practices, it is possible that bugs and Crash are basically equivalent. We also focus a lot on solving Crash bugs. There seems to be no excessive attention to bugs without Crash. However, in actual situations, the tough "pitfalls" are often caused by bugs that do not have Crash, such as OpenSSL heartbleed some time ago. Why? Let me hear about it.

How to reasonably create bugs

The Crash BUG proves that your program has a problem with death. You must take the time to solve the problem. There is no Crash Bug, like a lie-good person, disguised as a normal running, so that the entire program runs in an unstable state. Although the appearance looks good (no crash), it is too bad for me. Once the problem is reported, it is often fatal, such as the heartbleed of OpenSSL. This is what the predecessors summarized as "Dead programs do not lie ".

Crash is not terrible. What is terrible is that the program runs in an unstable state without Crash. If the program still operates the data, the harm will be disastrous.

So rest assured that the program will be Crash, because when it is Crash, you still have the opportunity to correct your own mistakes. If there is no Crash, it is possible that the whole program and the product will be removed. Therefore, one of the principles of making "bugs" rationally is also the biggest principle: To Create Crash bugs as much as possible and to reduce bugs without Crash, if it is possible to convert a Bug that does not fall into a Crash BUG for easy search.

NSAssert

This should be familiar. His name is "assertion ". Assertion refers to the code used during development that enables the program to perform self-check during runtime (usually a sub-program or macro ). If the assertions are true, the program runs normally. If the assertions are false, it means that unexpected errors have been found in the Code. Assertions are especially useful for large complex programs or programs with extremely high reliability requirements. When the assertion is false, almost all of the system's processing strategies are to let the program die, that is, Crash. It is easy for you to know that there is a problem with the program.

Assertion is actually a common means of "Defensive Programming. The main idea of Defensive Programming is that subprograms should not be damaged by passing in error data, even the error data generated by other subprograms. This idea is to control the impact of possible errors to a limited scope. Assertions can effectively ensure data correctness and prevent the entire program from running in an unstable state due to dirty data.

For more information about how to use assertions, see Chapter "defense programming" in code Daquan 2. Here is a simple excerpt to summarize the general idea:

  1. Use the error processing code to handle the expected situation, and Use assertions to handle the situation that should never occur.

  2. Avoid placing the code to be executed in assertions

  3. Use assertions to annotate and verify the pre-and post-Conditions

  4. For highly robust code, Use assertions before handling errors

  5. Use assertions for reliable data from internal systems, rather than for externally unreliable data. Use error processing code for externally unreliable data. In IOS programming, we can use NSAssert to process assertions. For example:

12345 - (void)printMyName:(NSString *)myName  {      NSAssert(myName == nil, @"The name cannot be blank! ");      NSLog(@"My name is %@.",myName);  }

To verify the security of myName, you must ensure that it cannot be empty. NSAssert checks the value of its internal expression. If it is false, it continues to execute the program. If it is not false, it causes the program to Crash.

Each thread has its own assertionhanlder (an NSAssertionHanlder instance). When an assertion occurs, it prints the asserted information and the current class name, method name, and other information. Then an NSInternalInconsistencyException is thrown to cause the entire program to Crash. In addition, execute handleFailureInMethod: object: file: lineNumber: description: In the assertion catch of the current thread.

At that time, when the program was released, the assertions could not be brought into the installation package. You don't want the program to Crash off on the user machine. You can set assert in the project settings to enable and disable assert. The assert fails after NS_BLOCK_ASSERTIONS is set in the release version.

Try not to use Try-Catch

It does not mean that the exception handling mechanism like Try-Catch is not good. However, many people mistakenly use Try-Catch in programming and use the Exception Handling Mechanism in the core logic. Use it as a variant of GOTO. Write a lot of logic in Catch. I am weak enough to say why I don't need ifelse in this situation.

In reality, exception handling only occurs in the user's processing software. A common situation is that the subroutine throws an error, so that the upper-layer caller can know that the subroutine has encountered an error and the caller can use an appropriate policy to handle the exception. In general, the exception handling policy is Crash, killing the program and printing the stack information.

In IOS programming, errors are often thrown in a more direct way. If the upper layer needs to know the error information, half of it will pass in a NSError pointer:

123456789 - (void) doSomething:(NSError* __autoreleasing*)error{    ...    if(error != NULL)    {        *error = [NSError new];    }    ....}

There are very few scenarios that can be left for exception handling, so Try not to use Try-Catch in IOS programming.

(PS: I have seen the use of Try-Catch to prevent program Crash design. If not mandatory, Try not to use this policy)

Try to eliminate the Crash BUG and make it Crash

The above mainly describes how to know the "BUG" of Crash ". Another reason for making a "BUG" is to try to remove the "BUG" that does not have a Crash. There is no reliable method. Let's rely on violence. For example, write some arrays that are out of bounds. For example, if you want to find the hard-to-tune multi-thread BUG, you can find a way to make it more convenient.

In short, it is to let the program "die" mentality to program, born to death.

How to find bugs

In fact, finding bugs is a bit unreliable. Because you never need to find a BUG, he will be there and will only increase or decrease. It's all about bugs. You rarely take the initiative to find bugs. The program is dead, and we have to work overtime. In fact, we are looking for the cause of the BUG. Find the cause of the BUG. The more theoretical point is: find out the causes that are causal with bugs in a bunch of possible causes (note that they are causal, not correlated ).

The BUG can be solved in two steps:

  1. Rationality hypothesis: Find a series of reasons with the highest possibility.

  2. Analyze the cause and effect between the cause and BUG found above. It must be determined that this BUG is caused by a specific cause and is only caused by a change. That is, determining the specific cause is a sufficient and necessary condition for a BUG. After finding the cause, the rest is relatively simple, and the code is replaced.

Rationality hypothesis

In fact, the cause of a BUG can be divided into two categories:

  1. Problems with our own programs.

  2. System environment, including OS, database, framework, and other issues. The former is found, and we can change it. The latter is powerless, either complaining or email the developer. It is not clear whether the developer can be changed. For example, when the IOS framework is created, category will report an exception that cannot be found.

Of course, 99.999999% of the causes of program problems are caused by ourselves. Therefore, the rationality is assumed as follows:

First, I doubt myself and my programs, and secondly I doubt everything.

The program is actually a developer's own problem. After all, bugs are the child and child of programmers. We have made bugs. There are roughly three reasons for developers to create bugs:

Insufficient knowledge reserves. For example, the common NULL pointer problems in IOS are often caused by unfamiliar IOS memory management models.

A typical mistake is array out-of-bounds errors. Also, do not pay attention to the type conversion. For example, the following program:

123456 //array.count = 9for (int i = 100; array.count - (unsigned int)i > 10 ; ){    i++    .....}

In principle, this should be a program that can be normally executed, but if you run it, it is an endless loop. The endless loop problem may not be solved after you have changed it for many days. Until colleagues tell you that array. count returns NSUInterge. When there is an unsigned integer, if a negative value exceeded the border. You just suddenly realized: depending on, type issues.

Logical error

This is the problem of the way of thinking, but it is also the most serious problem. Once this happens, it is difficult to find. People are always hard to doubt their way of thinking. For example, the issue of endless loops is the loop reference between functions and the issue of multithreading. Fortunately, the vast majority of bugs are caused by insufficient knowledge reserves and carelessness. So the second assumption of Rationality:

First, I doubt the underlying causes, such as my knowledge reserve and carelessness, and look for specific problems through these reasons. Then you can doubt the hard-to-handle logic errors. There are some basic strategies with the above rational doubts, and there is no need for some basic materials. It is a common Crash cause. Finally, we have to implement these specific causes or code, but find the causal relationship with the BUG.

  1. Access a released object, such as NSObject * aObj = [[NSObject alloc] init]; [aObj release]; NSLog (@ "% @", aObj );

  2. Access the array class object or insert an empty object

  3. The method does not exist.

  4. Byte alignment (incorrect type conversion)

  5. Stack Overflow

  6. Multi-thread concurrent operations

  7. Repeating nstating

Rational hypothesis Article 3: Try to find the specific reason for the possibility.

Causal Analysis

First, it must be noted that we are looking for "causal" rather than "Relevance". These are two very confusing concepts. In addition, we often mistakenly regard relevance as a result. For example, when we solve a multi-thread problem, we found a data chaos problem, but we were puzzled. Finally, one day you accidentally added a lock to an object, and the data would be normal. Then you can say that this problem is caused by the fact that this object has no shackles.

However, based on your analysis above, you can only find that the object's shackles are related to data exceptions, but not the cause of Data exceptions. Because you failed to prove that object locking is a sufficient and necessary condition for data exceptions, instead, you just used a single dependent variable experiment. The variable is in a cool state, with the value x = [] and x being an integer. Then, the experiment result shows whether the shackles are positively correlated with data exceptions.

Correlation: in probability theory and statistics, Correlation (Correlation, or Correlation coefficient) shows the intensity and direction of the linear relationship between two random variables. In statistics, the correlation is used to measure the distance between two variables and each other. In this broad definition, many data-related coefficients are defined based on data characteristics.

Causal: a causal relationship is the relationship between an event (that is, the cause) and the second event (that is, the result). The last event is considered as the result of the previous event. The correlation is equivalent to the result. Not only programmers, but almost all common logical errors. To deepen understanding, let's take a look at this small science: Correlation = causal.

The primary problem of causal analysis is that you should not be fooled by your own logical errors to correctly distinguish between relevance and causal. Do not equate correlation with causation.

Afterwards, it is the result analysis content. Previously, it has been repeatedly said that the objective of the result analysis is to determine the specific cause as a sufficient and necessary condition for the occurrence of a BUG. To determine this, we need two steps:

  1. Proof of adequacy

  2. Proof of necessity

For adequacy proof, this is basically a normal logical reasoning. The basic idea is to restore the path where a BUG occurs, the code from the cause to the BUG occurrence, and the function call and control logic. By confirming this, we can prove the adequacy. Generally, the Crash stack information can directly prove the adequacy.

It is difficult to prove the necessity. The adequacy and necessity are defined as follows: when the proposition "if A is B" is true, A is A sufficient condition of B, and B is A necessary condition of. The necessity is that the BUG can be used as the cause of the BUG. This statement is relatively difficult. In other words, you must confirm that this BUG can be used to explain the cause. This BUG is only caused by this.

Only by proving the necessity can we find the cause of the BUG.

Q: one-click call to programmer Q & A artifacts, one-to-one service, developer programming required official website: www.wenaaa.com

QQ Group 290551701 has gathered many Internet elites, Technical Directors, architects, and project managers! Open-source technology research, welcome to the industry, Daniel and beginners interested in IT industry personnel!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.