[英]Lock a boolean method (How to return nothing from a boolean method or discard)
我有一个private boolean status;
场。
我试图以这种方式锁定一个类方法:
status == true
表示班级被锁定, status == false
表示班级解锁
如果该类已被锁定,则方法无法调用,例如:
protected void flip ()
{
if (locked()) return;
face = (int) (Math.random() * 2);
}
要理解这个问题,请考虑:
protected boolean isHeads ()
{
//if(!locked()) return false or true;
//if I write upper command then its true or false like the bottom command and its unclear that this false or true is for which of them
//if(!locked())
//if i write this command then i have to write another return and its the same problem too;
return (face == HEADS);
}
PS:我有一个接口,所以我不能改变关于locked()
和lock等的方法;
这种编程的正确设计是抛出异常,所以代码应该是这样的:
protected boolean isHeads () throws ObjectIsLockedException
{
if(locked()) throw new ObjectIsLockedException();
return (face == HEADS);
}
请注意ObjectIsLockedExpception
不是 Java 异常:您必须在代码中将其声明为类。
您不能从布尔方法返回任何内容。 它必须是真的或假的。 返回 int 或 enum 或使函数等待。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.