避免使用If语句检查对象是否为Null

时间:2019-12-17 09:09:42

标签: spring design-patterns nullpointerexception lombok

我正在使用Lombok S1F4j记录我的数据,并且为了避免记录空数据,我检查对象是否为null。我想避免这些家伙,所以我的代码更健壮并且易于测试。

这是一个示例:

if (object != null)
 {
log.info("lalalalal", object)
object1.set(object)  }

有没有避免检查null而不记录对象是否为null的信息?

2 个答案:

答案 0 :(得分:0)

您可以在调用对象的任何函数或数据字段之前添加问号。仅当对象不为空时才调用函数

class AggregatingExceptions
{              
    public void Main()
    {
        //create the alarm
        AlarmAndLocation alarm = new AlarmAndLocation();

        //subscribe the listeners 
        alarm.OnAlarmRaised += AlarmListener;
        alarm.OnAlarmRaised += AlarmListener2;

        try
        {
            alarm.RaiseAlarm("Kitchen");
        }
        catch (AggregateException agg)
        {
            foreach (Exception ex in agg.InnerExceptions)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    private static void AlarmListener(object sender, AlarmEventArgs e)
    {
        Console.WriteLine("Alarm listener 1 called.");
        throw new Exception("Hello");
    }
    private static void AlarmListener2(object sender, AlarmEventArgs e)
    {
        Console.WriteLine("Alarm listener 2 called.");
        throw new Exception("World");
    }

}

public class AlarmAndLocation
{
   public event EventHandler<AlarmEventArgs> OnAlarmRaised = delegate { };

   public List<Exception> exceptionList = new List<Exception>();

    public void RaiseAlarm(string location)
    {            
        foreach (Delegate handler in OnAlarmRaised.GetInvocationList())
        {
            try
            {
                handler.DynamicInvoke(this, new AlarmEventArgs(location));
            }
            catch (TargetInvocationException ex) 
            {
                exceptionList.Add(ex.InnerException);
            }
        }

        if(exceptionList.Count > 0)
        {
            throw new AggregateException(exceptionList);
        }
    }
}

public class AlarmEventArgs : EventArgs
{
    public string  Location { get; set; }

    public AlarmEventArgs(string location)
    {
        Location = location;
    }
}

答案 1 :(得分:0)

您可以创建类似以下内容的包装函数:


    public static void log_info(Logger logger, Object obj) {
        if (obj != null) {
            logger.info(obj);
        }
    }

然后,使用此包装器方法代替日志记录方法。