Why the Execute Aroud idiom is not considered a Strategy design pattern? - java

More and more I see new labels for the same solutions but with different names. In this case why we cannot simply say that the Execute Aroud idiom is the same that the Strategy design pattern?
When I read the Jon Skeet’s answer to the question: “What is the “Execute Around” idiom?”, he states that:
it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource".
In this case #jon-skeet uses a executeWithFile(String filename, InputStreamAction action) method as an example of the method that does things which are always required and the interface InputStreamAction as an abstraction over what we want to do with the resource.
public interface InputStreamAction
{
void useStream(InputStream stream) throws IOException;
}
Comparing this with the Stratey design pattern why we cannot just say that the interface InputStreamAction defines a family of algorithms? And, each implementation of the interface InputStreamAction corresponds to a concrete strategy encapsulating an algorithm. Finally these algorithms are interchangeable and we can make use of the executeWithFile with any of those strategies.
So, why can’t I interpret the Jon Skeet’s answer as an example of the application of the Stratey design pattern?
By the way, which of the idioms came first? The Execute Around or the Strategy design pattern?
Although the Execute Around idiom is usually related with a functional style programming, the only documentation that I found about it was in Smalltalk Best Practice Patterns book from 1997 in the scope of the Smalltalk programming language, which follows an OO approach.
Because Design patterns describe general solutions to recurrent problems, then we can say that the Execute Around and Strategy are both the same solution to solve different problems. So, I ask: do we really need a different name to identify the same solution, when it is applied to a different problem?
Although I agree with #iluwatar's answer that this is the way to communicate different ideas, I still think that I could transmit the idea of the Execute Around just telling that: "I used a Strategy to specify what I want to do with a resource, which is always setup and cleaned in the same manner."
So the Execute Around idiom is reducing ambiguity (and that's good), but at same time is proliferating the names of design patterns? And, is that a good practice?

The way I see it, although both may be solutions to similar problems, these are different idioms and, therefore, should have different names.
I call them idioms, because the execute around it's just a programming idiom, used in many typical situations (similar to one presented) and also in several languages. And, at least that I have knowledge, the Execute Around was never formalized as a software design pattern, at least yet.
And why are they different? Here's my view:
The Stategy design pattern is intended to (from Wikipedia):
defines a family of algorithms,
encapsulates each algorithm, and
makes the algorithms interchangeable within that family.
Typically the strategy instance as a long lasting relation with the context instance, typically passed as a constructor dependency. Even though the context may have setters to the strategy, the same strategy can be used in several call to the context, without the caller (client) even not knowing which one is being used by that particular context and at the moment the call was done. Moreover, the same strategy instance may be used by the context in several methods of its public interface, without the caller no even knowing anything about its usage.
On the other hand, the execute around idiom is suited for parameterized algorithms, where the caller (client) should always pass the algorithm parametrization function in each call. Therefore, the strategy function passed, only influences behavior of that particular call, not other calls.
Although the presented differences may seam theoretical and rhetorical, if you put the context being called in a multithreaded scenario, is where I think the differences are more obvious and easily seen and "felt".
Without lots of locks and synchronization, you cannot use the strategy design pattern in a multithreaded scenario, at least if it is allowed to change the context strategy. If you don't, you see the more lasting duration of that relation between the context and the strategy, as they typically live the same time.
The execute around idiom, if properly implemented, should not suffer from this "disease", at least if the the passed function doesn't have any side effects.
Wrapping up, although Strategy design pattern and execute around idiom may seam alike, may be used to solve similar problems, and may seam to have a similar static structure, they are different in nature, having the former a much more OO style and the latter more functional style and, therefore, should have different names!
I agree with Miguel Gamboa, that the proliferation of names that mean the same is not good and should be avoided. But, at least in my opinion, this is not the case.
Hope this helps!

While Strategy and Execute Around are technically very similar they communicate different ideas. When we discuss interchangeable algorithms the term to use is Strategy. When we discuss about allocating and freeing resources around a business method we should use the term Execute Around.

To me, the Strategy pattern being a "family of algorithms" implies that there are multiple different ways to achieve a particular goal. For example, there are multiple different algorithms/strategies that can achieve the particular goal of sorting a list of values. But in the example given – where executeWithFile handles the opening and closing of a file – I don't think that there is any particular goal for the InputStreamAction family. The concrete implementations probably all have different goals.
In Java, the Execute Around pattern requires objects that are concrete implementations of interfaces. I think that's why it looks so similar to the Strategy pattern. But in other languages, only a plain old function is required. Take Ruby, for example:
execute_with_file('whatever.txt') do |stream|
stream.write('whatever')
end
There is no InputStreamAction interface, and there is no concrete WhateverWriterAction. There is just a function that takes a another function as a parameter. Can a plain old function parameter be considered as a "strategy"? It could be, but I wouldn't call it a strategy. And I certainly don't think of it in terms of the Strategy pattern when I'm using or creating an Execute Around implementation.
In summary, if you wanted to be very literal, you could say that Execute Around is a specific type of Strategy pattern. If you consider the intent behind the two patterns, however, they are separate ideas: the Strategy pattern is a family of algorithms that achieve a particular goal, and Execute Around is a generic way to run something before and after a chunk of arbitrary code.

Related

I want to know the meaning of compile-time decisions

What does it mean to say "with inheritance you're locked into compile-time decisions about code behavior".
I suggest this post from Donal Fellows on Programmers,
Some languages are pretty strongly static, and only allow the
specification of the inheritance relationship between two classes at
the time of definition of those classes. For C++, definition time is
practically the same as compilation time. (It's slightly different in
Java and C#, but not very much.) Other languages allow much more
dynamic reconfiguration of the relationship of classes (and class-like
objects in Javascript) to each other; some go as far as allowing the
class of an existing object to be modified, or the superclass of a
class to be changed. (This can cause total logical chaos, but can also
model real world nasties quite well.)
But it is important to contrast this to composition, where the
relationship between one object and another is not defined by their
class relationship (i.e., their type) but rather by the references
that each has in relation to the other. General composition is a very
powerful and ubiquitous method of arranging objects: when one object
needs to know something about another, it has a reference to that
other object and invokes methods upon it as necessary. As soon as you
start looking for this super-fundamental pattern, you'll find it
absolutely everywhere; the only way to avoid it is to put everything
in one object, which would be massively dumb! (There's also stricter
UML composition/aggregation, but that's not what the GoF book is
talking about there.)
One of the things about the composition relationship is that
particular objects do not need to be hard-bound to each other. The
pattern of concrete objects is very flexible, even in very static
languages like C++. (There is an upside to having things very static:
it is possible to analyse the code more closely and — at least
potentially — issue better code with less overhead.) To recap,
Javascript, as with many other dynamic languages, can pretend it
doesn't use compilation at all; just pretence, of course, but the
fundamental language model doesn't require transformation to a fixed
intermediate format (e.g., a “binary executable on disk”). That
compilation which is done is done at runtime, and can be easily redone
if things vary too much. (The fascinating thing is that such a good
job of compilation can be done, even starting from a very dynamic
basis…)
Some GoF patterns only really make sense in the context of a language
where things are fairly static. That's OK; it just means that not all
forces affecting the pattern are necessarily listed. One of the key
points about studying patterns is that it helps us be aware of these
important differences and caveats. (Other patterns are more universal.
Keep your eyes open for those.)

Visitor-Pattern vs. open/closed principle: how to add new visitable object?

I'm studying the visitor pattern and I wonder how this pattern is related to the open/closed principle. I read on several websites that "It is one way to follow the open/closed principle." (citated from wikipedia).
On another website I learned that is follows the open/closed principle in such a way that it is easy to add new visitors to your program in order to "extend existing funcionality without changing existing code". That same website mentions that this visitor pattern has a major drawback: "If a new visitable object is added to the framework structure all the implemented visitors need to be modified." A solution for this problem is provided by using Java's Reflection framework.
Now, isn't this solution a bit of a hack solution? I mean, I found this solution on some other blogs as well, but the code looks more like a workaround!
Is there another solution to this problem of adding new visitables to an existing implementation of the visitor pattern?
Visitor is one of the most boilerplate-ridden patterns of all and has the drawbacks regarding non-extensibility that you mention. It is itself a sloppy workaround to introduce double dispatch into a single-dispatch language. When you consider all its drawbacks, resorting to reflection is not such a terrible choice.
In fact, reflection is not a very bad choice in any case: consider how much today's code is written in dynamic languages, in other words using nothing but reflection, and the applications don't fall apart because of it.
Type safety has its merits, certainly, but when you find yourself hitting the wall of static typing and single dispatch, embrace reflection without remorse. Note also that, with proper caching of Method objects, reflective method invocation is almost as fast as static invocation.
It depends on precisely what job the Visitor is supposed to accomplish, but in most cases, this is what interfaces are for. Consider a SortedSet; the implementation needs to be able to compare the different objects in the set to know their ordering, but it doesn't need to understand anything else about the objects. The solution (for sorting by natural order) is to use the Comparable interface.

Which GoF Design pattern will be changed or influenced by the introduction of lambdas in Java8?

Many claims that the biggest part of the GoF design patterns are just workarounds for the absence of first class functions. Now that Java is about to get lambda expressions, which of those patterns will be influenced by them? Which ones can be dramatically simplified or generalized? And which ones will basically remain the same? Any practical example is welcome.
I think your will see the most changes in Behavioral patterns.
Template Method - Template methods will be more and more seldomly used, and instead we will see objects pass functions to the AbstractTemplate instead of subclassing the AbstractTemplate. I blogged about this a loooong time ago here: http://hamletdarcy.blogspot.ch/2007/11/groovy-closures-end-of-template-method.html
Observer Pattern - Observer becomes simplified because you no longer need to keep a list of observers that get updated on new events, but instead keep a list of functions that need to be called back on new events. So there is no more Observer interface and just function objects.
State/Strategy Pattern - I group these together because they are structurally equivalent, just different in intent. Strategy usage become much more common because it is easier to implement. You don't need a parent strategy and strategy subclasses, you just need functions. So it is simple to just pass a function as a parameter, which in effect is using the strategy pattern.
Overall, I think any pattern that requires a one-method interface becomes easier to implement. This will have the two effects. 1) We will use these functional patterns more, and 2) we will stop referring to them as patterns but just as "passing a function".
You do what you want, but I think "JavaScript the Good Parts" gives a pretty nice introduction to leveraging functions in a language. You might pick it up and read it!
I tried to reply to this question myself writing a series of articles where I analyzed some GoF pattern and their functional counterpart with practical code examples. In particular I revisited: Command and Strategy, Template and Observer, Decorator and Chain of Responsibility, Interpreter and Visitor.

