为了性能而违反集合属性应该是只读的原则是否可以?

发布于 2024-09-03 12:50:05 字数 297 浏览 2 评论 0原文

我使用 FxCop 分析了我编写的一些代码。我通过 setter 暴露了一个集合。我明白为什么这不好。在我没有预料到的情况下更改后备存储是一个非常糟糕的主意。但这是我的问题。我从数据访问对象中检索业务对象列表。然后,我需要将该集合添加到另一个业务类中,我是使用 setter 方法来完成的。我这样做的原因是,进行赋值比通过另一个 addElement 方法一次将数十万个对象插入到集合中要快。

在某些场景下,集合有 getter 可以吗? 我想宁愿有一个接受集合的构造函数? 我想也许我可以将对象传递给 Dao,然后让 Dao 直接填充它? 还有其他更好的想法吗?

I used FxCop to analyze some code I had written. I had exposed a collection via a setter. I understand why this is not good. Changing the backing store when I don't expect it is a very bad idea. Here is my problem though. I retrieve a list of business objects from a Data Access Object. I then need to add that collection to another business class and I was doing it with the setter method. The reason I did this was that it is going to be faster to make an assignment than to insert hundreds of thousands of objects one at a time to the collection again via another addElement method.

Is it okay to have a getter for a collection in some scenarios?
I though of rather having a constructor which takes a collection?
I thought maybe I could pass the object in to the Dao and let the Dao populate it directly?
Are there any other better ideas?

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

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

发布评论

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

评论(2

绾颜 2024-09-10 12:50:05

如果这些属性不是您的公共 API 的一部分,请自行淘汰;否则不行。但是,您真的确定这是性能瓶颈吗?我敢打赌你现在正在过早地优化。

If the properties aren't part of your public API, knock yourself out; otherwise no. But then, are you actually sure that this is a performance bottleneck? I'd wager you're prematurely optimizing at this point.

灵芸 2024-09-10 12:50:05

我仍然会将该属性设置为只读,并提供一种替代方法,该方法接受集合并进行赋值——可能是构造函数。当然,这就是属性设置器应该做的事情,但这让类用户非常清楚,您不希望该属性从您的下面移出,并且分配应该只在特殊情况下发生。

I would still make the property read only, and provide an alternative method that takes a collection and does the assignment — possibly the constructor. Sure, that's a what a property setter is supposed to be for, but this makes it really clear to a class user that you don't expect this property to moved out from under you, and assignment should only happen in exceptional circumstances.

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