凡检查对象是否为空或不? [英] Where to check if an object is null or not?

查看:165
本文介绍了凡检查对象是否为空或不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你在哪里检查,如果要传递给方法的对象为空或不是?

Where do you check if an object that you are passing to a method is null or not?

如果一个对象需要调用一个方法之前进行测试?或使用参数的方法中?

Should an object need to be tested before calling a method? or within the method that is using the argument?

public class Program
{
    public static void Main(string[] args)
    {
        // Check if person is null here? or within PrintAge?

        PrintAge(new Person { Age = 1 });
    }

    private static void PrintAge(Person person)
    {
        // check if person is null here?

        Console.WriteLine("Age = {0}", person.Age);
    }
}

public class Person
{
    public int Age { get; set; }
}

有一个空检查这两类似乎太多多余的code。

Having a "null" check in both classes seem to be too much redundant code.

:?什么将是一个主叫或被叫内检查空的DIS /优势

: What would be an dis/advantage of checking for null within a caller or a callee?

:我只是碰到了防御性编程,它似乎像它主张检查被叫内空。我不知道这是一种被广泛接受的做法。

: I just ran into Defensive Programming and it seems like it advocates checking null within a callee. I wonder if this is a widely accepted practice.

推荐答案

您可以设计一个方法,有效的对象只工作。

You can design a method to work with valid objects only.

这意味着你期望得到有效的对象(在你的情况不为空)。
这意味着,你不知道如何反应,如何处理无效对象:

That means you are expect to receive valid objects ( not null in your case ).
That means you don't know how to react and what to do with invalid objects:

  • 从功能默默地返回 是不是解决;
  • 在抛出一个异常,将意味着你将责任推给上 方法在那里他们可以传递给你之前已经检查值。
  • returning silently from the function is not a solution;
  • throwing an exception will mean you move responsibility to the upper methods where they can check the value already before passing to you.

所以,如果你的方法不知道如何处理无效的对象和方法将不执行额外的逻辑在无效的情况下,你应该把

So if your method don't know exactly how to handle invalid object and the method won't follow additional logic in the invalid case you should put

Debug.Assert( Person );

PrintAge 开始,这将强迫你做检查上通过调用堆栈。

at the PrintAge begin and this will force you to make checks upper by call stack.

在层次较低的功能是它应该做的少检查的。在做这做的工作职能检查以下是缺点

The lower function in hierarchy is the less checks it should do. The following is disadvantages of doing checks in the functions that do the work.

  • 在该功能可在做实际的工作 必须尽可能明确 没有大规模的如果取值
  • 函数将被调用更多的则多次
  • 在这样的函数可以调用这些功能,他们可以再次调用这些功能。他们每个人都将执行相同的验证
  • Function that is doing actual work has to be as clear as possible without mass of ifs
  • Function will be called more then many times
  • Such function can call such functions and they can call such functions again. Each of them will perform the same validation

这篇关于凡检查对象是否为空或不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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