Is there a name for a java method considered as separate from any particular class?

This is a terminological question, which makes it hard to ask!
Let me give an example. Suppose I am writing a symbolic-differentiation algorithm. I have an abstract class Exp that is a superclass of a bunch of expression types (sums, integrals, whatever). There is an abstract method derivative such that e.derivative() is supposed to be the derivative of the expression e. All the concrete subclasses of Exp (imagine a whole hierarchy here) implement a derivative method that captures knowledge of how to differentiate expressions of that type. A given method will typically compute the derivative of an expression by combining derivatives of subexpressions.
The details of the example are not important. The important thing is that all of these scattered methods can be considered pieces of one (recursive) algorithm. This is not true of all methods, but it's true of many of them (and the use of overloading to reuse the same method name for fundamentally different operations is considered a Bad Idea). The question is, what is the term for 'derivative,' considered as a single function? It's not a method; in another language it would be a function, and the various clauses (what to do with sums, what to do with integrals) would be in the same place. I don't care which approach or languaage is better, or whether that style can be used in Java. I just want to know what term to use for 'derivative' considered as a single function or procedure (the idea is not limited to functional programming, nor is recursion a key feature). When I tell someone what I did today, I'd like to say "I tried to implement a symbolic-differentation __, but every algorithm I thought of didn't work." What goes in the blank?
I assume the same issue comes up for other OO languages, but Java is the one I'm most familiar with. I'm so familiar with it that I'm pretty sure there is no standard term, but I thought I would ask our fine battery of experts here before jumping to that conclusion.
That sounds like "normal" subtype polymorphism. The subclasses/implementations do the work but the interface is defined in a base-type. This "scatter" method is in contrast to say, the Visitor Pattern ("as good as Java gets") or Pattern Matching (not in Java) or a big manky switch/if-else controller. I'm not sure I really would call it anything else as an aggregate.
Addendum: you may find Are Scala case-classes a failed experiment? a nice read. In particular, the comments which talk about "column" vs. "row" organization and the "difference of locality" each approach has:
...in OO, you divide by rows. Each row is a module, called a class. All the functions pertaining to that data variant are grouped together. This is a reasonable way of organizing things, and it's very common. The advantage is that's easy to add a data variant ... However the disadvantage is that it's hard to add new functions that vary by data type. You have to go through every class to add a new method.
I'm not sure if this is what you're looking for but I think I can answer this in terms of design pattern terminology. Your example sounds vaguely like the GoF Strategy Pattern. Here is an example of the Strategy Pattern implemented in Java.
On the contrary, I think that "method" is the standard term for this in the Java context.
A polymorphic function can be applied to values of different types. The function may be implemented by more than one Java method.

