构造函数中的外部副作用

发布于 2024-09-18 07:24:34 字数 438 浏览 12 评论 0原文

看一下这段代码:

#include <framework_i_hate.h>
int main() {
  XFile file("./my_file.xxxx", "create");
  XObject object("my_object");
  // modify the object
  object.Write();
}

尝试猜测 object 将被保存在哪里...是的,您猜对了。我觉得这太神奇了,我想写一些类似 object.Save(file) 的东西,但没有必要。显然,framework_i_hate.h 中有一个全局变量,它在 file 构造函数中被修改。您如何看待构造函数内部的这种副作用?

如何隐藏这种行为?

对于猜出框架的人来说是一个奖励。

Look at this code:

#include <framework_i_hate.h>
int main() {
  XFile file("./my_file.xxxx", "create");
  XObject object("my_object");
  // modify the object
  object.Write();
}

Try to guess where object will be saved... yes, you guessed it. I think this is too magic, I'd like to write something like object.Save(file), but it's not necessary. Obviously there is global variable inside framework_i_hate.h that it is modified during the file constructor. What do you think about this side effect inside constructor?

How can this behavior be hidden?

A bonus to who guess the framework.

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

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

发布评论

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

评论(3

厌味 2024-09-25 07:24:34

帖子非常混乱难以理解,最后的问题非常反讽。
全局变量是邪恶的,还要添加什么?

Very muddled hard to understand post and the question in the end is very rhetorical.
Global variables are evil, what else to add?

忆依然 2024-09-25 07:24:34

关于这一点可以说的还不够明显:这是一个相当令人讨厌的副作用,因为:

  • 结果的行为是意外的,根本不可预测,除非你很了解那个框架。

  • 在面向对象编程中,全局程序状态通常不是一个好主意。 (事实上​​,全局状态可能从来都不是一个好主意,所以如果可以的话最好避免它。)

  • 这个框架很可能也不是线程安全的。 (想一想,当两个并发线程都创建一个 XFile 对象,然后其中一个线程写入一个 XObject 时会发生什么……它最终会保存在哪里? )

虽然这个线程被标记为 C++ 而不是关于 .NET,但我以前见过这种“反模式”,其形式不太严重且更理智,即数据库事务范围。

What can be said about this that isn't already obvious enough: It's a fairly nasty side effect, because:

  • the resulting behaviour is unexpected and not predictable at all, unless you know that framework well.

  • global program state usually isn't a good idea in object-oriented programming. (In fact, global state is probably never a good idea, so best avoid it if you can.)

  • it's fairly likely that this framework isn't thread-safe, either. (Think about what happens when two concurrent threads both create an XFile object each, and one of these threads then writes an XObject... where will it end up being saved?)

While this thread is tagged C++ and not about .NET, I have seen this "anti-pattern" before in a less severe and much more sane form, namely with DB transaction scopes.

很酷又爱笑 2024-09-25 07:24:34

我更愿意看到 XFile 和 XObject 之间的关系是明确的,我同意这种“魔法”隐藏得很好。我还质疑为什么要为对象指定一个名称,除非 API 的其他部分中该名称很重要。

全局变量被鄙视的原因有很多,这只是一个例子。

I'd prefer to see the relationship between XFile and XObject be explicit, I agree that this "magic" is too well hidden. I also question why the object is given a name, unless there are other parts of the API where the name is significant.

Global variables are despised for many reasons, this is just one example.

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