Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Hot answers tagged

174

I find the code hard to read with the goto statements. I would recommend structuring your enum differently. For example, if your enum was a bitfield where each bit represented one of the choices, it could look like this: [Flags] public enum ExampleEnum { One = 0b0001, Two = 0b0010, Three = 0b0100 }; The Flags attribute tells the compiler that ...


166

The problem with your basic example isn't the null check, it's the silent fail. Null pointer/reference errors, more often than not, are programmer errors. Programmer errors are often best dealt with by failing immediately and loudly. You have three general ways to deal with the problem in this situation: Don't bother checking, and just let the runtime ...


154

I have a bag with five potatoes in it. Are there .Any() potatoes in the bag? "Yes," you say. <= true I take all of the potatoes out and eat them. Are there .Any() potatoes in the bag? "No," you say. <= false I completely incinerate the bag in a fire. Are there .Any() potatoes in the bag now? "There is no bag." <= ArgumentNullException


135

IMO the root of the problem is that this piece of code shouldn't even exist. You apparently have three independent conditions, and three independent actions to take if those conditions are true. So why is all that being funnelled into one piece of code that needs three Boolean flags to tell it what to do (whether or not you obfuscate them into an enum) and ...


112

What Color Is Your Function? You may be interested in Bob Nystrom's What Color Is Your Function1. In this article, he describes a fictional language where: Each function has a color: blue or red. A red function may call either blue or red functions, no issue. A blue function may only call blue functions. While fictitious, this happens quite regularly in ...


109

Checking for uniqueness and then setting is an antipattern; it can always happen that the ID is inserted concurrently between checking time and writing time. Databases are equipped to deal with this problem through mechanisms like constraints and transactions; most programming languages aren't. Therefore, if you value data consistency, leave it to the expert ...


83

You are right there is a contradiction here, but it is not the "best practices" being bad. It is because asynchronous function does essentially different thing than a synchronous one. Instead of waiting for the result from its dependencies (usually some IO) it creates a task to be handled by the main event loop. This is not a difference which can be well ...


78

This is not brittle in the usual sense. A unit test is considered brittle if it breaks due to implementation changes which does not affect the behavior under test. But if the business logic itself changes, then a test of this logic is supposed to break. That said, if the business logic indeed changes often, perhaps it is not appropriate to hardcode the ...


75

The problem with this approach is that while exceptions never get thrown (and thus, the application never crashes due to uncaught exceptions), the results returned are not necessarily correct, and the user may never know that there is a problem with the data (or what that problem is and how to correct it). In order for the results to be correct and ...


68

Sure there is a good reason to name it more explicitly. It's not primarily be the method definition that should be self-explanatory, but the method use. And while findById(string id) and find(string id) are both self-explanatory, there is a huge difference between findById("BOB") and find("BOB"). In the former case you know that the random literal is, in ...


55

Since _someEntity can be modified at any stage, then it makes sense to test it every time that SetName is called. After all, it could have changed since the last time that method was called. But be aware that the code in SetName isn't thread-safe, so you can perform that check in one thread, have _someEntity set to null by another and then the code will barf ...


52

First off, it appears that that source code will throw ArgumentNullException, not NullReferenceException. Having said that, in many cases you already know that your collection is not null, because this code is only called from code that knows that the collection already exists, so you won't have to put the null check in there very often. But if you don't ...


47

Is this a good way of handling exceptions? No, I think this is pretty bad practice.  Throwing an exception vs. returning a value is a fundamental change in the API, changing the method's signature, and making the method behave quite differently from an interface perspective. In general, when we design classes and their APIs, we should consider that ...


40

No, this is perfectly fine. It merely means that the API is over-engineered with regards to your current application. But that doesn't prove that there will never a use case in which the data source and the measurer are different. The point of an API is to offer the application programmer possibilities, not all of which will be used. You should not ...


37

I think what you call “fail fast” and what I call it is not the same. Telling the database to make a change and handling the failure, that is fast. Your way is complicated, slow and not particularly reliable. That technique of yours is not fail fast, it is “preflighting”. There are sometimes good reasons, but not when you use a database.


37