Secret Handshake Anti-Pattern

I've just come across a pattern I've seen before, and wanted to get opinions on it. The code in question involves an interface like this:
public interface MyCrazyAnalyzer {
public void setOptions(AnalyzerOptions options);
public void setText(String text);
public void initialize();
public int getOccurances(String query);
}
And the expected usage is like this:
MyCrazyAnalyzer crazy = AnalyzerFactory.getAnalyzer();
crazy.setOptions(true);
crazy.initialize();
Map<String, Integer> results = new HashMap<String, Integer>();
for(String item : items) {
crazy.setText(item);
results.put(item, crazy.getOccurances);
}
There's reasons for some of this. The setText(...) and getOccurances(...) are there because there are multiple queries you might want to do after doing the same expensive analysis on the data, but this can be refactored to a result class.
Why I think this is so bad: the implementation is storing state in a way that isn't clearly indicated by the interface. I've also seen something similar involving an interface that required to call "prepareResult", then "getResult". Now, I can think of well designed code that employs some of these features. Hadoop Mapper interface extends JobConfigurable and Closeable, but I see a big difference because it's a framework that uses user code implementing those interfaces, versus a service that could have multiple implementations. I suppose anything related to including a "close" method that must be called is justified, since there isn't any other reasonable way to do it. In some cases, like JDBC, this is a consequence of a leaky abstraction, but in the two pieces of code I'm thinking of, it's pretty clearly a consequence of programmers hastily adding an interface to a spaghetti code class to clean it up.
My questions are:
Does everyone agree this is a poorly designed interface?
Is this a described anti-pattern?
Does this kind of initialization ever belong in an interface?
Does this only seem wrong to me because I have a preference for functional style and immutability?
If this is common enough to deserve a name, I suggest the "Secret Handshake" anti-pattern for an interface that forces you to call multiple methods in a particular order when the interface isn't inherently stateful (like a Collection).
Yes, it's an anti-pattern: Sequential coupling.
I'd refactor into Options - passed to the factory, and Results, returned from an analyseText() method.
I'd expect to see the AnalyzerFactory get passed the necessary params and do the construction itself; otherwise, what exactly is it doing?
Not sure if it does have a name, but it seems like it should :)
Yes, occassionally it's convenient (and the right level of abstraction) to have setters in your interface and expect classes to call them. I'd suggest that doing so requires extensive documentation of that fact.
Not really, no. A preference for immutability is certainly a good thing, and setter/bean based design can be the "right" choice sometimes too, but your given example is taking it too far.
I'm not sure whether it's a described anti-pattern but I totally agree this is a poorly designed interface. It leaves too much opportunity for error and violates at least one key principle: make your API hard to misuse.
Besides misuse, this API can also lead to hard-to-debug errors if multiple threads make use of the same instance.
Joshua Bloch actually has an excellent presentation (36m16s and 40m30s) on API design and he addresses this as one of the characteristics of a poorly designed API.
I can't see anything bad in here. setText() prepares the stage; after that, you have one or more calls to getOccurances(). Since setText() is so expensive, I can't think of any other way to do this.
getOccurances(text, query) would fix the "secret handshake" at a tremendous performance cost. You could try to cache text in getOccurances() and only update your internal caches when the text changes but that starts to look more and more like sacrifice to some OO principle. If a rule doesn't make sense, then don't apply it. Software developers have a brain for a reason.
One possible solution - use Fluent chaning. That avoids a class containing methods that need to called in a certain order. It's a lot like the builder pattern which ensures you don't read objects that are still in the middle of being populated.

Categories