206

Your project is big enough already. In my experience, one class and one function have been sufficient to consider the need for unit testing. class Simple { boolean reallySimple() { return true; // how do we make sure it doesn't change to false? } } class SimpleTest { void assertReallySimple() { //...


109

I've never bought into the "you must unit test everything" idea, though there are certainly folks out there who have (see gnat's answer!). As far as I'm concerned, the main benefits of unit testing are: Helping ensure changes don't break things. Helping you design sensible interfaces to your classes (since it forces you to be a client to your own code). ...


107

The question is not so much whether you should check for null or let the runtime throw an exception; it is how you should respond to such an unexpected situation. Your options, then, are: Throw a generic exception (NullReferenceException) and let it bubble up; if you don't do the null check yourself, this is what happens automatically. Throw a custom ...


101

0 is false because they’re both zero elements in common semirings. Even though they are distinct data types, it makes intuitive sense to convert between them because they belong to isomorphic algebraic structures. 0 is the identity for addition and zero for multiplication. This is true for integers and rationals, but not IEEE-754 floating-point numbers: 0.0 ...


98

I would strongly advise against #1, because just ignoring errors is a dangerous anti-pattern. It can lead to hard-to-analyze bugs. Setting the result of a division by zero to 0 makes no sense whatsoever, and continuing program execution with a nonsensical value is going to cause trouble. Especially when the program is running unattended. When the program ...


96

I think a 404 response is the best semantic match here, because the resource you were trying to find (as represented by the URI used for the query) was not found. Returning an error payload in the body is reasonable, but not required. According to RFC 2616, the definition of the 404 status code is: 10.4.5 404 Not Found The server has not found anything ...


91

What if your code was: try { MethodThatMightThrow(); var firstVariable = 1; } catch {} try { var secondVariable = firstVariable; } catch {} Now you'd be trying to use an undeclared variable (firstVariable) if your method call throws. Note: The above example specifically answers the original question, which states "consistency-sake aside". This ...


88

Exceptions were invented to help make error handling easier with less code clutter. You should use them in cases when they make error handling easier with less code clutter. This "exceptions only for exceptional circumstances" business stems from a time when exception handling was deemed an unacceptable performance hit. That's no longer the case in the ...


74

Because the math works. FALSE OR TRUE is TRUE, because 0 | 1 is 1. ... insert many other examples here. Traditionally, C programs have conditions like if (someFunctionReturningANumber()) rather than if (someFunctionReturningANumber() != 0) because the concept of zero being equivalent to false is well-understood.


74

The CPU has built in detection. Most instruction set architectures specify that the CPU will trap to an exception handler for integer divide by zero (I don't think it cares if the dividend is zero). It is possible that the check for a zero divisor happens in parallel in hardware along with the attempt to do the division, however, the detection of the ...


73

I tend to build an application log, either in DB or in file, and log all such information to that. You can then give the user an error number, which identifies which log item the error is related to, so you can get it back. This pattern is also useful as you can follow errors even if the users don't bother raising them with you, so you can get a better idea ...


72

When should an exception be thrown? When it comes to code, I think that following explanation is very helpful: An exception is when a member fails to complete the task it is supposed to perform as indicated by its name. (Jeffry Richter, CLR via C#) Why is it helpful? It suggests that it depends on the context when something should be handled as an ...


69

There is a difference between error codes and error return values. An error code is for the user and help desk. An error return value is a coding technique to indicate that your code has encountered an error. One can implement error codes using error return values, but I would advice against that. Exceptions are the modern way to report errors, and there is ...


66

One should avoid throw errors as the way to pass error conditions around in applications. The throw statement should only be used "For this should never happen, crash and burn. Do not recover elegantly in any way" try catch however is used in situation where host objects or ECMAScript may throw errors. Example: var json try { json = JSON.parse(input) ...


64

I know that this has been well answered by Ben, but I wanted to address the consistency POV that was conveniently pushed aside. Assuming that try/catch blocks didn't affect scope, then you would end up with: { // new scope here } try { // Not new scope } And to me this crashes head on into the Principle of least astonishment (POLA) because you now ...


63

In my mind, the biggest argument is the difference in what happens when the programmer makes an error. Forgetting to handle an error is a very common and easy mistake to make. If you return error codes, it is possible to silently ignore an error. For example, if malloc fails, it returns NULL and sets the global errno. So correct code should do void* ...


62

It's not so much "fake" performance as real responsiveness. There are a number of reasons why it's popular: Internet connections are fairly reliable nowadays. The risk of an AJAX request failing is very low. The operations being performed are not really safety critical. If your emails don't get deleted on the server, the worst that happens is you have to ...


58

IMHO trying to handle null values that you don't expect leads to overly complicated code. If you don't expect null, make it clear by throwing ArgumentNullException. I get really frustrated when people check if the value is null and then try to write some code that doesn't make any sense. The same applies to using SingleOrDefault (or even worse getting ...


58

These are two different questions. Should you accept null? That depends on your general policy about null in the code base. In my opinion, banning null everywhere except where explicitly documented is a very good practice, but it's even better practice to stick to the convention your code base already has. Should you accept the empty collection? In my ...


57

While Steven's answer provides a good explanation, there is another point which I find is rather important. Sometimes when you check an error code, you cannot handle the failure case immediately. You have to propagate the error explicitly through the call stack. When you refactor a big function, you may have to add all the error-checking boilerplate code to ...


56

I don't think that your examples are really equivalent. There are three distinct groups, each with it's own rationale for its behaviour. Magic value is a good option when there is an "until" condition such as StreamReader.Read or when there is a simple to use value that will never be a valid answer (-1 for IndexOf). Throw exception when the semantics of the ...


52

Imagine code with thousands files using a bunch of libraries. Imagine all of them are coded like this. Imagine, for example, an update of your server causes one configuration file disappear; and now all you have is a stack trace is a null pointer exception when you try using that class: how would you resolve that? It could take hours, where at least just ...


39

As others have said, the math came first. This is why 0 is false and 1 is true. Which math are we talking about? Boolean algebras which date from the mid 1800s, long before digital computers came along. You could also say that the convention came out of propositional logic, which even older than boolean algebras. This is the formalization of a lot of the ...


36

The habit of checking for null to my experience comes from former C or C++ developers, in those languages you have a good chance of hiding a severe error when not checking for NULL. As you know, in Java or C# things are different, using a null ref without checking for null will cause an exception, thus the error will not be secretly hidden as long as you don'...


35

Interesting question. Basically, we can reduce this down to the right way to classify things in terms analogous to OSI layers. HTTP is commonly defined as an Application Level protocol, and HTTP is indeed a generic Client/Server protocol. However, in practice, the server is almost always a relaying device, and the client is a web browser, responsible for ...


34

It's simple: you don't need unit testing if you will discard the program after running it once. If this seems excessive to you, consider what the alternative would mean. If there were some size below which unit testing doesn't pay, you would have to keep judging in your mind: "Have I reached the magic size yet? Should I start writing tests?" Now, ...


34

what to show to the user. Should this also be hidden from the user? You show the user what is actionable for them. For example, if you have an error which is caused because of some null pointer exception and more of a bug than user error you don't want full explanation because they can't do anything different. Or should we show this anyway? Or should ...


34

It depends on the language, on the compiler, on whether you are using integers or floating point numbers, and so on. For floating point number, most implementations use the IEEE 754 standard, where division by 0 is well defined. 0 / 0 gives a well defined result of NaN (not-a-number), and x / 0 for x ≠ 0 gives either +Infinity or -Infinity, depending on ...


34

I will use your examples. http://example.com/restapi/deviceinfo?id=123 If the endpoint returns a json array, the best choice for is 200 OK with a empty array if no result were found. If the endpoint is designed to return a single result, my choice would be 404 NOT FOUND, because, for me, the right syntax for this kind of endpoint is: http://example.com/...


Only top voted, non community-wiki answers of a minimum length are eligible