OOP: Should setters be private? - oop

When writing getter/setters in classes, should the setters be private methods?
It might seem a bit redundant to have to write another method to set a variable but it seems like that might allow for a more maintainable code structure.

Setter is a method that is suppose to allow modifying internal state of an object without exposing that object directly. We can later include validation or other logic inside setter.
If your setter is private, you are missing the point. It's like having a door in your house that is always closed and doesn't even allow opening. Also inside the class you can simply access the field directly, why would you use a setter there?
Of course the real question is: should we have setters at all? The typical class these days holds a bunch of fields, auto-generated getters/setters and no logic. This is hardly a class. It's just a structure with awkward way of accessing elements. But that's not what you are asking for.

In General, I don't recommend "private" access for any member, maybe "protected". Usually, you or other programmer may require it in a descendant class.
Long Boring Descriptive Answer
Now, for accessors ("getters & setters"), its also depends on the syntax and implementation of properties on the programming language.
For Example, C++, or Java, I consider not have "real properties", and accesors, maybe required to have the same scope as the properties. (Unless using a template for properties).
C# & Delphi (Lazarus) have properties implemented, but, I don't like the way C# declare the accesors.
There are cases, where you may want a property not to be public, maybe "protected" or "package protected", and its accesors, the same access than the property.
I just work in some code in Object Pascal. Most properties where "public", and its accesors "protected", but, want to migrate that code to c++ or Java, so, I make the accesors "public", as well.
Quick Short Answer
Same access as the property, but, depends on the syntax of properties.

