What is the difference between the Interpreter pattern and Visitor pattern? - java

I have troubles understanding these two design patterns.
Can you please give me contextual information or an example so I can get a clear idea and be able to map the difference between the two of them.
Thanks.

The visitor pattern allows you to add functionality to classes without altering them. You keep in a single place/class the same kind of behaviour for different type of objects while (potentially) having different implementation for each type. You can extend or change the behaviour for multiple types of objects while working on a single class (the visitor). Also useful when you want to extend behaviour of classes that are not under your control, without wrapping or extending them.
In visitor the driver of the behaviour is based on behalf of which type of object the operation is performed.
The interpreter pattern can be used on domain problems which can be expressed in simple language/sentences. Then the problems can be solved by interpreting these sentences. So we get an input, we can understand (interpret) it and then implement certain behaviour based on the interpretation/categorization of the input.
In interpreter the driver of the behaviour is based on what the input is, the interpretation/categorization of the input.

Related

Choice of design pattern - serial execution

I have a simple design problem - I am looking for the best pattern to implement a simple functionality. Let's say, I am going to create an xml message in java. This message consists of many fields in different logic groups.
So, the first idea - create a class to set all fields. I can do it one method (which will be really long...) or split the method into multiple smaller (for each of the logical groups). However, I don't think it is a good approach, because the class will be really long and difficult to mantain.
The second idea is to create a functional interface and some implementations for different groups, for instance GroupXxxSetter, GroupYyySetter, etc. I can create and keep all instances in a list or a set and call the method defined inside the interface for each object stored inside the collection. It seems to be very similar to the 'Chain of responsibility' pattern. However, the idea of this pattern is different, so I am not sure if it is a good idea to use this pattern in my case.
Should I use the 'chain of responsibility' pattern here? Or, maybe there is something better?
Thanks in advance.
Should I use the 'chain of responsibility' pattern here?
Clearly, no. You don't have the notion of candidate responsible to respond to a request. All elements will do a processing.
Or, maybe there is something better?
You have multiple possibilities.
Your context is not totally set. So it is hard to propose one rather than another.
I may propose you a implementation with the Builder pattern (Java Effective reference and not GOF).
For each logic group, you could have a specific class.
You would also have a composite class that is composed of logic group instances.
Instead of providing a public constructor or setters that prevent immutability and that can make rules validation cumbersome, you could use the Builder pattern for each one logic group class and in the composite class, you could use the same kind of Builder pattern where you will build the final message from the previously created logic group instances.
You could so create the instances in this way :
OneLogicGroup oneLogicGroup = OneLogicGroup.builder().fieldXXX(...).fieldYYY(...).build();
AnotherLogicGroup anotherLogicGroup = AnotherLogicGroup .builder().fieldXXX(...).fieldYYY(...).build();
MyMessage myMessage = MyMessage.builder().oneLogicGroup(oneLogicGroup).anotherLogicGroup(anotherLogicGroup).build().
I can create and keep all instances in a list or a set and call the
method defined inside the interface for each object stored inside the
collection.
It seems referring to a structural concern.
It is not directly related to the creation of the object. It is much related to how to share the created objects.
The flyweight pattern addresses this need and may be used conjointly with the presented builder Pattern.

Do method names always have to be verb?

