How can Object Oriented code use functional principles?

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Prelates, Moderators General

How can Object Oriented code use functional principles?

Postby mister_m » Wed Oct 05, 2011 6:10 am UTC

I read in various places that the best programmers know how to maximize functional principles when writing Object Oriented code. That is great, but unfortunately, examples are never really cited. Could someone give me some insight into what this means exactly? What are some examples of functional principles that can be applied in a beneficial way to object oriented code? Unfortunately it is hard for me to really ask a specific question, as I can't really explain what I am after.

Off the top of my head, one thing that I have encountered would be the Comparator interface in Java, where you write a class that implements the Comparator interface (which consists of a compare function), and then pass that Comparator object to a sort function.

Thanks guys.
User avatar
mister_m
 
Posts: 33
Joined: Fri Feb 04, 2011 2:51 am UTC

Re: How can Object Oriented code use functional principles?

Postby Jplus » Wed Oct 05, 2011 11:04 am UTC

I must say that I find the point a bit moot. OO and functional programming are more or less orthogonal to each other, i.e. you can apply OO techniques both to procedural and to functional code. Of course it depends a bit on the language, and historically OO is more related to procedural, but the relation isn't strictly inherent to the nature of the pradigms.

Apart from the taxonomical aspects, I think it's nonsense that one should always try to apply functional techniques, just like it's nonsense that you should always apply OO techniques or even structural programming. Just use the techniques that suit your needs best (and for that matter, use the language that suits your needs best).

Edit because of accidental post:
But to give more of an answer to your question: in a strictly procedural+OO lanuage you might see functional aspects when working with function objects (which correspond to closures in functional languages), and simply when passing around functions as arguments to other functions.
Feel free to call me Julian. J+ is just an abbreviation.
Image coding and xkcd combined
User avatar
Jplus
 
Posts: 1560
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: classified

Re: How can Object Oriented code use functional principles?

Postby Cleverbeans » Thu Oct 06, 2011 12:56 am UTC

I would interpret the statement to mean that they would minimize state data as much as possible, only using it when it provides some direct benefit, and when it is used, that it is as tightly scoped as possible. MIT Opencourseware has this lecture which I feel summarizes nicely the tradeoffs you make when introducing state data. As a default I write all my code functionally, only introducing concepts from OOP as required, and I believe this is likely why I spend significantly less time debugging than my peers.
"Labor is prior to, and independent of, capital. Capital is only the fruit of labor, and could never have existed if labor had not first existed. Labor is the superior of capital, and deserves much the higher consideration." - Abraham Lincoln
User avatar
Cleverbeans
 
Posts: 1307
Joined: Wed Mar 26, 2008 1:16 pm UTC

Re: How can Object Oriented code use functional principles?

Postby bobbysideshow » Mon Oct 10, 2011 11:17 am UTC

Ignoring the whole functions-as-arguments thing... you can as Cleverbeans said try to minimize state data. Broadly speaking, the more methods you write that have no side effects, the easier your code will be to read. Within reason.

An example would be a recursive tree lookup function, I'd say that was quite 'functional' in style, although it works on a structure of objects.

Code: Select all
int tree::find(x)
{
  if (leaf)
    return value;
  else
  {
    if (x<key)
      return find(left);
    else
      return find(right);
  }
}
bobbysideshow
 
Posts: 2
Joined: Mon Oct 10, 2011 11:03 am UTC

Re: How can Object Oriented code use functional principles?

Postby OmenPigeon » Tue Oct 11, 2011 3:00 am UTC

If you push the idea of 'minimize state' a little farther, you end up at immutable objects. They're pretty common in functional languages (I think Haskell and most/all of the ML family treat variables as immutable by default), but they can be super useful in OO code too. Most OO languages have immutable string objects, for example (Ruby is the notable exception I can think of). You get huge benefits in terms of how easy it is to reason about your code when you're dealing with strictly immutable objects. Consider the following pseudocode:
Code: Select all
define foo(arg):
    temp = arg
    bar(arg)
    assert_equal(temp, arg)


If arg is an immutable type, we know the assertion will always pass. No matter what bar() does, it can't modify arg, only make copies of it. If arg is a mutable type, then we can't know whether the assertion will pass without also knowing the entire implementation of bar() and everything it calls. I once spent several person-days digging through around a dozen KLOC whose original authors were sadly missing to ensure that a set of objects weren't changed by any of the functions that used them so that I could reorder some method calls near the top of the code. Not pleasant, and could have been avoided my type system could have assured me that the types were immutable.

Another thing that I've noticed myself doing differently after spending more time working in functional code is paying a lot more attention to the order of arguments to my functions. When I have partial application and currying it makes a lot of difference to my future happiness whether I make a function map(func, list) or map(list, func). The first is more often reusable. It doesn't come up as often in OO code, but I like being able to voice a reason why my arguments in in a particular order.

Fundamentally, a lot of what gets lumped together as 'functional' style are techniques and language features that tend to make it easier to reason more clearly about code. Part of this is because a lot of functional languages can trace their ancestry back to lisp, which (especially when expressed as Scheme) is pretty close to raw lambda calculus. Part of it is because functional languages, historically, have been more popular in academia, where being able to reason about a program is often more important than getting it shipped for the Q3 sales cycle. And part of it is because those things do actually tend to make it easier to reason about the code.
As long as I am alive and well I will continue to feel strongly about prose style, to love the surface of the earth, and to take pleasure in scraps of useless information.
~ George Orwell
User avatar
OmenPigeon
Peddler of Gossamer Lies
 
Posts: 673
Joined: Mon Sep 25, 2006 6:08 am UTC

Re: How can Object Oriented code use functional principles?

Postby Yakk » Tue Oct 11, 2011 3:43 am UTC

Minimize state, and make it clear what your state is.

When your code uses lots of state, to understand what your code does, you must understand all of the state it interacts with.

When your code uses minimal state, to understand what your code does, you must only understand the minimal state it interacts with.

Immutable objects have less state. Pure functional functions have less state. Objects with fewer member variables have less state. Objects with const member variables and const methods have less state.

Pointers that are reference counted have less state (the alternative is that to understand if the code is valid, you must know if what you are pointing to has been deallocated yet, which requires understanding every single interaction with that pointer or whatever it was assigned from, or wherever it is assigned to, and knowing every such location that whatever is pointed to could be invalidated.)

Garbage collected pointers have less state (reference counted pointers require that you know if there is a loop). Edit: but garbage collected data has more state, because you don't know when it will be cleaned up (it will be cleaned up as "some point" when the last reference is gone, and the GC thread has decided to bother cleaning it up).
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10454
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: How can Object Oriented code use functional principles?

Postby MHD » Fri Oct 14, 2011 11:25 am UTC

The real issue here is that Java isn't Object Oriented. It is Imperative with compartmentalized state that works sort-of like OO.
A "real" OO language, like Smalltalk embraces the beauty of Object Orientation, which is "For every problem build the tools you need to solve it with, then solve it." If your problem is something that needs functional code, you build tools to do that.
EvanED wrote:be aware that when most people say "regular expression" they really mean "something that is almost, but not quite, entirely unlike a regular expression"
User avatar
MHD
 
Posts: 631
Joined: Fri Mar 20, 2009 8:21 pm UTC
Location: Denmark

Re: How can Object Oriented code use functional principles?

Postby Yakk » Fri Oct 14, 2011 1:13 pm UTC

Java isn't a true scotsman either.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.
User avatar
Yakk
Poster with most posts but no title.
 
Posts: 10454
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove


Return to Coding

Who is online

Users browsing this forum: No registered users and 4 guests