使用finally从setter返回旧值,不带临时变量

发布于 2024-11-07 20:13:15 字数 351 浏览 6 评论 0原文

我正在 Map.Entry 中实现 V setValue(V value) 方法,并完成了以下操作:

@Override public T setValue(T value) {
  try {
    return this.value;
  } finally {
    this.value = value;
  }
}

它按预期工作。

我知道有一些关于 finally 块之类的问题,但我找不到这个具体问题。您对这个特定用例有什么想法?这合法吗?应该避免吗?如果是,那么为什么或为什么不。谢谢!

I was implementing the V setValue(V value) method in Map.Entry<K,V> and have done the following:

@Override public T setValue(T value) {
  try {
    return this.value;
  } finally {
    this.value = value;
  }
}

It works as it should.

I know there are some questions about finally blocks and stuff, but I couldn't find this specific question. What are your thoughts on this particular use-case? Is this legal? Should be avoided? If yes then why or why not. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我纯我任性 2024-11-14 20:13:15

更喜欢简单、明显的代码。即

@Override public T setValue(T value) {
    T old = this.value;
    this.value = value;
    return old;
}

此外,这可以扩展为[本地]线程安全(如 NIO attach)。

private final AtomicReference<T> valueRef;

@Override public T setValue(T value) {
    return valueRef.getAndSet(value);
}

Prefer simple, obvious code. i.e.

@Override public T setValue(T value) {
    T old = this.value;
    this.value = value;
    return old;
}

Also, this can be extended to be [locally] thread-safe (as NIO attach).

private final AtomicReference<T> valueRef;

@Override public T setValue(T value) {
    return valueRef.getAndSet(value);
}
等你爱我 2024-11-14 20:13:15

它有效,但它并不那么明显(易于理解):

@Override public T setValue(T value) {
  T oldValue = this.value;
  this.value = value;
  return oldValue;
}

为什么不使用这种更简单的形式?

It works, but it's not nearly as obvious (easy to understand) as:

@Override public T setValue(T value) {
  T oldValue = this.value;
  this.value = value;
  return oldValue;
}

Why not use this simpler form?

落花浅忆 2024-11-14 20:13:15

嗯,我认为,目前来说,这是绝对合法的。通常,您使用finally 子句来指定在返回之前分配执行o 的值。但有时我们习惯将其放入返回值中,并引发警告。我认为你必须避免这种返回,但你可以使用finally来完成其余的事情。

否则,它就像一个过时的函数,无论您将这些赋值放在finally还是try/catch块之后,都没有关系。

Well, I think that, by the moment, it's absolutely legal. Normally you use the finally clause to specify values that execute o are assigned just before the return. But sometimes we use to put inside the return, and a warning is thrown. I think you must avoid that return, but you can use the finally for the rest.

Otherwise, it is like an obsolete function, for example, and it does no matter if you put those assignments inside the finally or after the try/catch block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文