如何避免对对象进行繁琐的空检查
如果我有一个类想要接受可选记录器来记录调试信息:
public class A {
private Logger logger ;
public A( Logger logger ) {
this.logger = logger ;
}
public A() {
this( null ) ;
}
public void hello() {
logger.debug( "hello" ) ;
}
public void goodbye() {
logger.warn( "goodbye" ) ;
}
}
有什么方法可以避免需要不断的空检查?
public void hello() {
if( logger != null ) {
logger.debug( "hello" ) ;
}
}
public void goodbye() {
if( logger != null ) {
logger.warn( "goodbye" ) ;
}
}
我想也许如果我创建一个记录器包装类,它可以为我进行检查,然后什么都不做,或者记录消息。但随后我需要包装我想要使用的每个方法。
If I have a class that I want to accept an optional logger to log debug information:
public class A {
private Logger logger ;
public A( Logger logger ) {
this.logger = logger ;
}
public A() {
this( null ) ;
}
public void hello() {
logger.debug( "hello" ) ;
}
public void goodbye() {
logger.warn( "goodbye" ) ;
}
}
Is there any way for me to avoid the need for constant null checks?
public void hello() {
if( logger != null ) {
logger.debug( "hello" ) ;
}
}
public void goodbye() {
if( logger != null ) {
logger.warn( "goodbye" ) ;
}
}
I thought maybe if I made a logger wrapper class, that could do the checks for me and then either do nothing, or log the message. But then I would need to wrap each method I would want to use.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我将创建 Logger 作为接口并实现真正的记录器和不记录任何内容的虚拟类。这样,您始终可以访问记录器而无需任何空检查。
I would create
Logger
as an interface and implement the real logger and a dummy class that doesn't log anything. This way, you can always just access the logger without any null checks.所有答案基本上都建议使用空对象模式,请参阅:
All answers basically suggest using Null Object pattern, see:
两件事:
2 things:
可能是这样的:
现在您只需调用
logDebug(str)
或logInfo(str)
,您还可以使用MessageFormat.format()
:Something like this maybe:
Now you can just call
logDebug(str)
orlogInfo(str)
, and you can also interpolate the log messages with parameters usingMessageFormat.format()
:抱歉,如果这听起来很愚蠢,但是使方法 Warn 和 Debug static 不会解决这个问题吗?
如果您需要一个实例,只需在静态方法中创建它,或者如果它是单例,则在静态方法中检查是否为 null。
Sorry if it sounds dumb, but won't making the methods Warn and Debug static solve this ?
If you need an instance just create it inside the static methods, or if its a singleton check forr null inside the static methods.
您可以在 1 参数构造函数中将布尔值“enableLogging”设置为 true,在空构造函数中将布尔值“enableLogging”设置为 false。因此,您可以为您的支票赋予更多意义 - 而且速度更快。
You could set a boolean "enableLogging" to true in your 1-parameter constructor, and to false in your empty constructor. Thus you give more meaning to your checks - and they are faster.
主要问题是您到处都使用 null,这意味着您自然需要到处测试 null。创建一个 Logger,其中所有方法都不执行任何操作,并在适当的情况下使用该实例。
The main problem is you are using null everywhere, which means naturally you need to test for null everywhere. Create a Logger where all methods do nothing and use that instance where appropriate.