They have worked on critical applications dealing with aviation where the system could not go down. As a result ... That is an interesting introduction, which gives me the impression the motivation behind this design is to avoid throwing exceptions in some contexts "because the system could go down" then. But if the system "can go down because of an ...


36

There are reasons to prefer FindById (versus a compelling one in favor of Find: Brevity). Future-proofing: If you start with Find(int), and later have to add other methods (FindByName(string), FindByLegacyId(int), FindByCustomerId(int), FindByOrderId(int), etc), people like me tend to spend ages until they finally find the Find(int) method because they are ...


34

In C# and Java implementations, the objects typically have a single pointer to its class. This is possible because they are single-inheritance languages. The class structure then contains the vtable for the single-inheritance hierarchy. But calling interface methods has all the problems of multiple inheritance as well. This is typically solved by putting ...


31

There is absolutely nothing wrong with passing an entire User object as a parameter. In fact, it might help clarify your code, and make it more obvious to programmers what a method takes if the method signature requires a User. Passing simple data types is nice, until they mean something other than what they are. Consider this example: public class Foo { ...


31

Yes, because C# doesn't allow multiple inheritance except with interfaces. So if I have a class which is both a TypeNameMapper and SomethingelseMapper I can do: class MultiFunctionalClass : ITypeNameMapper, ISomethingelseMapper { private TypeNameMapper map1 private SomethingelseMapper map2 public string Map(TypeDefinition typeDefinition) { ...


30

Use a database with support for GIS (geographic information systems) queries. Most databases support this outright or have extensions, but the details will be database-specific (in their answer, Flater shows the syntax for SQL server). If you need to implement such queries within your application, you can implement a data structure that allows spatial ...


27

The best answer is use polymorphism. Another answer, which, IMO, makes the if stuff clearer and arguably shorter: if (One || OneAndTwo || OneAndThree) CallOne(); if (Two || OneAndTwo || TwoAndThree) CallTwo(); if (Three || OneAndThree || TwoAndThree) CallThree(); goto is probably my 58th choice here...


27

Never use gotos is one of the "lies to children" concepts of computer science. It's the right advice 99% of the time, and the times it isn't are so rare and specialized that it's far better for everyone if it's just explained to new coders as "don't use them". So when should they be used? There are a few scenarios, but the basic one you seem to be hitting ...


23

But should the method not have this check? This is your choice. By creating a public method, you are offering the public the opportunity to call it. This always comes along with an implicit contract on how to call that method and what to expect when doing so. This contract may (or may not) include "yeah, uhhm, if you pass null as a parameter value, it will ...


22

Null means missing information, not no elements. You might consider more broadly avoiding null — for example, use one of the built-in empty enumerables to represent a collection with no elements instead of null. If you are returning null in some circumstances, you might change that to return the empty collection.  (Otherwise, if you're finding ...


22

int is used for almost all integer variables in .NET although often a smaller type would be enough. Also, unsigned types are almost never used although they could be. Some reasons: Signed and unsigned types as well as integer types of different size can be awkward when combining them (+ or < for example). The rules are not obvious. I'm an experienced ...


18

Do computers still have deviations even if they follow the same float point standard? Unfortunately, yes, especially when you use C# (or another JIT compiled language). The problem which occurs here is that the JIT compilation stage on some processor architectures produces code which uses more CPU registers than on other architectures. This can lead to ...


17

Am I right in thinking this is a violation of the Open/Closed principle? No, it isn't a violation of that principle. That principle is concerned with not changing User in ways that affect other parts of the code that use it. Your changes to User could be such a violation, but it's unrelated. Are any other principles broken by this practice? Dependency ...


16

There are two completely different kinds of software: libraries that need a stable binary interface across multiple versions, and applications or internal software where you can just refactor. For internal software or applications, you are right: you can wait until something is needed, then refactor and recompile your code. So using public fields is jucky ...


16

What is it in functional programming that makes a difference? Functional programming is by principle declarative. You say what your result is instead of how to compute it. Let's take a look at really functional implementation of your snippet. In Haskell it would be: predsum pred numbers = sum (filter pred numbers) Is it clear what the result is? Quite so,...


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