不使用setter和getter真的错误吗? [英] Is it really that wrong not using setters and getters?

查看:63
本文介绍了不使用setter和getter真的错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP的新手.出于某种原因,在诸如JAVA之类的其他类型的编程语言中,我对每个变量都使用设置器和获取器没有问题,但是当我使用PHP进行编程时,可能是因为它是如此灵活,所以感觉像是在浪费时间.多数情况下,仅将类属性设置为公共并像这样操作它们会更简单.事实是,当我这样做时,我感觉自己做错了一些事情,并且违背了面向对象原则.

I'm kind of new in PHP. For some reason in other types of programming languages like JAVA I have no problem with using setters and getters for every single variable, but when I'm programming in PHP probably because it is so flexible it feels kind of like a waste of time. It feels simpler to just set the class attributes as public most of the time and manipulating them like that. The thing is that when I do it like this I feel like I'm doing something wrong and going against OO principles.

不使用setter和getter真的不对吗?为什么或者为什么不?你们大多数时候是怎么做到的?

Is it really that wrong not using setters and getters? Why or why not? How do you guys do it most of the time?

推荐答案

不使用属性访问器的主要问题是,如果发现以后需要将字段更改为属性,以使其成为计算属性例如,在子类中–您将破坏API的客户端.对于已发布的图书馆,这将是不可接受的.对于内部人员,只需进行大量工作即可解决问题.

The main problem with not using property accessors is that if you find out you ever need to change a field to a property later on – to make it a computed property in a subclass, for instance – you’ll break clients of your API. For a published library, this would be unacceptable; for an internal one, just quite a lot of work fixing things.

对于私有代码或小型应用程序,只需附加它即可. IDE(或文本编辑器)将允许您生成访问器样板并使用代码折叠将其隐藏.可以说,这使得机械地使用吸气剂和吸气剂相当容易.

For private code or small apps, it could be feasible to just wing it. An IDE (or text editor) will let you generate accessor boilerplate and hide it using code folding. This arguably makes using getters and setters mechanically fairly easy.

请注意,某些编程语言具有综合默认field + getter + setter的功能-Ruby通过元编程来实现,而C#具有自动实现的属性. Python通过让您覆盖属性访问,使您可以将属性封装在需要它的子类中,而不必事先打扰它,从而完全避开了问题. (这是我最喜欢的方法.)

Note that some programming languages have features to synthesise the default field+getter+setter – Ruby does it via metaprogramming, C# has auto-implemented properties. And Python sidesteps the issue completely by letting you override attribute access, letting you encapsulate the attribute in the subclass that needs it instead of having to bother with it up front. (This is the approach I like best.)

这篇关于不使用setter和getter真的错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