Avoiding get/set accessors...

Status
Not open for further replies.

lobobo

Ars Scholae Palatinae
778
Hello all,

I took a look at this article linked below...
http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html?page=1

...as I'm trying to determine whether getter/setter accessor methods are good or bad practice. The authors argument makes sense...

To see why, consider that there might be 1,000 calls to a getX() method in your program, and each call assumes that the return value is of a particular type. You might store getX()'s return value in a local variable, for example, and that variable type must match the return-value type. If you need to change the way the object is implemented in such a way that the type of X changes, you're in deep trouble.

If X was an int, but now must be a long, you'll get 1,000 compile errors. If you incorrectly fix the problem by casting the return value to int, the code will compile cleanly, but it won't work. (The return value might be truncated.) You must modify the code surrounding each of those 1,000 calls to compensate for the change. I certainly don't want to do that much work.

...but then that brings me to another question. If this example were true, how would you get X without using an accessor? I guess the goal is not to get X at all, rather, take what I'm trying to do with X and put it in a class method so the class can handle the work internally such that I would no longer need to "get X" outside of the class.

For example, if I have a class called Polynomial (that obviously represents a Polynomial) and I wish to find the derivative of the polynomial, instead of using get accessors to pull out the terms and finding the derivative of each outside of the class, it would be better to call a method such as "GetDerivative()" to return a derivative of the polynomial with the class handling the differentiation internally? I believe the author says this much at the bottom of page 3.

But then there comes some times when I think setters are absolutely necessary/unavoidable. Such as setting the balance on a CreditCard object. I can't see how I could set a balance better than just using a setter and telling the class to set the balance internally doesn't seem like it's any different from using a setter.
 

crxs

Ars Tribunus Militum
2,587
Subscriptor
That example of "int vs. long" is a very poor one, it obfuscates the article's point, one quote on the next page summarizes it well: "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." He is absolutely correct in that, and it's true that this basic principle of object orientation is often ignored in favor of using getters for all attributes and implementing the logic in the client code.

That's a good point, and one worth mentioning, but it's not really about getters and setters, so the focus on them is misguided. The problem lies more in laziness, implementing logic in the area you are currently in anyway instead of sitting back a minute and thinking about where the logic really belongs, and if it can be generalized and made to be reusable.
 
Blacken00100":2lsmpfss said:
Modern refactoring tools make the complaints of "1,000 compile errors" not overly important. Computer are good at boring repetitive tasks, and this is one of them.

Data hiding and the ability to do such things as range checks, etc. within your setter functions greatly outweigh the problems for vi programmers.
++

1) Get an IDE 2) Article is moot.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
Your example of needing to set the balance on a CreditCard class actually leads to the same point about encapsulation. You never set the balance on a credit card - you charge transactions to it (positive or negative - customers can return stuff for refunds), receive payments, and accrue interest. All of these adjust the balance appropriately, but none of them lets a caller explicitly set it.

Phil
 
Blacken00100":hkrehx9a said:
Data hiding and the ability to do such things as range checks, etc. within your setter functions greatly outweigh the problems for vi programmers.
One of the points he is making is that getters/setters greatly reduce "data hiding", and that rather than having a setter which performs some kind of validation, you should instead have methods that have some kind of semantic meaning and maintain invariants that way.

The account/credit card balance is a good example of this. Sure, you could have a setter that ensured that the balance always had the right sense for the kind of account in question, was always within the credit limit, etc.. But the far better solution is to only allow transactions to be posted to the account, and refuse transactions that aren't allowed for whatever reason.
 

w00key

Ars Legatus Legionis
10,102
Subscriptor
Article is nonsense. Exposing a public int and changing it into a long will break all int a = b.value as well. The right way is to just use a getter, but instead of changing the API, add an extra method to get a long as well.


The Java API has a good example how to evolve it: String.charAt and String.codePointAt.

When the language was still young, they thought that 65536 code points is all you'd need. Unfortunately, Unicode expanded way past that limit, with the result that a single character doesn't fit into a char anymore. Instead of breaking everything, the API was extended to add a codePointAt(int) : int function.

The charAt function is now defined as getting a single char from a UTF-16 array, with the supplementary characters represented by surrogate pairs.


