使用空字符串而不是null - 一个好习惯? [英] Use of empty strings instead of null - a good practice?

查看:116
本文介绍了使用空字符串而不是null - 一个好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如在数据库中:

  CREATE TABLE用户(
id INTEGER IDENTITY PRIMARY KEY,
last_name VARCHAR(50)DEFAULT''NOT NULL,
first_name VARCHAR(50)DEFAULT''NOT NULL,
email VARCHAR(50)DEFAULT''NOT NULL)

并考虑一个使用Hibernate作为ORM与此数据库交互的程序。



在我看来,这意味着:避免NullPointerExceptions
$ b


  • 避免需要检查null价值



这是不错的做法吗?请举例说明正反两面。正如PeterMmm所写,Null具有特殊的含义,并且通常受到支持由数据库引擎中的特殊操作员提供。



良好习惯就是这样一种短语,它意味着任何你想表达的意思,但是解开一些论点:$ b​​
$ b


  • 可维护性:坏主意。大多数开发人员习惯于在数据库系统中实现NULL,并且需要在您的设计中进行特殊培训。

  • 容错:坏主意。如果列不允许为空,那通常意味着应用程序设计中的某些内容。如果一个用户记录必须有一个电子邮件地址是有效的,你现在不能再在数据库级验证这一点 - 所以你的数据库可能会逐渐充满虚假数据,你只会发现当你试图发送一封电子邮件至 ''。 空指针异常是特性,而不是bug! 性能:根据 http://www.sql-server-performance.com/2007/datatypes/ ,NULL较慢。


    ul>

    Consider for example in the database:

    CREATE TABLE users (
      id INTEGER IDENTITY PRIMARY KEY,
      last_name VARCHAR (50) DEFAULT '' NOT NULL,
      first_name VARCHAR (50) DEFAULT '' NOT NULL,
      email VARCHAR(50) DEFAULT '' NOT NULL)
    

    And consider a program that interacts with this database using Hibernate as ORM.

    In my opinion this would mean:

    • avoiding NullPointerExceptions
    • avoiding the need to check for null values

    Is this good practice? Please give examples of the pros and cons.

    解决方案

    As PeterMmm writes, "Null" has a special meaning, and is generally supported by special operators in your database engine.

    "Good practice" is one of those phrases that means whatever you want it to mean, but unpacking the arguments a little:

    • Maintainability: Bad idea. Most developers are used to the way NULL is implemented in database systems, and will need special training in your design.

    • Fault tolerance: Bad idea. If a column is not allowed to be null, that usually means something in your application design. If a user record MUST have an email address to be valid, you can now no longer validate this at the database level - so your database could gradually fill up with bogus data, and you'd only find out when you try to send an email to ''. "Null pointer" exceptions are feature, not a bug!

    • Performance: according to http://www.sql-server-performance.com/2007/datatypes/, NULL is slower.

    这篇关于使用空字符串而不是null - 一个好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