7 ms·
Avoid NULL
- alfiedotwtf 11y agoSomething something Rust.
- mirimir 11y agoMaybe avoid null in C++. I have no clue. But null is a useful concept in SQL.
- TrisMcC 11y agoAvoid NULLs in SQL schemas. Embrace NULLs in outer joins.
- wvenable 11y agoIt's impractical in real life to avoid NULLs in SQL schema. Just embrace NULLs altogether; they aren't hard to understand or work with.
- Retra 11y agoThey are hard to understand. You don't know if they represent missing data, invalid data, or valid data that is null-valued, so you never know how to handle it.
- mirimir 11y agoThey're easy to handle. For any column with nulls, you just need to deal with them explicitly.
- Retra 11y agoAnd that's your standard for "easy to handle?"
- mirimir 11y agoYes. What's wrong with that? Let's say that I have a bunch of contact information, from multiple sources, to synthesize. Sources include guest lists, registration forms, notes from agents, and other hand written information. Some of the information is illegible, pages are ripped and damaged, etc. So let's consider email addresses. In some of our sources, there's no place to enter them, but we know that most people have at least one. The appropriate value for those email addresses is "NULL". That's also appropriate for email addresses in other sources that are illegible. Conversely, in reliable sources, missing email address means either that there is none, or that it shouldn't be used. In those cases, it would be appropriate to leave the column empty, or use "NONE", or even "nobody@dev.null". That's how I learned to handle "NULL", anyway.
- Retra 11y agoWhat's wrong with it is that it's cherry-picking. "Easy to handle" means you don't have to manually interpret the values every time you deal with them. That's the default! That's the hardest a thing gets to handle... You're talking about an innately fragile process. This algorithm is not general, and it's not generalizable, and thus it represents an upper limit on the effectiveness of our ability to write good software. You've got a method for solving multiple problems here; you gave me one example. Now give me an implementation of that algorithm, and you'll find it doesn't bother to employ nulls at all. You're just mapping other concepts onto null because that's how you imagine a database to work. You're familiar with a hammer, so you're employing nails all the time. >Conversely, in reliable sources, missing email address means either that there is none, or that it shouldn't be used. In those cases, it would be appropriate to leave the column empty, or use "NONE", or even "nobody@dev.null". A properly normalized database would put emails in another table and reference them using a key. You'll have no empty columns. You'll know there is no email because there is no value, not because there's a NULL value. If you want to send emails, you do a join on these two tables and get a list of people who have emails. This is the proper way to model such a domain. In the mean time, you'll just have a fragile model. Then you'll use that fragile model to make fragile decisions, and your database will be completely useless in 40 years. (Granted, your DB implementation might combine these tables as an optimization, but then the optimizer has a clean notion of what NULL means across your entire schema, and you shouldn't be exposed to it at all.)
- wvenable 11y agoThat doesn't make them hard to understand. Every column requires some context to understand adding NULLs changes very little.
- Retra 11y agoThe context of a column can't tell you why a given row is null. For instance, if you're looking at a middle_name field in a database and you see NULL, you have no idea what that means. It doesn't model the thing the scheme was meant to model, it only models the system's ignorance about the world.
- wvenable 11y agoIf I also have column that is called "Active" that is True or False what does that mean? I have to look somewhere else for that information. You seem to want to ascribe more pain to nulls than makes sense relative to other values. NULL means I couldn't store a valid value in that column. Why? Well that depends on the system, just like the contents of every other column.
- Retra 11y agoWhat it means is that you have an awfully named column. >NULL means I couldn't store a value in that column. Why? Well that depends on the system, just like the contents of every other column. No, it means you stored a NULL value in that column. Why you did that rather than throwing an error or generating a more informative value is a mystery. And it is not made clearer by changing the name of your column. And someone writing code to handle that data can't know how to handle it, because they have no clue what went wrong, or even if it is wrong.
- wvenable 11y ago> Why you did that rather than throwing an error or generating a more informative value is a mystery. Why would you think it's automatically an error or that a more informative value could exist? I might have a form with yes/no or date answers and if a question isn't required and the user doesn't provide an answer then it's stored as NULL. Either way the meaning is obvious, it's read and written perfectly fine, and it's not an error. I don't understand the implication that storing NULL means something went wrong? That's not at all what it means to me. I'm going to assume something about your response: you seem to conflating the concept of stored null value in database vs. returning a null reference or pointer in C.
- dragonwriter 11y agoIt's not impractical; it is occasionally undesirable for performance or otger reasons to normalize to a level that would avoid all nulls in base tables, but more often than not nulls are permitted because of poor data modeling. Nullable columns are not always wrong, but they are a design smell.
- deleted 11y ago[deleted]
- Pxtl 11y agoWell, it would be if testing x = y produced sane results where one of those is null. I understand why SQL chooses to treat null as unknown for comparison, but I hate it with every fibre of my being and wish SQL dialects would join the 21st century and let me define alternate concepts of nullity like we can with modern type systems.
- letstryagain 11y agoIdeally you'd want your RDBMS to refuse to compile tests like x = y in cases where either x or y could be null. You would have to explicitly handle nulls in boolean statements.
- dllthomas 11y agoI've been working on a linter for SQL - that's probably not a bad rule to toss in the mix...
- Pxtl 11y agoThat would be sensible if SQL dialects usually offered a sane comparison that returns true/false reasonably for null comparisons. Since they don't, and = is the only available equality test, I'm going to stick to my original point that null comparison in SQL is dumb and wrong for 99% of use-cases and compiler warnings would be solving the wrong problem.
- dllthomas 11y agoMySql, Postgres, and Vertica, at least, all support <=> as an operator that treats NULL as an ordinary, distinct value.
- yahelc 11y agoUseful but dangerous: If you have (1,2,3,4,NULL) as data in column foo, and you query select foo from tbl WHERE foo!=1 Returns: 2 3 4 Which, makes sense, but can be very confusing if you're not explicitly looking out for it. Redshift (and I think Postgres generally) will also, very confusingly if you're not aware of it, return no rows if your subquery returns any NULL values in a NOT IN scenario. If bar is (1,2,3,4,5) SELECT * FROM bar WHERE foo NOT IN (SELECT foo FROM tabl) Will return no results (instead of a single row with 5).
- mirimir 11y agoSELECT * FROM bar WHERE foo IS NOT NULL AND foo NOT IN (SELECT foo FROM tabl)
- dllthomas 11y agoThe fact that you seem to think that changes anything clearly demonstrates that this behavior is confusing.
- mirimir 11y agoOK, so I don't currently have a server to test that on. And I'm a little rusty. But are you saying that my query doesn't resolve the NULL issue? I know that I've done just that with tables containing NULL values. Maybe I screwed up the format.
- dllthomas 11y agoYour adjustment will filter out any nulls that would have otherwise been in the output. The issue was not NULLs in the output (there was nothing in the output), but NULLs in the subquery in the NOT IN clause. You could address this by filtering inside the subquery: SELECT * FROM bar WHERE foo NOT IN (SELECT foo FROM tabl WHERE foo IS NOT NULL) Making this a little more realistic: SELECT * FROM activation_code WHERE code NOT IN ( SELECT activation_code_used FROM user ); If that query was previously returning many rows, I contend that many people would not expect it to start returning zero rows just because a user was created without using an activation code.
- dllthomas 11y agoNull is a broken concept in SQL. It conflates "unknown" with "known to be absent".
- kirkbackus 11y agoIn the last example, wouldn't a Singleton to represent a null student be more effective since you could do a check for the null student by reference?
- deleted 11y ago[deleted]
- purpled_haze 11y agoI'll never understand why people would rather complicate things in an attempt to avoid null checks rather than provide null checks.
- johncolanduoni 11y agoBecause you can forget a null-check, but the type system won't let you forget an option/not_null? It's the same reason we complicate things with type systems in general.
- halayli 11y agoIt's more for consistency. You can still forget to use a not_null.
- johncolanduoni 11y agoNot if you're calling into an API that uses not_null; it will automatically insert the null check.
- halayli 11y agoMy point is that you can easily forget to declare a pointer as not_null and revert back to the old habit of declaring it as int*. The responsibility is still on the programmer.
- jschwartzi 11y agoYes. Malloc is a really good example of this, where malloc returning NULL indicates a fundamental resource is not available. If you dereference the pointer returned by malloc under those conditions, your program crashes, just like if you were to not catch an exception thrown at instantiation-time with a reference type. You should absolutely use NULL to represent the absence of some fundamental resource, like memory or a device. To the extent that a device is memory-mapped, it's the same thing. NULL is just a tool. It's just a way for you to express some property of your API. That said, some of the strategies outlined in the article could be very useful for avoiding use of pointers. Use of a class type implementing an interface as a "null type" is a very good strategy. Such a type could guarantee successful instantiation, and so avoid the need to throw exceptions or otherwise crash entirely. You could architect an application with those strategies and completely avoid the use of NULL and nullptr entirely. But where your program is dependent on a finite resource, you must have a way to represent the absence of that resource. NULL and nullptr are convenient ways to do that without a ton of extra code. So no, don't avoid NULL.
- mikekchar 11y agoEnumerating some techniques for avoiding NULL is useful, but it sidesteps the real issue. It is important that programmers understand that avoiding NULL will not suddenly make your programs robust. Generally speaking there is really only one case that you need to think about: what do you do when a function needs to return a value and it has no value to return. This often happens in error conditions, but it can also happen as a result of poorly designed code (for example the ubiquitous "doUpdate()" function that sometimes returns a result and sometimes doesn't, based on what was passed to it). I will maintain that initialization is a special case of this (I haven't initialized it yet, so I have no value to put in it). However, more important than what you use to represent "I don't have a value" values, is what you do with it if you get one. In several of the examples in this article, a boolean is returned to indicated whether or not you have valid data in the parameters passed by value. This may seem "safe" because you don't crash, but there are often much more serious problems than crashing: data corruption, for example. Let's consider the case where I gather some data from somewhere and write it to my database. In the case that my data collection failed, I certainly don't want to write random data that was returned in the parameter. What happens if the calling code neglects to check the boolean return value? This check is identical (and could literally be identical) to checking for NULL. The only difference is that if I try to an uninitialized, but valid data structure to my database, it will work. If I try to dereference NULL, it will crash. In many cases, crashing is preferred. Even when you return a NULL Object, you still need to think very hard about what you want to do with it. What happens if someone tries to write a NULL Object to the database? We know things are very, very wrong. We could just skip it, but many times it would be prudent to halt execution of the program. Too often I deal with programmers who blindly accept the advice that NULL is evil without actually understanding the problem that NULL is intended to solve. I have no problem with avoiding NULL (and in many cases it is a very good idea). It is important, though, to understand that you still have a lot to do to write robust code.
- tatterdemalion 11y agoThe problem with null is that its not a type error to use it as if it were a non-null value. What you want is for any code that could operate on invalid data as if it were valid data to be a compile time error.
- halayli 11y agoCompilers can give us a warm feeling when they help us enforce invariants at compile time, but those invariants can only be applied on information known at compile time. pointer values cannot be known at compile time. not_null gives you the illusion of creating compile time invariants based on dynamic values. But that's impossible. You can still pass a nullptr to a not_null parameter indirectly which will assert at runtime. It just prevents a user from passing nullptr directly as a function argument. It provides no advantage to pass by reference. If you pass a null reference (you gotta go out of your way to do that), it will fail at runtime just like not_null. not_null does provide a consistent way of doing assert(value != nullptr) but an assert is clearer imo, not_null hides the assert away from the programmer and adds ambiguity. You can forget to assert just like you can forget to specify a parameter as not_null. int *x = nullptr; int **value = &x; func(*value); This will compile just fine, but will assert at runtime. If the program state cannot proceed when one of the functions is passed a nullptr then assert in the function and make it clear, otherwise check for nullptr condition and proceed accordingly. You can forget to do that just like you can forget to increment a value.
- roel_v 11y agoBeware that his example of boost::optional is, as far as I know, wrong. He returns an empty student, which you can't test for (unless your Student() has a way of telling you that it's default-constructed, and when a default-constructed Student is in fact the same as a 'null' Student). Instead of return boost::optional<Student>(); he should have done return boost::none; .
- KayEss 11y agoIf that's really the API for boost optional then I'm very pleased I never used it. A default constructed optional really needs to be empty rather than contain a default constructed value.
- vp2015 11y agoAre you sure about that? Both resources below say something opposite. http://bit.ly/1SEnJQe http://bit.ly/1SEnJQe - see optional<T>::optional() and http://bit.ly/1lh7eyv http://bit.ly/1lh7eyv - see default constructor (I'm just curious) Edit: I've tested it, you are wrong. Default constructor of optional doesn't call Student constructor (VS2015).
- roel_v 11y agoYes you're right, I misread. I still think the preferred idiom is to use boost::none (like the optional documentation does).
- vp2015 11y agoIn fact boost::optional examples use default constructor in this case - at least all examples I've seen, see http://www.boost.org/doc/libs/1_58_0/libs/optional/doc/html/boost_optional/examples.html http://www.boost.org/doc/libs/1_58_0/libs/optional/doc/html/...
- userbinator 11y agoNULL/zero is a very simple concept. It means the lack of something. C/C++'s equating of null/zero with false also makes great sense with you think of it this way. Thus my personal belief is actually "avoid NULL, use zero instead." program will fail in run-time. Sometimes it's not an acceptable situation, sometimes it just makes debugging other problems more complicated. I disagree. If I were to make a list of all the bugs I had to find over the years, sorted by difficulty, a nullpo (usually caused by something else) would be near the bottom. They're quite obvious precisely because of the crash that occurs when they're used, and you can usually easily trace back to the origin of that value. Seeing all these clumsy "solutions" that increase complexity just to avoid something so simple is both sad and somewhat amusing. It's a bit cargo-culty. E.g. if you use the "Null Object Pattern", with the example given you still have to presumably check whether the returned value is an instance of the null object or not... so not only do you still have to do the same thing you'd have to do if you'd just used a simple 0, you now also have to make an additional class and figure out how to compare with it. It's obfuscatory. I think avoiding "NULL" makes as much sense as avoiding the number 0 - i.e., none, null, \0, nada, zilch. ;-)
- hawkice 11y agoYes, NULL means the lack of something. Very simple. But not having something when you think you do is by far the most common class of errors. So if you are always clear about the fact you either WILL have something or MAY have something (instead of it being hidden), you can write software that you are more confident in, and (hopefully) crashes with completely opaque errors less frequently. [This is why I happen to completely agree w.r.t. Null objects -- I don't see a point unless it means something extremely specific. Like, File openFile() could return a UnreadableFile null-ish object as an error code, but that seems worse than just having checked exceptions.]
- userbinator 11y agoBut not having something when you think you do is by far the most common class of errors. In all the things I've debugged that's almost never been the actual error, but rather a symptom of something else (running out of memory, failed file opening, etc.) that needs further investigation. In my experience the "check for null, skip processing and continue if a value is null" way is a far worse option since it causes errors to propagate further, whereas a crash is an unmistakable call to action.
- vp2015 11y agoI've just updated this article, thanks for interest & for sharing it btw.