Using accessors

So far you have a perfectly good init method for Appliance, but I want to show you a variation that you will see in other people’s code. I typically do a plain assignment in an init method, but many programmers will use the accessor method. Change your init method to do this:

-​ ​(​i​d​)​i​n​i​t​
 ​ ​ ​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​C​a​l​l​ ​N​S​O​b​j​e​c​t​'​s​ ​i​n​i​t​ ​m​e​t​h​o​d​
 ​ ​ ​ ​ ​ ​ ​s​e​l​f​ ​=​ ​[​s​u​p​e​r​ ​i​n​i​t​]​;​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​D​i​d​ ​i​t​ ​r​e​t​u​r​n​ ​s​o​m​e​t​h​i​n​g​ ​n​o​n​-​n​i​l​?​
 ​ ​ ​ ​ ​ ​ ​ ​i​f​ ​(​s​e​l​f​)​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​G​i​v​e​ ​v​o​l​t​a​g​e​ ​a​ ​s​t​a​r​t​i​n​g​ ​v​a​l​u​e​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​[​s​e​l​f​ ​s​e​t​V​o​l​t​a​g​e​:​1​2​0​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​}​
 ​ ​ ​ ​ ​ ​ ​ ​r​e​t​u​r​n​ ​s​e​l​f​;​
 ​ ​ ​ ​}​

In most cases, there is little reason to do one over the other, but it makes for a great argument. The argument goes like this: The assign guy says, You can’t use an accessor method in an init method! The accessor assumes that the object is ready for work, and it isn’t ready for work until after the init method is complete. Then the accessor method guy says, Oh, come on. In the real world that is almost never an issue. My accessor method might be taking care of other stuff for me. I use my accessor anytime I set that variable. In reality, either approach will work in the vast majority of cases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset