Monday, April 14, 2008

delete(this)

For any given language there are always language features that are considered so 'wrong' that no programmer 'should' use them ever. I've always found this a rather interesting bit of behavior and group think among programmers and it is actually a topic I've used as an interview question in the past.

You can guage someone's perspective on what they think about the 'unholy' language features. If one claims that a methos is always the right solution, or that a feature is always the wrong solution, that tells me something not so great about how flex able in understanding problems someone is... i.e. when presented with a screw do they still try to use a hammer?

Goto is the classic example,.. a dangerous command that comletely breaks OOP if OOP is your hammer. But that isn't the one I wanted to babble about.

Today I realized I was using "delete(this)". It isn't even the first time I've used it in this project. Deleting 'this' is considered one of those no-nos that many say 'well, it just means you structured your program wrong!'... unfortunately people tend to say this without actually knowing the structure, they can simply 'tell' because you came up with the 'wrong ' solution.

In this case, yes, I used it with one particular class. The case? Threaded classes that want to be able to terminate themselves. Nothing else 'owns' the object. Adding a manager (the 'correct' solution) is significant extra complexity, indirection, a bottleneck, and breaks from an event-driven design. The thread class ends up needing to know about the manager, the manager needs to know about the threaded class, you have statefullness to keep in sync, a deeper stack to do anything, and have the potential to introduce all sorts of race conditions. On top of that in order to do it right you need a whole mess of mutexs to make sure that different threaded classes don't screw with the manager's data.

All that to get around 'oh no! delete this is bad!'. And of course, the real problem is going to be the code review...

This also highlights the problem (and advantage) of multi-paradigm languages like c++. You can use any paradigm you like but start mixing them and you run into arguments. On top of that, in order to support so many ways of programming, it implements each of them poorly.

For instance, the delete(this) problem is handled elegantly in ObjC via Retain/Release. I would be surprised if Java didn't have a solution to the situations too. C++? You have to do something 'evil'. Oh well, evil needs luffs too.

1 comment:

Anonymous said...

oh hey, I actually understood some of this one.