They should be public, if the intent is to allow them to be manipulated from an external object. That is the point of POJO implementation. (http://en.wikipedia.org/wiki/Plain_Old_Java_Object)
If you're looking to implement some other pattern, perhaps looking at the docs on Java Access Modifiers should be your first stop (http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
However there might be some cases where you want to restrict access to your data just to instances of the same class, but you still want to retain some control over the access to the data for whatever reason (bookkeeping, locking etc.) - in that case having private (or protected) setters/getters makes sense (from both code reuse and safety POV). However, you can't rely on the compiler to catch you doing something wrong then.

Related

setting/getting object's property value directly or by method?

This is more general question to any OOP, please before answer consider readability and efficiency.
Here is example in Javascript:
function fnc () {
this.var = "abc";
this.setVar = function (val) {
this.var = val;
}
this.getVar = function () {
return this.var;
}
}
Now, i can set value of var via method:
fnc.setvar("abc");
or
fnc.var = "abc";
I can also get it directly:
console.log(fnc.var)
or via get method:
console.log(fnc.getVar())
Here comes the question:
If the result is the same which option is better? what are the pros and cons for direct or method way?
This highly depends on the features and patterns used in a given language.
Behaviour driven languages
In Java or C++ classes are defined by their behaviour, read "methods". The interfaces and the whole inheritance are based on methods. Fields are 2nd class citizens. Therefore you use methods to get and set attributes. This is the only way of overriding the access and ensuring the integration is correct after you change something later on. Having all fields hidden behind methods also enables you finer grained control (for example getter without a corresponding setter, or a setter that does a calculation instead of simply setting an attribute), but you need a lot of boilerplate, so you write lots of code that does not really add to your business logic and makes the code harder to read from within the class. What makes the code harder to read, however, makes it easier to understand from the client-side through interfaces, as they fully define a class. This concept of methods over attributes usually comes along with visibility settings for methods and attributes. This way you define what is meant for outside world and what is meant for this class or package only. Attributes are almost always private (read "for this class only").
Property driven languages
In languages like JavaScript or Python classes/objects are defined by their fields, read "attributes". Even methods are nothing more than attributes and so both methods and attributes can be overriden (or hidden), switched at runtime etc. Given that you gain nothing but false security using getters and setters, and given that every function call less means better performance and shorter stacktrace, using fields directly is the preferred usage in scripting languages. Regarding readability: the code itself is much easier to read and to understand, but interfaces as known from behaviour based languages don't exist here except in form of documentation (if the code author writes one). Visibility of methods and attributes is usually always public, but some languages offer special annotations or naming schemas to show which methods or fields are meant to be private. There is no strong or no enforcement at all though.
BTW-JFYI: Python has a special solution for the extendability of fields: properties. This is a special thing which enables you using getter and setter with proper logic inside the class but present the field as plain attribute to the outside world. See Python #property versus getters and setters for further reading.
Don't consider the immediate result only. Most software is going to be modified at some point. Considering that, you are more flexible when using getter and setter methods as opposed to direct attribute access.
However the best option - if applicable - is to not use setters at all but create immutable objects.

Is it possible to change an Objective-C object to a different type at runtime?

I have a situation where I want to create an object before I know what type it will eventually be. I know what its superclass will be, and want to temporarily create a concrete instance of that superclass and allow other objects to use it in that form until its "true" class can be created.
I realize this is pretty crazy and I don't have too high expectations that this is possible, but if I could do this it would be amazing. I know the Obj-C runtime has some pretty powerful features so thought it was at least worth asking.
I've looked into object_setClass, but while this appears to allow you technically change the class of an object at runtime, it doesn't allow you to actually reallocate a new instance, complete with its own ivars, at the address of the original instance, which is really what I need as I don't know specifically what the final class will be (it needs to work with any custom subclass).
Background: My intention is to provide a placeholder object that will allow external code to register dependencies and/or hold a reference to, such that when the object is eventually filled-in, those external dependencies will still hold and they won't have to correct their references.
You could try using NSProxy and ultimately proxying to the "real" underlying object you need.

Best way to define an immutable class in Objective C

I am a newbie in Objective C and I was wondering what is
the best way to define an immutable class in Objective-C (like NSString for example).
I want to know what are the basic rules one has to follow to make a class immutable.
I think that :
setters shouldn't be provided
if properties are used, they should be readonly
to "disable" Key Value Coding , accessInstanceVariablesDirectly must be override and return NO
Did I forget something ?
Thanks
The first and foremost thing you should do is to include usage comments in your .h file that explain that this is an immutable class, along with the class's purpose and general usage guidance. Far too often people go to great lengths to try to "enforce" with the compiler what could be achieved by just informing the caller.
You should certainly not provide public setters or readwrite properties if you intend the class to be immutable (but of course you should provide private setters so that you can use accessors within the class; you should always avoid, even internally, messing with ivars directly except in a few places). I guess you could add your accessInstanceVariablesDirectly override if you saw this as a likely error on the part of the caller.
But the key to understanding Objective-C is to understand and embrace the fact that the caller is not the enemy. The called code does not need to be "protected" from the caller. The caller needs to be protected from likely error. Everyone is on the same side here; caller and called want the program to work.
The caller is the customer and should be treated as such. The customer is not always right, but the customer is always the customer. Sometimes that means protecting the customer from himself if there is an easy mistake he might make. NSAssert() is particularly useful for that. And providing public setters to an immutable class is almost tricking the caller into making a mistake, so that would be bad for everyone.
In any case, you shouldn't make your class overly complex to try to enforce immutability. The caller can almost (*) always violate encapsulation by accessing the struct directly (object->ivar). The caller would be foolish to do so, but you would be even more foolish to try to prevent it. Note the immutability, hide your setters and mark your properties readonly, and in almost all cases you should be fine.
(*) Yes, it's possible to even more hide your data by nesting a private struct/object as an ivar, but then the caller can still modify the data with pointer arithmetic so it's still not "enforced." Always ask yourself what problem you're really trying to solve.
I believe they way I'd accomplish this is to have the header file contain only the publicly needed information. The rest would go in to the source file to limit possible override exposure.
Since Objective-C apparently has no definitive way of defining a class as final (sealed, etc), everything you'd be able to do isn't really all encompassing.
I've long ago came to the conclusion that you really can't use Objective-C like you'd use Java, C++ or C#. Objective-C is simply too different. In fact I believe there are drastic paradigm differences such as static vs. dynamic method dispatch/calls.
The reason I mention this is because perhaps no class in Objective-C is truly final. Perhaps this is by language design and not something you should try to get around. If you do, you'd ultimately needlessly complicate your code.

Correct OOP design without getters?

I recently read that getters/setters are evil and I have to say it makes sense, yet when I started learning OOP one of the first things I learned was "Encapsulate your fields" so I learned to create class give it some fields, create getters, setters for them and create constructor where I initialize these fields. And every time some other class needs to manipulate this object (or for instance display it) I pass it the object and it manipulate it using getters/setters. I can see problems with this approach.
But how to do it right? For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument? Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object.
Can you suggest some good resources where best practices in OOP design are presented? I'm planning to start a project in my spare time and I want it to be my learning project in correct OOP design..
Allen Holub made a big splash with "Why getter and setter methods are evil" back in 2003.
It's great that you've found and read the article. I admire anybody who's learning and thinking critically about what they're doing.
But take Mr. Holub with a grain of salt.
This is one view that got a lot of attention for its extreme position and the use of the word "evil", but it hasn't set the world on fire or been generally accepted as dogma.
Look at C#: they actually added syntactic sugar to the language to make get/set operations easier to write. Either this confirms someone's view of Microsoft as an evil empire or contradicts Mr. Holub's statement.
The fact is that people write objects so that clients can manipulate state. It doesn't mean that every object written that way is wrong, evil, or unworkable.
The extreme view is not practical.
"Encapsulate your fields" so I learned to create class give it some fields, create getters, setters
Python folks do not do this. Yet, they are still doing OO programming. Clearly, fussy getters and setters aren't essential.
They're common, because of limitations in C++ and Java. But they don't seem to be essential.
Python folks use properties sometimes to create a getter and setter functions that look like a simple attribute.
The point is that "Encapsulation" is a Design strategy. It has little or nothing to do with the implementation. You can have all public attributes, and still a nicely encapsulated design.
Also note that many people worry about "someone else" who "violates" the design by directly accessing attributes. I suppose this could happen, but then the class would stop working correctly.
In C++ (and Java) where you cannot see the source, it can be hard to understand the interface, so you need lots of hints. private methods, explicit getters and setters, etc.
In Python, where you can see all the source, it's trivial to understand the interface. We don't need to provide so many hints. As we say "Use the source, Luke" and "We're all adults here." We're all able to see the source, we don't need to be fussy about piling on getters and setters to provide yet more hints as to how the API works.
For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument?
Good idea.
Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object.
That's why the Render object is separate. Your design is quite nice.
No reason why a Person object can't call a general-purpose renderer and still have a narrow set of responsibilities. After all the Person object is responsible for the attributes, and passing those attributes to a Renderer is well within it's responsibilities.
If it's truly a problem (and it can be in some applications), you can introduce Helper classes. So the PersonRenderer class does Rendering of Person data. That way a change to Person also requires changes to PersonRenderer -- and nothing else. This is the Data Access Object design pattern.
Some folks will make the Render an internal class, contained within Person, so it's Person.PersonRenderer to enforce some more serious containment.
If you have getters and setters, you don't have encapsulation. And they are not necessary. Consider the std::string class. This has quite a complicated internal representation, yet has no getters or setters, and only one element of the representation is (probably) exposed simply by returning its value (i.e. size()). That's the kind of thing you should be aiming for.
The basic concept of why they are considered to be evil is, that a class/object should export function and not state. The state of an object is made of its members. Getters and Setters let external users read/modify the state of an object without using any function.
Hence the idea, that except for DataTransferObjects for which you might have Getters and a constructor for setting the state, the members of an objects should only be modified by calling a functionality of an object.
Why do you think getters are evil? See a post with answers proving the opposite:
Purpose of private members in a class
IMHO it contains a lot of what can rightfully be called "OOP best practices".
Update: OK, reading the article you are referring to, I understand more clearly what the issue is. And it's a whole different story from what the provocative title of the article suggests. I haven't yet read the full article, but AFAIU the basic point is that one should not unnecessarily publish class fields via mindlessly added (or generated) getters and setters. And with this point I fully agree.
By designing carefully and focusing on what you must do rather than how
you'll do it, you eliminate the vast majority of getter/setter methods in
your program. Don't ask for the information you need to do the work;
ask the object that has the information to do the work for you.
So far so good. However, I don't agree that providing a getter like this
int getSomeField();
inherently compromises your class design. Well it does, if you haven't designed your class interface well. Then, of course, it might happen that you realize too late that the field should be a long rather than an int, and changing it would break 1000 places in client code. IMHO in such case the designer is to blame, not the poor getter.
In some languages, like C++, there's the concept of friend. Using this concept you can make implementation details of a class visible to only a subset of other classes (or even functions). When you use Get/Set indiscriminately you give everyone access to everything.
When used sparingly friend is an excellent way of increasing encapsulation.
Assume you have many entity classes in your designs, and suppose they have a base class like Data. Adding different getter and setter methods for concrete implementations will pollute the client code that uses these entities like lots of dynamic_casts, to call required getter and setter methods.
Therefore, getter and setter methods may remain where they are, but you should protected client code. My recommendation would be to apply Visitor pattern or data collector for these cases.
In other words, ask yourself why do I need these accessor methods, how do I manipulate these entities? And then apply these manipulations in Visitor classes to keep client code clean, also extend the functionality of entity classes without polluting their code.
In the following paper concerning endotesting you'll find a pattern to avoid getters (in some circumstances) using what the author calls 'smart handlers'. It has a lot in common with how Holub approaches avoiding some getters.
http://www.mockobjects.com/files/endotesting.pdf
Anything that is public is part of the API of the class. Changing these parts may break other stuff, relying on that. A public field, that is not only connected with an API, but with internal representation, can be risky. Example: You save data in a field as an array. This array is public, so the data can be changed from other classes. Later you decide to switch to a generic List. Code that use this field as an array is broken.

Abstract design / patterns question

I had a bunch of objects which were responsible for their own construction (get properties from network message, then build). By construction I mean setting frame sizes, colours, that sort of thing, not literal object construction.
The code got really bloated and messy when I started adding conditions to control the building algorithm, so I decided to separate the algorithm to into a "Builder" class, which essentially gets the properties of the object, works out what needs to be done and then applies the changes to the object.
The advantage to having the builder algorithm separate is that I can wrap/decorate it, or override it completely. The object itself doesn't need to worry about how it is built, it just creates a builder and 'decorates' the builder with extra the functionality that it needs to get the job done.
I am quite happy with this approach except for one thing... Because my Builder does not inherit from the object itself (object is large and I want run-time customisation), I have to expose a lot of internal properties of the object.
It's like employing a builder to rebuild your house. He isn't a house himself but he needs access to the internal details, he can't do anything by looking through the windows. I don't want to open my house up to everyone, just the builder.
I know objects are supposed to look after themselves, and in an ideal world my object (house) would build itself, but I am refactoring the build portion of this object only, and I need a way to apply building algorithms dynamically, and I hate opening up my objects with getters and setters just for the sake of the Builder.
I should mention I'm working in Obj-C++ so lack friend classes or internal classes. If the explanation was too abstract I'd be happy to clarify with something a little more concrete. Mostly just looking for ideas or advice about what to do in this kind of situation.
Cheers folks,
Sam
EDIT: is it a good approach to declare a
interface House(StuffTheBuilderNeedsAccessTo)
category inside Builder.h ? That way I suppose I could declare the properties the builder needs and put synthesizers inside House.mm. Nobody would have access to the properties unless they included the Builder header....
That's all I can think of!
I would suggest using Factory pattern to build the object.
You can search for "Factory" on SO and you'll a get a no. of questions related to it.
Also see the Builder pattern.
You might want to consider using a delegate. Add a delegate method (and a protocol for the supported methods) to your class. The objects of the Builder class can be used as delegates.
The delegate can implement methods like calculateFrameSize (which returns a frame size) etc. The returned value of the delegate can be stored as an ivar. This way the implementation details of your class remain hidden. You are just outsourcing part the logic.
There is in fact a design pattern called, suitable enough, Builder which does tries to solve the problem with creating different configurations for a certain class. Check that out. Maybe it can give you some ideas?
But the underlying problem is still there; the builder needs to have access to the properties of the object it is building.
I don't know Obj-C++, so I don't know if this is possible, but this sounds like a problem for Categories. Expose only the necessary methods to your house in the declaration of the house itself, create a category that contains all the private methods you want to keep hidden.
What about the other way around, using multiple inheritance, so your class is also a Builder? That would mean that the bulk of the algorithms could be in the base class, and be extended to fit the neads of you specific House. It is not very beautiful, but it should let you abstract most of the functionality.