Sunday, June 21, 2009

Functional/Pure OO Programming

I saw an article about this a while ago and while somewhat interesting, I didn't really put too much stock into it as that wasn't how we were doing things on my one project as work that uses Java. Yesterday, I saw this on stackoverflow: http://stackoverflow.com/questions/1008803/how-to-use-pure-in-d-2-0

Needless to say, it got me thinking about this more. I guess it's the difference between something written up as theory vs. a real-world solution to a problem. Also, in my mind, having an example in a language that actually cares about purity reinforces this.

Right now I'm contemplating the best way to do this based on the examples that were provided in DK's reply. I'm leaning towards the second for a couple reasons.
  1. I think it's cleaner to do all the data manipulation before you create the new object, not after.
  2. The second solution can provide better encapsulation. You see, in the first example, it's assumed you can manipulate the variables in the class directly, which could lead to other types of errors if one is not careful. By manipulating the data strictly within a method and passing the new data into the constructor, I believe it will be safer and more reliable.
Granted, I do see the concern that without a really good garbage collector, you are create a lot of "garbage" when you do this, but I guess you have to weigh that against the benefits you get by having code that's safer to run in a multi-threaded environment.

Of course, if you're doing this in C++, memory management could be an issue if you're not careful. On the other hand, if you know what you're doing the code could still be quite efficient. In my opinion, the best solution here is to put the results into a temp variable, delete the original variable, and then assign the new class instance to the original variable. Not exactly the most efficient thing to do when you think about it. Perhaps we could see some better efficiency if we use a pool of objects and periodically clear out unused instances when you hit the end of the pool?

Food for thought.

Labels: , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home