你在编程时使用不变量吗?

发布于 2024-08-10 13:23:48 字数 76 浏览 4 评论 0原文

我正在学习中级编程课程,该课程强调不变量的使用。我以前从未使用过它们,而且它们似乎花费了更多时间来创作。软件工程行业是否强调不变量的使用?

I am taking an intermediate programming course which stresses the use of invariants. I have never used them before and they seem to take up more time to create. Does the software engineering industry stress the use of invariants?

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

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

发布评论

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

评论(3

七度光 2024-08-17 13:23:48

取决于你问的是谁——我使用不变量只是因为它让生活更轻松。学习不变量就像学习盲打字。每次使用不变量时,您都会对代码有更多了解。如果您将不变量作为注释插入循环中,会对读者有很大帮助。我想说,使用不变量使源代码的创建和维护变得更加便宜,并且使您能够创建更复杂且仍然可维护的算法。

与 OOP 相比,我从未见过有人因为使用不变量而浪费时间。

Depends on who you ask - I use invariants simply because it makes life easier. Learning invariants is like learning blind-typing. Each time you use an invariant, you know more about your code. If you insert the invariant as a comment in your loop, it helps the reader A LOT. I would say that using invariants makes creation and maintenance of source code much cheaper, and makes you able to create much more sophisticated algorithms, which are still maintainable.

And in contrast to OOP, I have never experienced anyone wasting their time by using invariants.

-柠檬树下少年和吉他 2024-08-17 13:23:48

我不太考虑不变量——不像前置/后置条件那么多。老实说,我可能应该更多地考虑不变量。

需要考虑的一件事是不变性 - 如果您使用面向对象语言,但尽可能使类型不可变,则无需过多担心不变量:如果状态一开始是有效的,它将保持有效。

听起来你的课程可能有点过分强调不变量......但这确实取决于你在做什么。它们在某些情况下比其他情况更合适。也许您的讲师只是它们的忠实粉丝,在它们真正有用的领域拥有丰富的经验。

I don't think about invariants very much - not as much as pre/post-conditions. I should probably think about invariants more, to be honest.

One thing to think about is immutability - if you're using an OO language but make types immutable where you can, you don't need to worry about invariants as much: if the state is valid to start with, it will stay valid.

It does sound like your course may be over-emphasizing invariants a little bit... but it does depend on what you're doing. They're more appropriate in some situations than others. Maybe your lecturer is just a big fan of them with a lot of experience in areas where they're really useful.

浅笑依然 2024-08-17 13:23:48

一旦您了解了不变量是什么以及它们的含义,它往往会改变您推理代码的方式。我的意思是,我很少写显式的不变量。但我的脑海中经常会浮现出我正在编写的代码中的不变量的画面。这将使您编写出更简单的代码。在大多数情况下,您最终得到的代码非常简单,无需编写有关不变量的显式注释。然而,不了解不变量的人编写的代码要复杂得多:)

Once you learn what invariants are and what they mean, it tends to change the way you reason about code. I mean, I very seldom write explicit invariants. But I often have a picture in my mind of the invariant in the code I'm writing. This leads you to write code that is much simpler. In most cases you end up with code that is so simple that you don't need to write an explicit comment about the invariant. Yet people who don't know about invariants write code that is much more complicated :)

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