开发者

why are getters and setters required in objective c?

开发者 https://www.devze.com 2023-03-09 05:46 出处:网络
i have read several answers on stackoverflow with this question in my mind, but my question is a little different.

i have read several answers on stackoverflow with this question in my mind, but my question is a little different. what i want to know is for variables that are not dependent on other variables of the class, why can't i declare the variable public like we do in java and then access the 开发者_高级运维variable directly?

i mean in objective c, if i have a variable which i have declared in the interface of a class, why can't i directly (without making its getters and setters) access with, self.variable or instanceofclass.variable....?

this is what we usually do in java and other object oriented languages.

getters and setters have their own advantages, but when you are doing simple things,would it not be better if you access variables in the way i have mentioned above.

PS: i am very new to objective c, so if we can access the variables in the way that i am claiming we cannot , please excuse. i have tried doing so, but there was an error, hence i am asking, but it very well could have been due to something else. so again please excuse.

thank you in advance.


because it is fundamentally wrong. If you expose a member variable as public, you are exposing internal details of a storage strategy which is not supposed to be known to the client. This will make your life much harder if, in the future, you want to implement smart strategies like allocation on the fly, or even just putting a print statement every time the variable is accessed, for debug purposes. Accessing a public variable gives you much less freedom than calling a method, and you are bound to your choice because accessing a member var and calling a member function use different syntaxes, so you will have to go around and fix your code everywhere.

The only situation where this is not an issue is when you have a pure struct, a class whose members are purely to hold and carry around a bunch of data under a collective name, and the storage strategy is already exposed by the very nature of the bunch of data you are carrying around.

0

精彩评论

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