When you grow an API, you never break every users code. Without knowing what getX() was, you can never spec out they "right" way to grow it. But if you know what getX() is, the solution is obvious most of the time. One of the most famous getX() limit was the 2GB file size limits for many older programs. Solution: just cap the old API at 2GB and add a 64 bit version of getFilesize(). That's also the cause why so many ancient programs think you have exactly 4GB of free memory if you have more than that available.
 
w00key":2xt6ujy7 said:
Article is nonsense. Exposing a public int and changing it into a long will break all int a = b.value as well. The right way is to just use a getter, but instead of changing the API, add an extra method to get a long as well.
The article isn't nonsense; tell don't ask is a fine design principle.

The Java API has a good example how to evolve it: String.charAt and String.codePointAt.

When the language was still young, they thought that 65536 code points is all you'd need. Unfortunately, Unicode expanded way past that limit, with the result that a single character doesn't fit into a char anymore. Instead of breaking everything, the API was extended to add a codePointAt(int) : int function.

The charAt function is now defined as getting a single char from a UTF-16 array, with the supplementary characters represented by surrogate pairs.
Except that's a horrible example, since code depending on the old behaviour is now broken anyway. At best, it should return the value if it's a non-surrogate, and throw an exception otherwise.

When you grow an API, you never break every users code. Without knowing what getX() was, you can never spec out they "right" way to grow it. But if you know what getX() is, the solution is obvious most of the time. One of the most famous getX() limit was the 2GB file size limits for many older programs. Solution: just cap the old API at 2GB and add a 64 bit version of getFilesize(). That's also the cause why so many ancient programs think you have exactly 4GB of free memory if you have more than that available.
Yes, that's a great way of causing corruption and errors. It's not good for any other purpose.
 

w00key

Ars Legatus Legionis
10,102
Subscriptor
DrPizza":2fqvk4ag said:
The article isn't nonsense; tell don't ask is a fine design principle.

My mistake, the design principle at the end isn't nonsense, but the idea that it's impossible to change exposed elements because it's an accessor is.

DrPizza":2fqvk4ag said:
The Java API has a good example how to evolve it: String.charAt and String.codePointAt.
Except that's a horrible example, since code depending on the old behaviour is now broken anyway. At best, it should return the value if it's a non-surrogate, and throw an exception otherwise.

It works for 99.9% of all strings, and the return values are valid UTF-16 values. The only problem is that it won't display correctly if you output that single char to a device without following it up with the next value.

Python's print to sys.stdout behavior is kinda like what you suggest here: raise an exception whenever you print unprintable stuff. No, that's the worst way to evolve an API, guaranteed to break the simplest programs and get exceptions everywhere.

DrPizza":2fqvk4ag said:
When you grow an API, you never break every users code. Without knowing what getX() was, you can never spec out they "right" way to grow it. But if you know what getX() is, the solution is obvious most of the time. One of the most famous getX() limit was the 2GB file size limits for many older programs. Solution: just cap the old API at 2GB and add a 64 bit version of getFilesize(). That's also the cause why so many ancient programs think you have exactly 4GB of free memory if you have more than that available.
Yes, that's a great way of causing corruption and errors. It's not good for any other purpose.

Better inconsistent than outright broken. Lots of ancient win32 code still work fine, you just have to be careful when you're near the once impossible 2GB limits. Dropping the old API is like releasing 64 bit windows without 32 bits support, you'll have access to as many programs as you would on the DEC Alpha versie of windows :p
 
w00key":3okqgkvm said:
It works for 99.9% of all strings, and the return values are valid UTF-16 values. The only problem is that it won't display correctly if you output that single char to a device without following it up with the next value.
Right, which breaks expectations. It also means that programs might potentially screw up the surrogates if they do some char-by-char processing (e.g. splitting the string between a surrogate pair).

Python's print to sys.stdout behavior is kinda like what you suggest here: raise an exception whenever you print unprintable stuff. No, that's the worst way to evolve an API, guaranteed to break the simplest programs and get exceptions everywhere.
Except it isn't the worst way. It means that programs given the kind of input they were written to handle will continue to work, but it also means that if they're given input they plainly cannot handle (e.g. surrogate pairs) then they will fail harmlessly.

Better inconsistent than outright broken. Lots of ancient win32 code still work fine, you just have to be careful when you're near the once impossible 2GB limits.
In other words, it doesn't work fine. It (to the user) randomly corrupts and destroys data.

