Article 51944 CodeSOD: An Ugly Mutation

CodeSOD: An Ugly Mutation

by
Remy Porter
from The Daily WTF on (#51944)

If there's a hell for programmers, it probably involves C-style strings on some level. C's approach to strings is rooted in arrays, and arrays are rooted in pointers, and now suddenly everything is memory manipulation, and incautious printf and memcpy commands cause buffer overruns. I'm oversimplifying and leaving out some of the better libraries that make this less painful, but the roots remain the same.

Fortunately, most of the time, we're not working with that sort of string representation. If you're using a high-level language, like Java, you get all sorts of perks, like abstract string methods, no concerns about null termination, and immutability by default.

In C, a string is just a pointer to a block of memory and you can do anything you like with it. In Java, a string is an object that can't have its contents changed.

Cid has a co-worker that comes from a C background, and constantly equates "references" in Java to "pointers" in C, which is largely accurate, but highlights certain misunderstandings in this case.

Since, obviously, every non-primitive variable is holding an object reference, and it's like pointers, and that means if you mutate the object in one place, it mutates everywhere. Much like a C-string, it's just a pointer to memory and anybody can do anything.

That means, when this developer writes getters and setters for string properties, they want to make sure that nobody's ever sharing a reference. That means thousands of lines of code like this:

public String getValue() { if (value == null) { return null; } else { return new String(value); }}public void setValue(String value) { if (value == null) { this.value = null; } else { if (value.trim().length == 0) { this.value = null; } else { this.value = new String(value); } }}

Every string property gets that treatment, and there are a lot of string properties. It's a great stress test for the garbage collector; there's no reason to spin up extra instances of these immutable objects, but we do it anyway.

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today! TheDailyWtf?d=yIl2AUoC8zA4wNHUrM4AT4
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments