开发者

Why "Properties that return arrays are prone to code inefficiencies"?

开发者 https://www.devze.com 2023-01-08 10:57 出处:网络
I have a开发者_JAVA百科 piece of code which deals with customers stored in database. There is an object Customer, and it has, among other, two properties of type byte[]: one property for password salt

I have a开发者_JAVA百科 piece of code which deals with customers stored in database. There is an object Customer, and it has, among other, two properties of type byte[]: one property for password salt, the second one for password hash.

Checking the code with FxCop, I see that it complains (CA1819, Performance Rules) that:

"Properties that return arrays are prone to code inefficiencies. Consider using a collection or making this a method. See the design guidelines for more information."

and suggests:

"Change 'Customer.PasswordHash' to return a collection or make it a method."

I don't really understand, what is the code inefficiency in what I'm doing?


The problem is that arrays are always mutable. That means you can't return one from a method without either:

  • Allowing the caller to mess up your internal state
  • Creating a copy first

If you use a collection, you can create a read only wrapper around the real collection instead, and return that - and that can be considerably cheaper. Alternatively, if you change it to a method that will lower the expectation that it will be very quick to call.

Of course, if you're happy with callers mutating your data, then an array will work fine...

0

精彩评论

暂无评论...
验证码 换一张
取 消