Dropping the old API is like releasing 64 bit windows without 32 bits support, you'll have access to as many programs as you would on the DEC Alpha versie of windows :p
Programs that run the risk of randomly corrupting my data due to systemic flaws should not be allowed to run. Bugs are one thing; deliberate design errors are quite another.
 

w00key

Ars Legatus Legionis
10,102
Subscriptor
Yeah yeah, I get it. You want to live in the idealized world that requirements never change, and if they do, *everyone* will just magically recompile or rewrite their programs to cope with it.

"print post.title" raising an exception instead of just using printing � or ? if it's not ASCII friendly is just insanity.


Most people would rather learn to live with limits like no 4GB+ files on FAT32, no 2GB+ AVI's than removing any support for it. And besides, those older tools won't work with your precious oversized data anyway. Showing a maximum of 4GB free space on C:\ in an ancient installer is quite harmless, I'd rather let it be than getting an exception. The get free space function won't magically nuke the partition.


Thank god most APIs are never changed, only extended. I'd rather target posix, win32 and Java that just works since forever than one that requires not only a recompile, but updates to my code as well just because something changed from an int to long.


(There was a very good IBM DeveloperWorks article about how to evolve APIs, but I kinda lost it and can't find it anymore. Does anyone remember the title?)
 
w00key":c5l6ddpf said:
Yeah yeah, I get it. You want to live in the idealized world that requirements never change, and if they do, *everyone* will just magically recompile or rewrite their programs to cope with it.
Better that than they corrupt data.

"print post.title" raising an exception instead of just using printing � or ? if it's not ASCII friendly is just insanity.
Yeah, unless you're redirecting the output into something that actually cares about control characters.

Most people would rather learn to live with limits like no 4GB+ files on FAT32, no 2GB+ AVI's than removing any support for it.
On the other hand, many people were deeply, deeply unhappy that Outlook would create PSTs that broke the 2^31 byte barrier and subsequently corrupted themselves.

And besides, those older tools won't work with your precious oversized data anyway.
That doesn't stop them from fucking it up, though.

Showing a maximum of 4GB free space on C:\ in an ancient installer is quite harmless, I'd rather let it be than getting an exception. The get free space function won't magically nuke the partition.
No, but attempts to copy or append files that only read the first 2 or 4 GB will result in data loss and corruption. I'd rather prevent that than just hope for the best.

Thank god most APIs are never changed, only extended.
Make no mistake: changing charAt to return essentially gibberish (half surrogate pairs) is a change in API, whether you like it or not.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
If you want old stuff that doesn't understand the limits to work it should be run in a sandbox (VM,WoW, the details don't matter) such that the old rules it adhered to are maintained.

This is the only sensible, rational way to do it.

That there are programs which can function (badly but not horrendously) does not mean that this is the way it should be done.

If you desire a function which will silently convert unprintable characters into something printable then spec a function (overload, whatever) that does this and use it properly. 'Retro fitting' the functionality to a function after the event *is* a breaking change, it's just the worst sort: one that turns a previously correct program into one that is incorrect but not safe* in that, on being presented with stuff it does not (and cannot) understand doesn't halt.

* Yes, even if you were writing stuff running a nuclear reactor/pacemaker/space probe. The correct implementation of these is to have multiple programs, upgrade only one at a time and for the system to spot the death of one and use the remainder.
 

pyu

Ars Praefectus
5,108
Subscriptor
I want to but I can't. And I blame whatever process came up with the JavaBean specification. It is a broken implementation of what should have been simply records. You can't get away from 'getters/setters' now because all the other frameworks demand it to exist. Example: Spring (and Guice) abuse the JavaBean spec for dependency injection. Oh noes.

Java is more than a decade old though. If we apply many of the things we learn about writing good code today to it, you will probably get something radically different. Or Scala/Groovy. Ha.
 

THBMan

Ars Legatus Legionis
18,256
Subscriptor
You want to live in the idealized world that requirements never change, and if they do, *everyone* will just magically recompile or rewrite their programs to cope with it.
Actually, I want to live in a world where APIs are broken when necessary and fuck the programs who can't keep up. If charAt is broken, it should be removed. If it gets removed, and that means your app/tool/library fails to work... good. Fix it or become irrelevant. Like DrPizza said, the API changed underneath you anyway, whether you wanted it to or not.
 
Status
Not open for further replies.