I know one of the goals of pure functional programming is to eliminate mutability, and therefore to preclude side-effects. But let's face it, Java is not a functional language even with all of the functional-programming libraries that exist. In fact it seems that some of the FP-libraries know and expect this. For instance in Functional Java, there is the Effect class. In the Jedi FP library, there is the Command interface. This allows you to -- among other things -- apply a command pattern with type-safety to elements of an Iterable without the nasty for-loop boilerplate.
Command<PhoneNumber> makeCall = new Command<PhoneNumber> {
public void execute(PhoneNumber p) { p.call(); }
}
List<PhoneNumber> phoneList = ...
FunctionalPrimitives.forEach( phoneList, makeCall );
So the question is, is there anything like that in Guava?
EDITED AFTER ANSWER ACCEPTED FOR CLARIFICATION
I am developing a framework that helps with the "vertical problem" inherent in most Java FP-libraries, under a certain set of circumstances. So I would not actually make the code example as shown above: i.e., explicitly declare a new class implementation of Command with all of its vertical-noise icky-ness, simply for the purpose of immediately applying it right after the declaration.
I was thinking more along the lines of the actual command pattern, where there may be several possible commands declared elsewhere, and only one of them gets passed into the code which wants to apply it iteratively. Furthermore, the goal of my framework is to make it more idiomatic to create functional-interface objects (functions, predicates, commands, other simple lambdas) without simply moving the vertical problem elsewhere. I have long realized this is not within the scope of Guava. But as Command-like interface are available in other FP libraries, I just wanted to know if an analog existed in Guava.
A more complete code example, using my framework, might be something like this:
class Stuff {
private final Stuff CALLS_TO = callsTo(Stuff.class); // a proxy
public static final Command<Stuff> CMD1 = commandFor(CALLS_TO.someMethod1());
public static final Command<Stuff> CMD2 = commandFor(CALLS_TO.someMethod2());
// methods exist for use elsewhere, but are conveniently also wrapped as commands
public void someMethod1() {...}
public void someMethod2() {...}
}
class Activity {
public void handleIt(List<Stuff> stuffs, Command<Stuff> doCmd) {
doSomeThings();
...
forEach(stuffs, doCmd);
...
doOtherThings();
}
}
Nope!
Kevin Bourrillion, the Guava project lead, has said on Guava's functional features:
“The syntax sucks. At the same time, this stuff is now, has always been and will always be nothing but a stopgap measure until the right language change can come along, at which time we can finally really decide on the optimal syntax and have functional-style programming start actually making lives better in Java for once. So I’m undecided how much effort to put into the Function/Predicate stuff; it’s in the library more because it sort of had to be, not so much because we think it’s a crown jewel.”
We will probably change our strategy significantly when Java 8 comes along, but that won't be for a while yet.
Also, we haven't found many use cases for which we think the Command interface you describe would be the best solution. For example, we think that your above code would be much better written as
for(PhoneNumber phone : phoneList) {
phone.call();
}
the old-fashioned way. We could potentially be convinced of the merit of Command, but I think the "for-each" use case is almost always better done the old-fashioned way.
Related
First question here, so hopefully I'm not committing too many faux pas at the moment
The quick version: I want to save typing time by creating "shorthands" for an arbitrary (but known) field within an object's aggregation. (I think I'm saying that right -- still grasping certain terminology)
I'm not sure if there's a better/more accurate terminology for what I'm looking for here, and nothing I've come across has specifically mentioned this concept in Java (though I could have entirely missed something crucial in my search, and I feel that even though my familiarity is with Java, this question is probably more open to the world of OOP in general).
I'm pretty sure that if I got tired of writing, say:
MyClass myClass = new MyClass();
// ... more code ....
// This is a specific string I need to print out for "Foo"
if(reasonToFoo) {
System.out.println(myClass.getSomeObject().getSubObject1().getDescription());
}
I feel as though I have two options: I can make a little helper function in the same class to "wrap" around that uglyish chain of object references, making it simpler for me to type out later:
public String getFooString() {
return this.getSomeObject().getSubObject1().getDescription();
}
// ... elsewhere ...
if (reasonToFoo) {
System.out.println(getFooString());
}
My alternative is to create a helper object that's sole purpose is to simplify snagging that same string
class FooString {
public static String getFrom(MyClass mC) {
return mC.getSomeObject().getSubObject1().getDescription();
}
}
// ... elsewhere ...
if(reasonToFoo) {
System.out.println(FooString.getFrom(this));
}
My questions are:
Do my approaches here effectively solve the "how" of the problem? As in, am I employing reasonable OOP practices in my solutions?
I'm having a hard time seeing a lot of the cases for "why" -- why would I want to use one version of dealing with this problem over any of the others? Are any of these implementations inherently worse than the others?
[EDIT]: Just realized I should probably not be accessing the objects within the instance of MyClass directly, and via getters instead. Editted accordingly
Background: I've dabbled in writing code in various forms and languages since the early 2000s (beginning with TI-83 BASIC, extending through some basic HTML/JS/CSS of that period, moved on for a period with ActionScript 3 and scripting in mIRC, before moving on to Java and Python) and am now a 28 year old freshman in college trying to get a better grasp on the design-side of programming while angling towards indie game development as a dream job (with the realization that a cubicle farm programming job is more realistic for paying the bills).
From the object oriented point of view your code is violating the Law of Demeter It's good to ask the myclass itself to give the required description.quoting from this blog.
If in code it looks like this
public class A
{
public void someMethod(B b)
{
b.getC().getD().getE().doThing();
}
}
its good to change that to
public class A
{
public void someMethod(B b)
{
b.doThing();
}
}
EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.
Each method in Facade Object is combination of several other methods exposed in several interfaces. Over the period of time this object will also grow as we will come to know about different operations that can be achieved by combining different interfaces available in complex system and its method.
My question is simple:
1) It is a better option to go ahead with Facade or do we have some other option available? because as we increase the number of methods to accommodate each new operation in Facade object, it also becomes complex. A possible solution that I can think of is to create one more Facade
2) Also, is there a limit-on methods exposed by facade when we will say it become complex?
Update: my analysis says stop adding more method to a Facade if it is making hard to understand and rethink your design; is that it?
Since your question is very abstract, it's hard to answer it in a way that is guaranteed to be good for the specifics of what you're writing.
As far as I can tell, the question you're asking is really, if you have
interface A { public void a(); }
interface B { public void b(); }
class ABFacade {
private final A a = ...
private final B b = ...
public void ab() { a.a(); b.b(); }
}
then is that useful or not?
The answer is going to depend on
The problem domain - how well defined is it?
How you name things - will people understand it?
Code reuse - is there more than one thing that will ever need to call a facade method?
I don't think there is a single right answer - at least not with specific examples. It also depends on what the purpose for using this pattern is - better code reuse? Fewer sets of duplicate code that does something complex? Creating choke points all code that does X must pass through? Clarity for other developers? The answers to that question profoundly affects what your code should look like.
I can suggest some general things that might help result in something useful:
If a facade method will only be used in one place, it probably does not deserve to be in the facade - if it the code only has one client, it probably makes more sense to do all the steps inline
Can some operation on the facade be given clear naming? Would the result be more intuitive to use than writing out everything the facade does? If so, then that probably should be on the facade
At the end, it's just a pattern. If it lets you write smaller, better or more reliable software, use it; if it doesn't, don't bother.
I'm a Java developer with 7 years of experience but I'm almost entirely new to C++. This isn't homework or even for real paid work. I'm just delving into C++ and having trouble emulating this one particular pattern that I use frequently in Java.
Basically (in Java):
public class ExampleManager
{
private static Example _example;
public static Example getExample()
{
return _example;
}
public static void setExample(Example example)
{
_example = example;
}
}
I've so far tried about four variants with what I've learned about C++. I found that passing 'example' with the same syntax gets me a copy of 'example' stored in the class. I understand most of the logic behind pointers, just not a lot of the specifics. This example would go a long way to help me with that.
If someone could give me equivalent C++ code to this so that I can break it down line by line and step through it, I would appreciate it very much.
I don't use this pattern as is in Java, but its the bones of the pattern I use to maintain thread safe access to single instance members.
The basically equivalent code in C++ would be this:
class ExampleManager
{
private:
static std::shared_ptr<Example> _example;
public:
static std::shared_ptr<Example> getExample()
{
return _example;
}
static void setExample(std::shared_ptr<Example> example)
{
_example = example;
}
};
It makes use of the std::shared_ptr class, which does most of the memory handling stuff for you (you only have to new objects, basically just like in Java).
We do not use "raw" pointers (i.e. Example *) here; usage of "raw" pointers is usually frowned upon (unless you're working in an environment with limited resoures, or close to hardware), since it gains you little in terms of performance but can lead to ugly problems (memory leaks, double deletions, ...) if not considered carefully.
Please note that the shared_ptr used above is only part of the standard since C++11. Most halfway recent compilers will already accept its usage like shown above; for some a bit older ones you might have to do special things:
e.g. for g++ <= 4.6, add -std=c++0x to compilation command line
for some you might have to use std::tr1::shared_ptr
if both of the above options fail, you can use boost::shared_ptr from the boost libraries.
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.