views:

301

answers:

4

I'm just checking out anonymous methods (in c#)--part of me likes the flexibility and short-hand, but I'm also concerned that it may make the code harder to read.

It also occurred to me that this construct seems to go against some of the o/o paradigm. Do you consider anonymous methods to be in-line with object oriented principles?

+18  A: 

lambda (anonymous methods) is from the functional paradigm. That doesn't mean it is good or bad! If it fits the problem then use it, if it doesn't don't. OOP is not a goal, good code is the goal. I hate when people try to force a single paradigm down the throat, like in Java for example. C# is going in the right direction (IMHO), so it is becoming a multiparadigm language.

AraK
+4  A: 

If you'd like to think of them with respect to Object Oriented design, they're merely syntactic sugar for some anonymous class which contains a method which gets invoked. In fact, Java does it with the longer winded final class. C# chose the shorter method. Both are valid and well within the bounds of Object Oriented design.

Lambda expressions are also no less Object Oriented than delegates. IMHO, lambda expressions fall into an almost entirely orthogonal study of programming from OOP: functional versus procedural.

So, use the right tool for the job be it lambdas, delegates, anonymous classes, objects, monads, etc ad nauseam. Your goal should be to have the right code to solve the right problem.

sixlettervariables
I think Java bends the concept of lambda. There is no reason why lambda should be considered OO to be good.
AraK
I'll +1 AraK's to emphasize the point that programming is not about a single paradigm.
sixlettervariables
A: 

Interestingly, the C# implementation of anonymous methods sometimes requires the creation of objects due to "closures". Read about it here: http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx

John Fisher
+1  A: 

It doesn't make any sense to me to speak of anonymous functions being "object-oriented" or not "object-oriented." Are variables object-oriented? How about loops? Are exceptions object-oriented?

The label is not a useful thing to apply in this case.

If you think that in some particular case, using an anonymous function to accomplish something makes it harder to read, then don't use one.

mquander
+1 for the emphasis on the fact that functional and object-oriented programming are orthogonal with regard to each other.
Steven Sudit