Lambda expression and static or instance fields - java

We know that a lambda expression can refer to and use static instance variables, instance variables and local variables( if they are effectively final). All this seems ok. Whenever I see any session on Lambdas and Java's take on functional programming I see one common point which is "Writing concurrent code is tough and so adapting functional code helps".
However if I can access Static and instance variables in a lambda does this not defeat this point altogether. I know we have parallel streams which are very helpful in certain concurrent case but still is the closure scope not broken in Java if we are going towards functional programming style.
Also we should be creating pure functions in a functional style of programming. However if I am dependent on the state of the instance then my function is not pure.
I might be incorrect in inferring what I have shared but if I am then was there a particular reason to allow these design principles.
public class UsingStaticVariables {
static int staticTest = 10;
public static void main(String args[]) {
staticTest++;
System.out.println("Static test first value is " + staticTest);
Supplier<Integer> supplier = () -> {return staticTest++; };
staticTest++;
System.out.println("Static test second value is " + staticTest);
System.out.println("Static Test lambda output is " + supplier.get());
}
}

if I can access Static and instance variables in a lambda does this
not defeat this point altogether[?]
The ability for lambdas to access static and instance variables does not make the whole feature fail at providing an approach to functional programming. Only when lambdas actually do access such data is pure functional programming violated.
But also, it sounds like you may be working from a false premise. Lambdas provide for more convenient representations of higher-order functions than Java previously had, but there is no reason to take that as a sign of Java moving toward being a pure functional language. I am confident that that will never happen.
I know we have parallel streams
which are very helpful in certain concurrent case but still is the
closure scope not broken in Java if we are going towards functional
programming style.
Nothing requires you to make your lambdas touch anything they cannot reach via their arguments. And avoiding that is a very good idea in lambdas that are going to be shared between threads, but even that doesn't protect you from all the intricacies of multithreaded programming.
Java supports -- even more so nowadays -- multiple programming paradigms and mixed programming paradigms. This is generally a good thing for programmers, which is probably why a lot of programming languages seem to move in that direction, regardless of where they start.
[W]as there a particular reason to allow these design principles[?]
The motivation for most of Java language and standard library development has pretty much always been to make the language easier to use in a variety of ways, for as many programming tasks as possible. Lambdas seem to have been motivated much more by a desire to reduce the importance of anonymous inner classes than by any ideal of providing better support for functional programming style. The FP angle largely comes along for the ride, though the standard library does seem to have really latched on to that.

Related

Why class objects only created dynamically in java?

This question already asked before but I don't find good understandable answer from there.
I would actually want to know that unlike c++ class objects can't be created statically in java why ? and what are the main disadvantages to create objects statically that java designers want to prevent to be occur ?
Thanks.
Good question. One is tempted to say that it is because the
authors of the language knew better than you what value types
you need, and provided them, and didn't want to let you define
new ones (e.g. like Complex). And there's certainly some of
that: it also explains the lack of operator overloading.
But I suspect that that wasn't the reason in the minds of the
Java authors. You need dynamic allocation and pointers (what
Java calls references) in some cases, such as when polymorphism
is involved, and the Java authors simply decided that they would
only support this idiom, rather than making the language more
complex by having it support several different idioms. It's
a pain, of course, when you actually need value semantics, but
with care, you can simulate them (java.lang.String would be
a good example) by making the class final and immutable, with
"operators" which return a new instance.
Of course, the added expressiveness of C++ does give more
possibility for errors: it's easy to take the address of a local
variable, for example, and end up with a dangling pointer. But
just because you can do something doesn't mean that you have to;
in C++, an incompetent programmer can make the program crash
immediately, where as in Java, he'll generally end up with
a wrong result (although uncaught exceptions aren't that rare
either).
Edit: It appears the poster may actually be asking why can't Objects be static in Java?, in which case, the answer is "they can" and I have added that to the answer at the bottom. If however the question is why can't Objects be allocated on the stack as they can in C++ then the first part of this answer attempts to deal with that:
I guess it boils down to the design goals of the Java language.
Because java has a garbage collector it doesn't really need to have stack allocated objects.
Trying to make things simpler, safer, familiar, while keeping them fast and consistent were design goals of the Java language designers.
Quoting from here http://www.oracle.com/technetwork/java/simple-142339.html (emphasis is mine):
Simplicity is one of Java's overriding design goals. Simplicity and
removal of many "features" of dubious worth from its C and C++
ancestors keep Java relatively small and reduce the programmer's
burden in producing reliable applications. To this end, Java design
team examined many aspects of the "modern" C and C++ languages to
determine features that could be eliminated in the context of modern
object-oriented programming.
One of those features that the designers decided was of "dubious worth" (or unnecessarily complicated the language or its Garbage Collection processes) were stack-allocated Objects.
These online chapters cover the design goals of the Java language in-depth.
Reviewing the comments I believe that I may have misinterpretted the original poster's question because the question seems to be confusing the two completely orthogonal concepts of allocating Objects on the stack with statically allocated Objects.
Stack allocation refers to value Objects that exist only within their current scope and occupy space on the stack.
Static allocation refers to instances that exist per Class - Objects that can exist for the lifetime of the application and are initialized within a static allocation block.
Java doesn't support the former concept (except with primitive data types) for the reasons explained above; but it certainly does support the latter. It is perfectly acceptable Java code to instantiate a static Object belonging to a class. A very simple example of a static Class Object would be this snippet of code:
public class Foo {
public static Integer integerValue = new Integer(32);
}
This would create a single public instance of an Integer Object that belongs to the class Foo. Because it is public in this example, one could access it and set it by calling:
Foo.integerValue = 57;
Note that only one (effectively global) copy exists of the integerValue regardless of how many Foo instances are instantiated.
A common use of statics is for class constants (declared with the the final modifier), but static variables in Java do not have to be constant: they are mutable by default if you omit the final modifier. Static variables need to be used with caution in multi-threaded applications, but that's another story.
For more information on static variables in java, you can read about them here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
and here:
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Hopefully the helps.

