language agnostic - Favorite (Clever) Defensive Programming Best Practices -


If you had to select your favorite (clever) techniques for defensive coding, then What will happen Although my current languages ​​are Java and Objective (with C ++ in the background), feel free to answer in any language. Emphasis will be placed here clever except for those protective techniques which 70% already know us here. So now it is time that you can dig deeper into your baggage.

In other words, try to think about it other than the Nostalgic example:

  • if (5 == instead of if (x == 5) : to avoid unexpected assignment

here something < Strong> Tangled Some examples of the best defensive programming methods (language-specific examples are in Java) are given:

- Unless you know, lock your variable Make that you change them It is needed

That is, you can declare all variable final unless you know that you have it At that point, you can remove the final at that point. A commonly unknown fact is that this method is also valid for the parameter:

  public void foo  

- If something bad happens, leave behind the proof of the evidence

There are many things that you can make exceptions I: Obviously, logging it and doing some cleaning should be something but you can also leave the proof mark (for example, setting a variable like sensitive values ​​like "impossible to load file" or 99 999) would be useful in the debugger, if Exception hold you block).

- When it comes to continuity: Satan is in the description

Be consistent with other libraries that you are using. For example, in Java, if you are creating a method that removes many types of values, then the following bound inclusive and the upper bound unique Code> String.substring (start, end) which will run in the same way. You will find all these types of methods in Sun JDK to behave in a way that is because it creates various functions including reconstruction of many reserves, where the index is from zero ( inclusive ) to length Of ( exclusive )

So what are your favorite protective behaviors?

Update: If you do not already have it, you have to get free for free. I am offering more responses to the official answer before coming to the selection.

In C ++, I once used to redefine the new one , So that some extra memory was provided to catch fence-post errors.

Currently, I like to avoid defensive programming in the side. If you catch errors quickly and externally, then you do not have to mess with your code defensive maneuvers, your code And you wind-bridge with fewer errors which you have to defend.

:

Avoid protective programming, instead of failing fast

By defensive programming, I have a habit of written code that attempts to compensate for some failure in the data, written code assumes that callers can provide data And sub-routine does not correspond to the contract and this sub-routine should be handled in any way.


Comments