Domanda

Take the following code:

private var m_iQuanitity:int;
public function get quantity():int
{
    return m_iQuantity;
}

That seems to make perfect sense. You can see what the quantity is from an outside class without any problems, but you can't really mess with it at all. Now take the following code:

private var m_acUsers:ArrayCollection = new ArrayCollection();
public function get users():ArrayCollection
{
    return m_acUsers;
}

In that case you can't really set the variable directly, but you can still do just about everything else under the sun to it without any problems. You can call its AddItem and RemoveItemAt functions, which can do quite a bit to "set" the variable.

Does it still make sense to do this? I know you can create a duplicate ArrayCollection and just pass the duplicate back to avoid allowing it to be set, but doing stuff like that all over the place, purely for defensive programming, can waste a lot of CPU time. So I guess I'm asking if it still makes sense anyway, how so, and if I'm missing the point of using get and set completely? Thanks!

È stato utile?

Soluzione

Syntactically there is nothing wrong with what you've got, but the second example does break down the concept of 'get' by making more than a read only property. If you need to adhere to a read only policy, then you've broken that since now you can manipulate the ArrayCollection.

In the end it comes down to what it is you're tying to do. Does it matter for the project that you can change the value? If you're working on a project with more than a few people, this type of coding will require you to either add a comment or have you explain what you're doing. When ever you do something outside of the norm, that can add confusion, so it's always best to simplify and stick to what is expected, avoiding having to explain something.

Also, I can think of a few ways this could cause problems - changing values outside of the function if you pass the returned property off to other classes that don't know where it came from and having internal code in the original class fail.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top