I was reading Hatena's anonymous diary somehow the other day, and the question was written there, "Why use setter/getter instead of controlling access to internal member variables in Java public/private?" There was. I also used to write getters/setters (or use lombok) habitually, but that's why I didn't control access to member variables with public/private, and made member variables uniformly private variables. I wondered if the method was to access from getter/setter. I felt that C # and PHP do not write getters/setters as exactly as Java.
When I searched, this page (stackoverflow) was hit. The reasons for using getters/setters on this page were listed below.
There were also the following answers. Two weeks after the implementation (two months or two years later), I finished the implementation with public member variables, but after that, in fact, it is not enough to just set the value to the member variable, more than that when setting the value Suppose it turns out that you need to do that. If you want to implement that change, and the member variable is already referenced by 238 outer classes, you're at a loss (how to fix it).
Since C # has an automatic property initialization function, it seems that you can exchange via getter/setter without writing getter/setter in the class.
It seems that PHP can also create getter/setter functions automatically depending on the IDE, but from the viewpoint of performance, it seems that naive setter/getter should be avoided ([stackoverflow](stackoverflow). However, this was written at the time of php5, and php7 and php8 that came out after that should have significantly improved performance compared to those days, so I thought that it would be better to use setter/getter now. It was.
Even in stackoverflow, the following cases were mentioned as reasons why setter/getter should be used in PHP. You can add validation processing (even later) by defining a setter.
class Foo {
public $bar; //I'm expecting it to be an integer type
}
$foo = new Foo;
$foo->bar = "string"; //Since it is dynamically typed, it can also be a string type.
Some have argued that (naive getters/setters) are not desirable from a readability standpoint. It seems good to avoid the situation where getter/setter functions overflow by using lombok. Some people have argued that getters/setters are anti-patterns in pure OOP. I haven't read it properly (!!), but I think I'm not saying that I should use public member variables instead, but that I should define an OOP-like function instead of using an object as a data structure in the first place. ..
I'm glad that it was an opportunity to look back on the meaning of what I usually do.
Recommended Posts