Is it common, in API Design, to do something like this:
public ReadOnlyCollection Get开发者_运维百科Collection
{
get { // Get's read only collection here...
}
}
In the body of the get, this calls a private method that fills the collection. So I only expose one, consistent object to clients. The thing which confuses me is if it is right to make the class and its members static? After all, we are returning an object so the class is immutable too (I keep thinking an immutable class should be static?). I am aware that static does not insinuate stateless. Am I right in thinking static is right for anything which will be centralised as one entity (e.g. company details)?
Thanks
Avoid static
- it is a trait of procedural programming. Use it only for utility methods and widely-accessibly constants.
And no - static != immutable, they have nothing in common. Static is a global state, something which is not thread-safe, and you can't have more than one occurrence of the static data in your application.
Immutable means that an object instance cannot change its internal state. That is String
for example - once you construct it, you cannot change it. It has nothing to do with static-ness, though.
As for the first question - it is perfectly fine for a getter to expose an internal collection, especially read-only copy of it.
depending on the model requirements, having 'smart' setters and getter is Ok. I don't think your described use of 'static class' is correct here. If you are returning a computed list, you might want to make it an unmodifiable collection. This helps (but is not all you have to do) make it so the only way to change your domain objects is through setters.
The purpose of a getter method is simply to return a value, in a totally black-box fashion as to where the value comes from. It's very common to put additional code in the getter method, the specific example you're talking about sounds like a technique called "lazy initialization". This does not at all violate any OO principles.
Choosing static or non-static isn't so much about statefulness or mutability. If anything, you want to ask whether or not the class should represent a Singleton. If it is holding "company details" as a bundle of constants, then static would be appropriate. It the class is basically a DAO, and re-fetching the latest changes to company detail on each and every request, then you might want an non-static class. It sounds like your example leans more toward the former.
精彩评论