Bul*_*aza 5 java api-design awtrobot
执行软件时出现以下异常:
Exception in thread "main" java.lang.IllegalArgumentException: Delay must be to 0 to 60,000ms
at java.awt.Robot.checkDelayArgument(Robot.java:544)
at java.awt.Robot.delay(Robot.java:534)
at com.company.Main.main(Main.java:10)
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是有一个睡眠时间限制,并且标准库异常消息的语法/错字(to 0 to
?)不好。在检查了delay()
方法的源代码之后,我注意到它限制了等待时间,因为出现了以下异常:
/**
* Sleeps for the specified time.
* To catch any <code>InterruptedException</code>s that occur,
* <code>Thread.sleep()</code> may be used instead.
* @param ms time to sleep in milliseconds
* @throws IllegalArgumentException if <code>ms</code> is not between 0 and 60,000 milliseconds inclusive
* @see java.lang.Thread#sleep
*/
public synchronized void delay(int ms) {
checkDelayArgument(ms);
try {
Thread.sleep(ms);
} catch(InterruptedException ite) {
ite.printStackTrace();
}
}
private static final int MAX_DELAY = 60000;
private void checkDelayArgument(int ms) {
if (ms < 0 || ms > MAX_DELAY) {
throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
}
}
Run Code Online (Sandbox Code Playgroud)
为什么要这样做?似乎API设计不佳。InterruptedException
除了为您捕获冗余的已检查异常并同步呼叫外,它还有什么目的?
除了原始开发人员之外,没有人可以回答这个问题。
你可以很清楚地看到它所做的只是 call Thread::sleep
,所以只需做同样的事情即可。你不需要打电话Robot::delay
。
以下是完全等价的,没有任意限制
Robot r;
long sleepDuration = 60001;
synchronized (r) {
try {
Thread.sleep(sleepDuration);
} catch(InterruptedException ite) {
ite.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
API 设计似乎很糟糕
这个班级今年19岁。JDK 中有很多糟糕的设计决策,尤其是在旧的东西中。
归档时间: |
|
查看次数: |
62 次 |
最近记录: |