Java 8 dancing around functions as first class citizens? [duplicate]

This question already has answers here:
Java 8 lambda expression and first-class values
(5 answers)
Closed 8 years ago.
So the functional programmer in me likes languages like python that treat functions as first class citizens. It looks like Java 8 caved to the pressure and "sort of" implemented things like lambda expressions and method references.
My question is, is Java on its way to using first class functions, or is this really just syntactic sugar to reduce the amount of code it takes to implement anonymous classes / interfaces such as runnable? (my gut says the latter).
My ideal scenario
Map<String,DoubleToDoubleFunc> mymap = new HashMap<String,DoubleToDoubleFunc>();
...
mymap.put("Func 1", (double a, double b) -> a + b);
mymap.put("Func 2", Math::pow);
...
w = mymap.get("Func 1")(y,z);
x = mymap.get("Func 2")(y,z);
There is no function structural type in Java 8. But Java has always had first class objects. And in fact, they have been used as an alternative. Historically, due to the lack of first-class functions, what we have done so far is to wrap the function inside an object. These are the famous SAM types (single abstract method types).
So, instead of
function run() {}
Thread t = new Thread(run);
We do
Runnable run = new Runnable(){ public void run(){} };
Thread t = new Thread(run);
That is, we put the function inside an object in order to be able to pass it around as a value. So, first class objects have been an alternative solution for a long time.
The JDK 8 simply makes implementing this concept simpler, and they call this type of wrapper interfaces "Functional Interfaces" and offer some syntactic sugar to implement the wrapper objects.
Runnable run = () -> {};
Thread t = new Thread(run);
But ultimately, we are still using first-class objects. And they have similar properties to first-class functions. They encapsulate behavior, they can be passed as arguments and be returned as values.
In the lambda mailing list Brian Goetz gave a good explanation of some of the reasons that motivated this design.
Along the lines that we've been discussing today, here's a peek at
where we're heading. We explored the road of "maybe lambdas should
just be inner class instances, that would be really simple", but
eventually came to the position of "functions are a better direction
for the future of the language".
This exploration played out in stages: first internally before the EG
was formed, and then again when the EG discussed the issues. The
following is my position on the issue. Hopefully, this fills in some
of the gaps between what the spec currently says and what we say
about it.
The issues that have been raised about whether lambdas are objects or
not largely come down to philosophical questions like "what are
lambdas really", "why will Java benefit from lambdas", and ultimately
"how best to evolve the Java language and platform."
Oracle's position is that Java must evolve -- carefully, of course --
in order to remain competitive. This is, of course, a difficult
balancing act.
It is my belief that the best direction for evolving Java is to
encourage a more functional style of programming. The role of Lambda
is primarily to support the development and consumption of more
functional-like libraries; I've offered examples such as
filter-map-reduce to illustrate this direction.
There is plenty of evidence in the ecosystem to support the hypothesis
that, if given the tools to do so easily, object-oriented programmers
are ready to embrace functional techniques (such as immutability) and
work them into an object-oriented view of the world, and will write
better, less error-prone code as a result. Simply put, we believe the
best thing we can do for Java developers is to give them a gentle push
towards a more functional style of programming. We're not going to
turn Java into Haskell, nor even into Scala. But the direction is
clear.
Lambda is the down-payment on this evolution, but it is far from the
end of the story. The rest of the story isn't written yet, but
preserving our options are a key aspect of how we evaluate the
decisions we make here.
This is why I've been so dogged in my insistence that lambdas are not
objects. I believe the "lambdas are just objects" position, while
very comfortable and tempting, slams the door on a number of
potentially useful directions for language evolution.
As a single example, let's take function types. The lambda strawman
offered at devoxx had function types. I insisted we remove them, and
this made me unpopular. But my objection to function types was not
that I don't like function types -- I love function types -- but that
function types fought badly with an existing aspect of the Java type
system, erasure. Erased function types are the worst of both worlds.
So we removed this from the design.
But I am unwilling to say "Java never will have function types"
(though I recognize that Java may never have function types.) I
believe that in order to get to function types, we have to first deal
with erasure. That may, or may not be possible. But in a world of
reified structural types, function types start to make a lot more
sense.
The lambdas-are-objects view of the world conflicts with this possible
future. The lambdas-are-functions view of the world does not, and
preserving this flexibility is one of the points in favor of not
burdening lambdas with even the appearance of object-ness.
You might think that the current design is tightly tied to an object
box for lambdas -- SAM types -- making them effectively objects
anyway. But this has been carefully hidden from the surface area so
as to allow us to consider 'naked' lambdas in the future, or consider
other conversion contexts for lambdas, or integrate lambdas more
tightly into control constructs. We're not doing that now, and we
don't even have a concrete plan for doing so, but the ability to
possibly do that in the future is a critical part of the design.
I am optimistic about Java's future, but to move forward we sometimes
have to let go of some comfortable ideas. Lambdas-are-functions opens
doors. Lambdas-are-objects closes them. We prefer to see those doors
left open.
They are not really first-class functions IMO. Lambda is ultimately an instance of a functional interface. But it does give you advantages of a first-class function. You can pass it as an argument to a method that expects an instance of functional interface. You can assign it to a variable, in which case its type will be inferred using target typing. You can return it from a method, so on.
Also, lambdas doesn't completely replace anonymous classes. Not all anonymous classes can be converted to lambdas. You can go through this answer for a nice explanation about difference between the two. So, no lambdas are not syntactic sugar for anonymous classes.
It's not syntactic sugar for anonymous classes; what it compiles to is somewhat more involved. (Not that it would be wrong to do that; any language will have its own implementation detail for how lambdas are compiled, and Java's is no worse than many others.)
See http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html for the full, nitty-gritty details.
interface DoubleDoubleToDoubleFunc {
double f(double x, double y);
}
public static void main(String[] args) {
Map<String, DoubleDoubleToDoubleFunc> mymap = new HashMap<>();
mymap.put("Func 1", (double a, double b) -> a + b);
mymap.put("Func 2", Math::pow);
double y = 2.0;
double z = 3.0;
double w = mymap.get("Func 1").f(y,z);
double v = mymap.get("Func 2").f(y,z);
}
So it still is syntactic sugar and only to some degree.