I am new to java programming, and I am currently working on a command reading program (basically the user types in a command and my program evaluates what to do and does it). I have a separate class that contains all my commands, but they're stored as methods and aren't always using verbs as names. I understand that it is customary have methods stored as verbs. Am I using methods wrong and is there a better way to store my commands? Separate class for each command? Example of calling one of my methods:
else if (command[0].equals("math")) Commands.math();
Do method names always have to be verb?
As far as the Java language (i.e. the Java compiler) is concerned, no. The language spec only requires you to follow some rules about what characters are used, and about contextual uniqueness.
Typical Java Style Guides don't require method names to be verbs either. But they typically recommend this. (Note that this is not something that automated style checkers check, because of the difficulty of reliably distinguishing nouns and verbs.)
I understand that it is customary have methods stored as verbs.
That is a better characterization.
This actually comes out of Object Oriented Design. A class in the design maps to a Java class, and the Java methods represent actions on the instances on the design classes. It is "natural" (and customary) to use noun-like identifiers for classes, and verb-like identifiers for methods.
But it is NOT a requirement.
In your example, you could simply address the dilemma by using "doMath" as the method name. That is a verb phrase. (The "do xyz" is a commonly used convention, albeit that it doesn't "read" very well.)
However, it seems like you could, and possibly should avoid hard-wiring the command names into the method names. Take a look at the "Command" design pattern: http://www.fluffycat.com/Java-Design-Patterns/Command/ (archived).
Design patterns are something you will need to learn in the long run, but they are possibly too much for a beginner programmer to digest.
Must methods be verbs? No. As long as the compiler is concerned, it doesn't matter.
Should they be verbs? As a convention that will make programs easier to understand: Clearly yes.
Variables represent objects and data, so you should normally use a noun. Methods represent actions, so you should normally use a verb. There are exceptions, of course but that is the normal rule. Ideally the name of a variable or method should be enough to identify it's function in the class.
To make it more object oriented you may consider using Abstract Class Command and separe classes extending it as classes
In this case, you should put all the methods in the same class, but other than that, you are using methods correctly.
I'm a Java programmer, and I've never heard of the verb custom. However, If you want to follow it, some suggestions for method names are doMath() or calculateMath() or something similar.
Also, you should NOT be splitting up methods by class. Generally, you should only use multiple classes if you are planning to instantiate objects of the different classes. Putting each method in a separate class is pretty ridiculous.

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

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.

What's the design pattern for object to object conversion?

The question is simple. I need to convert the content of a bean into an other bean with different getters and setters. What's the right design pattern for doing this?
I think an adapter pattern is mainly referring to a mapping of a signature or interface to an other. Not a real mapping between objects.
Many people talks about "mapper" but I think this is not a design pattern.
So, is there actually a pattern for mapping an object to an other?
I'm not aware of any popular design pattern for object mapping.
I have been using Dozer framework for transfering the content from one bean to another.
It is simple to use and easily integrates with Spring.
Refer:
http://dozer.sourceforge.net/documentation/gettingstarted.html
A great "design pattern" would be to not tightly couple the mapped objects to each other. A copy constructor, for example, means that if you edit the source class, you also have to edit the destination class, and that can cause all sorts of downstream issues in a large project. Think about it this way. A very frequent mapping is from UI data structures to back-end data structures. You should be able to scrap your UI and not have to change the back-end for a new UI. An MVC design pattern is frequently used for this sort of work.
There is a nice Translator pattern published by Microsoft. The tutorial is in C++ but it should be easy to convert to Java.
Here is a tutorial: http://richhewlett.com/2010/06/11/a-useful-entity-translator-pattern-object-mapper-template/
The general idea is you have a generic Translator abstract class, parametrized with the class types you want to translate between. The concrete implementations provide the "to" and "from" conversion methods.
This pattern has the advantage that it does not require coupling between the two classes in the conversion. It does this in a reusable, generic framework that won't clutter your code with one-off conversion decoupling logic.
The related pattern is Assembler where you assemble some object given the contents of another. Since writing assemblers can be tedious and error-prone, you can use an object mapping library to do the work for you.
One object mapper you might check out is ModelMapper, which I authored, that uses actual code to map properties, fields and methods, in a safe way.
I agree with Javakid, what you need is not a design pattern but a good solution to handle te conversion from one bean to another.
If you really need to name, that should something like dto pattern since you are using data transfer object. You can use a visitor to inspect all your bean tree while building the converted one.
so I would suggest using a framework or developping the mapping by yourself, it depends on the size of the graph. Dozer is goode solution to do it but it uses Reflection API all the way and hide the mapping code. So you won't be able to debug it easily, there are also few other runtime mapping library like Orika the best I know.
But, If you want to be able to see the code, debug it and have compiler feedback you can also use Selma.
Last thing, you can also report to this thread for a big picture of solutions to handle bean to bean mapping in java: any tool for java object to object mapping?

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.

Categories