Can I use mvc without getters and setters?

ぃ、小莉子 提交于 2019-12-11 03:56:11

问题


If I don't want to expose the state of my object, but I still need to display it (in HTML, XML or JSON let's say), how would I go about doing that in an MVC environment. Does it make sense to have an export method which exports a dumbed down immutable object (a "data class" if you will). What about adding in a render method which talks to an interface? Are there any other approaches to this problem?


回答1:


The render method comes the closest to not exposing state. Another method (well-known to Smarty users) is to feed the view non-object data structures to work with.

It's worth asking, though, what is the problem that these abstractions and/or the interface hiding they serve are solving? If you're going to be doing all this work, IMO you should make sure there's some work it's saving you.




回答2:


The point of encapsulation is hiding implementation. There is "state" that other objects do need to know about -- sometimes the whole purpose of an object is telling such state.

For instance, it would be pretty useless to have a Defined Finite Automata object which doesn't have a getter for whether it's on a final state or not. But it's certainly useful to encapsulate how that information is stored internally.

Now, the goal of getters and setters is to provide an interface to properties of a state of an object, which might not have anything to do with how it is actually implemented. Granted, most of the time these properties are fields in the object, and the getters and setters just shallow shells. On the other hand, you have the freedom to change the internal implementation, because the getters and setters will ensure interface compatibility.

If, however, these properties are too related to the actual implementation and not so much with what the object is about, then you should consider removing such getters and setters.

Having said all that, if you need to display something to the user, then this is a property other objects need to know about. An object shouldn't be concerned with how to display itself, for many reasons. One of them is that it can't know how it should be rendered without knowing how it is used by the application, which would make IT know too much about the other objects.



来源:https://stackoverflow.com/questions/1184702/can-i-use-mvc-without-getters-and-setters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!