默认的字符串初始化:null或空? [英] Default string initialization: NULL or Empty?

查看:369
本文介绍了默认的字符串初始化:null或空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是初始化我的琴弦为NULL,用以为NULL表示没有值和或的String.Empty是一个有效的价值。我看到最近的code,其中的String.Empty被认为是默认值,或重新presents没有价值的例子。这令我奇怪,与新加入的可空类型的C#好像我们正在倒退用绳子不使用空重present没有价值迈开步伐。

你作为默认的初始使用,为什么?

什么

编辑:基于我进一步的我的进一步思考的答案


  1. 避免错误处理如果该值不能为空,为什么得到它在第一时间设置为 NULL ?也许它会更好,在它​​发生,而不是通过其掩盖了你codeBase的其余地方以找出错误?


  2. 避免null检查如果您已经厌倦了在做code null检查,岂不是更好地抽象null检查?也许包裹(或​​扩展!)字符串方法,使它们 NULL 安全吗?如果你不断用的String.Empty 和空的情况去解决问题的方式进入您的系统中会发生什么事,你开始添加 NULL 检查反正?


我不禁回,这是懒惰的意见。如果你使用''而不是在他\\她的数据库中的任何DBA会拍你9途径傻了。我认为同样的原则也适用于编程和应该有人嫌这些上攻谁用头的String.Empty ,而不是 NULL 重新present没有价值。


  

相关问题


  
  

解决方案

+1空和NULL区分。我同意空应该是指有效,但空白和空应该是指无效。

所以我回答你的问题是这样的:

时,我想可能会或可能不会改变,比如一个有效的默认值,用户的中间名。

NULL 当它是一个错误,如果随后的code不设置值明确。

I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and "" or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types in c# it seems like we are taking strides backwards with strings by not using the NULL to represent 'No Value'.

What do you use as the default initializer and why?

Edit: Based on the answers I futher my further thoughts

  1. Avoiding error handling If the value shouldn't be null, why did it get set to NULL in the first place? Perhaps it would be better to identify the error at the place where it occurs rather than cover it up through out the rest of your codebase?

  2. Avoiding null checks If you are tired of doing null checks in code, wouldn't it be better to abstract the null checks? Perhaps wrap (or extend!) the string methods to make them NULL safe? What happens if you constantly use String.Empty and a null happens to work it's way into your system, do you start adding NULL checks anyways?

I can't help but return to the opinion that it is laziness. Any DBA would slap you nine ways to silly if you used '' instead of null in his\her database. I think the same principles apply in programming and there should be somebody to smack those upside the head who use String.Empty rather than NULL to represent no value.

Related Questions

解决方案

+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."

So I'd answer your question like this:

empty when I want a valid default value that may or may not be changed, for example, a user's middle name.

NULL when it is an error if the ensuing code does not set the value explicitly.

这篇关于默认的字符串初始化:null或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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