Are functions only in non-object-oriented languages? [duplicate]

This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed 9 years ago.
I was asked to answer this question:
Where should I put the Javadoc specific comment notation of /** and */
if I want to tell the user specifics about a certain instance variable
or method?
I answered with:
Above the function declaration.
The answer was rejected and this was the reason:
Functions are in non-object-oriented languages. Method is the proper name.
Is this true?
Are functions found only in non-object-oriented languages?
No. There are object-oriented languages that have functions. C#, for example, is an object-oriented language but it has anonymous functions.
What are the named procedures which are members of a type typically called in object-oriented languages like Java or C#?
Typically they are properly called methods, though this differs from language to language. In Java or C# I would say "method".
In Visual Basic, for example, the distiction is made between functions and subroutines on the basis of whether or not they return a value, not on the basis of whether they are associated with a type container.
JavaScript, an object-oriented language which uses prototype inheritance rather than class inheritance, typically refers to all of the above as "functions".
Do people frequently refer to methods as functions when speaking casually about Java or C#?
Yes. Were I writing documentation or a book or a scholarly article then I would be careful to make the distinction. In commonplace parlance though everyone reasonably conversant with the art of computer programming would understand "function" and "method" to be roughly synonyms. I would not have rejected your answer.
Any answer which limits this to a specific language is inherently flawed. In addition you must also deal effectively with static methods and subroutines.
Computer science began with the term 'subroutine'. Small sections of repeatable code which could be executed arbitrarily to perform a common action. Examples are found in early programming languages such as BASIC.
Functions were the evolution of subroutines. They take arguments and may or may not return a value. They take some concepts from maths - input, translated to a given output.
With objects we need to be able to call actions on objects and we do this be exposing methods. Like functions they take arguments and may or may not return a value.
Static methods are designed to act on all possible objects of a class.
The problem is that, pure object-orientated programming leaves no scope for the definition of functions (or indeed subroutines). And languages that evolve to become object orientated often retain syntax from functions to implement methods.
In Java we resort to using 'Utility' classes to provide functions as public static methods. The Math class in JavaScript is another example of this.
In PHP we tolerate the use of the word function to define methods.
In C++ we see both functions and methods, neither demarcated. Indeed, C++ makes no reference to methods, calling them member functions.
A function is not bound to a class.
A function is something like doStuff();.
A method is like someThing.doStuff(); or SomeClass.doStuff();.
In Java, there is no such thing as a function. They are all methods. i.e.
class Test {
public static void doSomething() {...}
public void otherThing() {...}
public static void main(String[] args) {
doSomething(); //implied Test.doSomething();
}
public Test() {
otherThing(); //implied this.otherThing();
}
}

Is there a java library for function programming?

Has anybody written a library in java that provides mapping functions (such as mapcar from lisp).
I saw this post and few others (such as this one this one), but sadly nothing that I could consider mainstream and/or usable.
There are a few. They are usually described as something like "functional programming in Java" libraries rather than by reference to LISP.
At my company, the functional programming druids settled on Functional Java as their preferred library, although there is a significant and vocal minority who prefer the functional-esque provisions in Guava.
Guava is a very mainstream and popular library; it's firmly in the "nobody got fired for using" category. FJ may be less well known, but we're using it pretty happily. We've even forked it so we can help improve it.
You'll be looking forward to Java 8, then! It will have Project Lambda included, which has a much, much nicer syntax for closure-like anonymous classes.† Example:
Iterable<String> strs = ...
Iterable<String> downCased = strs.map(s -> s.toLowerCase());
Any interface with one method (or abstract class with one abstract method) can use this syntax, including Guava's Function and Predicate (though Java 8 has its own Mapper and Predicate interfaces, so these are usable out of the box). In this case Iterable.map is a new extension method that takes a new interface type called Mapper.
If you'd like more examples of Java 8 lambdas, just ask!
† All the usual restrictions of anonymous classes still apply, including that local free variables must be "effectively final". This means you don't have to explicitly tag the variable as final, but you're still not allowed to alter the value.

Java mechanisms at use in lambdaj closures

Lamdbaj allows the definition of closures in the Java language, various examples can be found
here
My question is regarding the underlying Java mechanisms at use, for instance, to define the println closure, the following code is used:
Closure println = closure();
{ of(System.out).println(var(String.class)); }
This closure can be subsequently executed via:
println.apply("foobar");
I am curious as to what mechanisms in Java would allow the call to of(...).println(...) to become associated with the println instance itself.
Naturally, the lambdaj source code is available to read but I was hoping for a slightly higher level explanation if anyone has one. My reflection skills go as far as a bit of introspection and executing methods dynamically.
I am Mario Fusco and I am the main developer of the lambdaj library.
First of all I would like to clarify something: lambdaj is not intended to replace any functional language. As I said last week in my speech at the Jug of Zurich if you have a chance to use Scala, go for it and never look back. Here you can find a resume of my speech where it is clearly stated that:
http://ctpjava.blogspot.com/2009/10/lambdaj-new-trends-in-java.html
I am an happy Scala developer too. But sometimes you are just obliged to develop in Java (in my experience, in the real world, about the 80% of times you cannot choose in which language you have to write your code) and in this case some of the lambdaj features could be helpful (or I hope so). I just wanted to bring to Java some functional features that are totally missing. Of course the result is not completely satisfying mainly due to the limitation imposed by Java itself.
As for the internal lambdaj mechanism, yes it uses a ThreadLocal in order to achieve that result. If you have other questions, curiosities or even better suggestions and constructive critics about lambdaj maybe you could be interested to register yourself to the lambdaj mailing list here:
http://groups.google.com/group/lambdaj
Bye
Mario
Well, of is presumably a static method which is imported statically so it can be called without the enclosing class name. I expect that var is the same. Both methods must return some type which have the methods subsequently called:
public class Printable {
public void println(Var var);
}
public class Fac {
public static Printable of(Object o) {
return new Printable(o);
}
public static Var var(Class<?> clazz) {
return new Var(clazz);
}
}
All of a sudden:
Fac.of(System.out).println(Fac.var(String.class));
Is valid Java. Using static imports, hey presto:
import static Fac.*;
of(System.out).println(var(String.class));
The curly-braces are obviously valid Java as you can add these in any method to aid in defining a lexical sope. This API-design style is called fluent and is best showcased by the JMock testing library.
By the way, if this is supposed to introduce closures to Java, it's quite ridiculous - the syntax is unreadably awful. Their I/O example actually made me laugh out loud. Try Scala!
EDIT - the two println calls are associated I believe because the first sequence of calls allow the library to capture the variables which you have passed in as parameters. These are probably captured in some ThreadLocal structure. When you then call a (also presumably static) println method, the library is using this captured data to actually execute the behaviour at a later point. Also testing related, the EasyMock test framework uses a similar mechanism (which uses Java proxies in the background) to capture expected values.

Categories

Resources