Switch statement or remotely invoke methods - java

I have a switch statement that compares a String with set of String where each match calls a different method.
switch(((Operation) expr.getData()).getValue()){
case "+":
return add(expr.getNext());
case "car":
return car(expr.getNext());
case "cdr":
return cdr(expr.getNext());
case "cons":
return cons(expr.getNext(), expr.getNext().getNext());
case "quote":
return quote(expr.getNext());
case "define":
handleDefine(expr.getNext());
break;
default:
return null;
}
However, to me this sounds like something that could be achieved far more elegantly and efficiently using a HashMap that links up to an Operation that contains a Method and the number of parameters so I could each method to a HashMap like:
nameToOperation.put("+", new Operation("+", 1, Driver.class.getMethod("add")));
nameToOperation.put("car", new Operation("car", 1, Driver.class.getMethod("car")));
So there would be N different instances of the Operation class each containing the String, Method and number of parameters
And then I could simply call the method using something similar to this (I understand this isn't how you use invoke):
Operation op = ((Operation) expr.getData())
if(op.getNumPars() == 1)
return(op.getMethod().invoke(expr.getNext()));
else
return(op.getMethod().invoke(expr.getNext(), expr.getNext().getNext()));
However, I still don't fully like this solution as I am losing type safety and it still doesn't look that great. Another example I have seen on stackoverflow that looked quite elegant but I don't fully understand is the first solution of the top answer on: How to call a method stored in a HashMap? (Java)
What does everyone on Stackoverflow think the best solution is?
Edit: Just in case anybody searches this and was wondering about my solution, I made each operation such as Add, Car, Cdr have their own class that implemented Command. I then had to make the majority of my methods static, which I suppose by nature each of them were anyway. This seems way more elegant than the original case statement.

basicaly , the answer recommends to go with Command pattern.
"The main advantage of the command design pattern is that it decouples the object that invokes the operation from the one that know how to perform it. And this advantage must be kept. There are implementations of this design pattern in which the invoker is aware of the concrete commands classes. This is wrong making the implementation more tightly coupled. The invoker should be aware only about the abstract command class"
Basicaly your map would be type safety. by declaring
Map <character,Command>
Open to Extendibility

It looks like you are trying to write a Scheme interpreter. In that case you're gonna need a map anyway since you need to store all the user defined values und functions.
When the user writes e.g. (define (add a b) (+ a b)), you store the function in the map using "add" as key.
But your functions should use lists as inputs, i.e. each function has exactly one argument which is a list. In Scheme all expressions are lists by the way. Usually a Scheme interpreter consists of a reader and an evaluator. The reader converts the code into a bunch of nested lists.
So basically "(define (add a b) (+ a b))" could be converted into a list structure similar to this.
List<Object> list = new ArrayList<Object>();
List<Object> list2 = new ArrayList<Object>();
list2.add("add"); list2.add("a"); list2.add("b");
List<Object> list3 = new ArrayList<Object>();
list3.add("+"); list3.add("a"); list3.add("b");
list.add("define"); list.add(list1); list.add(list2);
Of course your code doesn't actually look like this, instead the lists are constructed by recursive methods parsing the input code.
Those lists don't just contain strings btw., they also contain numbers and boolean values. Nested lists like this are the most simple form of an abstract syntax tree (AST). Since the syntax of Scheme is much simpler than that of most other languages, a very simple list structure is enough to store the parsed code.
The evaluator then processes those lists.
To evaluate a list you first recursively evaluate every element in the list and then apply the first element to the rest of the list. That first element must therefore be a user defined function or a build in command e.g. "define".

Related

Fluently adding to a Collection (add and return the value)

Time and again, I find myself in the situation where I want to use a value, and add it to a collection at the same time, e.g.:
List<String> names = new ArrayList<>();
person1.setName(addTo(names, "Peter"));
person2.setName(addTo(names, "Karen"));
(Note: using java.util.Collection.add(E) doesn't work of course, because it returns a boolean.)
Sure, it's easy to write a utility method myself like:
public static <E> E addTo(Collection<? super E> coll, E elem) {
coll.add(elem);
return elem;
}
But is there really not something like this already in JavaSE, Commons Collections, Guava, or maybe some other "standard" library?
The following will work if you use Eclipse Collections:
MutableList<String> names = Lists.mutable.empty();
person1.setName(names.with("Peter").getLast());
person2.setName(names.with("Karen").getLast());
The with method returns the collection being added to so you can easily chain adds if you want to. By using getLast after calling with on a MutableList (which extends java.util.List) you get the element you just added.
Note: I am a committer for Eclipse Collections.
This looks like a very strange pattern to me. A line like person1.setName(addTo(names, "Peter")) seems inverted and is very difficult to properly parse:
An existing person object is assigned a name, that name will first be added to a list of names, and the name is "Peter".
Contrast that with (for example) person1.setName("Peter"); names.add(person1.getName());:
Make "Peter" the name of an existing person object, then add that name to a list of names.
I appreciate that it's two statements instead of one, but that's a very low cost relative to the unusual semantics you're proposing. The latter formatting is easier to understand, easier to refactor, and more idiomatic.
I would be willing to wager that many scenarios that might benefit from your addTo() method have other problems and would be better-served by a different refactoring earlier on.
At its core the issue seems to be that you're trying to represent a complex data type (Person) while simultaneously constructing an unrelated list consisting of a particular facet of those objects. A potentially more straightforward (and still fluent) option would be to construct a list of Person objects and then transform that list to extract the values you need. Consider:
List<Person> people = ImmutableList.of(new Person("Peter"), new Person("Karen"));
List<String> names = people.stream().map(Person::getName).collect(toList());
Notice that we no longer need the isolated person1 and person2 variables, and there's now a more direct relationship between people and names. Depending on what you need names for you might be able to avoid constructing the second list at all, e.g. with List.forEach().
If you're not on Java 8 yet you can still use a functional syntax with Guava's functional utilities. The caveat on that page is a worthwhile read too, even in Java-8-land.

Which method signature is good and why?

Given an IP Address Range ( a.b.c.d - a.b.c.e) i would like a method to return the ip address's in an array list between the range.
Option 1 :
public static int getIPAddressesFromRange(String rangeStr, List list ) ;
return value is count and the input list would be populated with list of IP's the range has
Option 2:
public static List getIPAddressesFromRange(String rangeStr)
return value is the list of ip addresses'
My Option is 2, but that is intuition, not able to support my argument though.
Edit: Is there any design principle the option 1 is violation ?
I'd say
public static List<String> getIPAddressesFromRange(String rangeStr)
if you decide to represent IP addresses as strings.
Arguments against #1:
The caller needs to construct the list in advance
It is not straightforward what the return value is unless you document it
The method mutates one of its arguments, which is not in general forbidden, but it is best to avoid surprising the user of your API (especially if they are prone not to read the documentation)
Passing in a null value accidentally for the list parameter will result in a NullPointerException.
You can always get the length of the list from the list itself if you really care about it.
Prefer the option 2 to the option 1.
The list contains its count anyway, so there is no need to return two values (the count and the list).
Also, since you know the type of the list, you can use generics: List<String>.
Finally, you might also consider taking two arguments: the beginning and the end of the range.
Why do you want to return count in first method? You can fetch the number of IP's from List itself.
Second method should be the preferred one
Your second option is best because the first option has two problems:
It's redundant. If a List is returned, you can use its size() method to get that count, so you gain nothing by returning the count.
The list must be validated and in some cases the method outright cannot perform its work. If the caller passes null, there is danger of a NullPointerException being thrown if the code was not written carefully. Also in that case, reassigning the parameter to point to a new list will not be observed by the caller, so your only remotely sane option is to throw a clear exception. With the second option, you have full control of the list until it is returned to the caller.
Option two is probably better, since it is clear for any reader what is the method returning.
Method 1 might cause future coders to spend time thinking what is this parameter (unless it is properly documented), while method 2 is realy straight forward.
Option two also makes it more neat if you later need to iterate on the retrieved list, no need for temporary variables:
for (Object o : getIPAddressesFromRange(String rangeStr)) { ... }
You should also prefer using the generic type List<> and not the raw type.
Stuff in, stuff out. That's what your Option 2 does.
Option 1 mutates its input argument and returns redundant value (count, which can be got from the list).
Another thing is, perhaps a range of IP addresses would be described better by some other type than a String.
IMO method signature suggests it will return a list of ip addresses from range, not how many addresses are in this range, hence I'm also for option 2.
I think the 2nd one is better :
The count is the size of the list
You don't have to give a list to the function
Less null pointer exception risk
Your intuition is mine also, it is better to let getIPAddressesFromRange use its preferred implementation of List and avoid someone to give you an already populated list.
My opinion is that the second method signature is generally the best one as the first one will exposes your list object to concurrent modification. Thus, at the end of your method, it may hold less, more, other objects than expected.
It depends on whether you want to fill pre-created lists, or create new ones.
For example: You could do multiple calls to your function using the same List object to save some memory.
Or: To compare multiple lists, you may want to return a new List for each call.
I would go with Option 2.

Always avoid in-out parameters in Java?

There's no doubt that in-out parameters leads to confused code since they may increase unexpected/unpredictabled side-effects.
So, many good programmers say :
Avoid in-out parameters for changing mutable method parameters. Prefer to keep parameters unchanged.
For a perfectionist programmer who expects his code to be the most clean and understandable, does this "rule" must be applied in all case ?
For instance, suppose a basic method for adding elements to a simple list, there's two ways :
First way (with in-out parameter):
private void addElementsToExistingList(List<String> myList){
myList.add("Foo");
myList.add("Bar");
}
and the caller being :
List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
addElementsToExistingList(myList);
Second way without out parameter :
private List<String> addElementsToExistingList(List<String> originalList){
List<String> filledList = new ArrayList<String>(originalList); //add existing elements
filledList.add("Foo");
filledList.add("Bar");
return filledList;
}
and the caller being :
List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
myList.addAll(addElementsToExistingList(myList));
Pros of second way :
Parameter are not modified => no risk of unexpected side-effects for a new code reader.
Cons of second way :
Very verbose and very less readable ...
Of course, you would tell me that for a code as simple as this one, first way is really more convenient.
But, if we don't consider the difficulty of any concept/code, I juge the second way more logical and obvious for any readers (beginners or not).
However, it violates the CQS principle that consider "command" methods having void return with potential (but allowed since it's the convention) side-effects and "query" methods having a return type and without side-effects.
So, what should a motivate programmer adopt ? Mix of two accorging to the code case ? Or keep the "law" expecting to always avoid in-out parameters...
(Of course, method for adding Element is named for expliciting the example, and would be a bad name choice in real code).
I think the law should be:
Use what is more straight-forward, but always, always document the behavior of your methods extensively.
Your second example is a very nice case where without documentation you would have a guaranteed bug: the name of the method is addElementsToExistingList, but the method does not add elements to the existing list - it creates a new one. A counter-intuitive and misleading name, to say the least...
There is a third way. Wrap List<String> into a class that knows how to add elements to itself:
class ElementList {
private List<String> = new ArrayList<String>();
public void addElements(Element... elements);
}
I like this approach because it keeps the List implementation private. You don't have to worry if someone passes an immutable list to your method or whether parameters are modified. The code is simpler. Long method names like addElementsToExistingList are code smells that an object is trying to do something another object should be doing.
You should always document when mutating an object that is a parameter because otherwise this can have unintended side effects for the caller. In the first case I agree with the others that have commented that the method name is sufficient documentation.
In your second example, the elements that are already present in myList seem to be added twice. In fact you could entirely remove the parameter of the addElementsToExistingList method and rewrite it as:
private List<String> getElements() {
List<String> filledList = new ArrayList<String>();
filledList.add("Foo");
filledList.add("Bar");
return filledList;
}
List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
myList.addAll(getElements());
Note that this code is not equivalent to your second example because the elements are only added once, but I think this is actually what you intended. This is the style that I usually prefer. This code is easier to understand and more flexible than the first example without adding extra code (it may degrade performance very slightly but this usually isn't a concern). The client of getElements() can now also do other things with the element list besides adding it to an existing collection.
It's fine to change/mutate parameters as long as it's documented. And of course with a method name of "addElementsToExistingList", what else should someone expect? However, as someone previously pointed out, your second implementation returns a copy and doesn't modify the original, so the method name is now misleading. Your first way is a perfectly acceptable way of doing things. The only other additional improvements is to possibly add a true/false value to the return indicating true if only all the elements were added to the list.
In the case of your example the name makes it clear - "addElementsToExistingList" to me seems pretty clearly to hint that you're going to .. er.. you know. But your concern would be justified with a less obvious name.
For example, in ruby this is commonly handled with naming conventions
"a".upcase => gives you the uppercase of the variable, leaves the original unchanged
"a".upcase! => alters the original variable

is it possible to modify all elements of a list in java?

I have a list of Strings and I want to perform the same operation on all of the Strings in the list.
Is it possible without performing a loop?
Well something's got to loop, somewhere - if you want to abstract that into your own method, you could do so, but I don't believe there's anything built into the framework.
Guava has various methods in Iterables to perform projections etc, but if you want to modify the list on each step, I'm not sure there's any support for that. Again, you could write your own method (extremely simply) should you wish to.
When Java eventually gets closures, this sort of thing will become a lot more reasonable - at the moment, specifying the "something" operation is often more effort than it's worth compared with hard-coding the loop, unfortunately.
You could do it recursively, but I don't see why you'd want to. You may be able to find something similar to Python's map function (which, behind the scenes, would either be a loop or a recursive method)
Also note that strings are immutable - so you'll have to create 'copies' anyway.
No. You must loop through the list.
for(String s:yourlist){
dooperation(s);
}
Why do you not want to perform a loop?
If it's computational complexity, then no, it's unavoidable. All methods will essentially boil down to iterating over every item in the list.
If it's because you want something cleaner, then the answer depends on what you think is cleaner. There are various libraries that add some form of functional map, which would end up with something like:
map(list, new Mapper<String, String>() {
public String map(String input) {
return doSomethingToString(input);
}
);
This is obviously more long winded and complex than a simple loop
for (int i = 0; i < list.size(); i += 1) {
list[i] = doSomethingToString(list[i]);
}
But it does offer reusability.
map(list, new DoSomethingToStringMapper());
map(otherlist, new DoSomethingToStringMapper());
But probably you don't need this. A simple loop would be the way to go.
You could use apache commons util.
sorry, you have to iterate through the list somehow, and the best way is in a loop.
Depending on what you mean by no loop, this may interest you:
a map function for java.
http://www.gubatron.com/blog/2010/08/31/map-function-in-java/
...there's still a loop down inside of it.
In Java you'll need to iterate over the elements in the Collection and apply the method. I know Groovy offers the * syntax to do this. You could create an interface for your functions e.g. with an apply method and write a method which takes your Collection and the interface containing the function to apply if you want to add some general API for doing this. But you'll need the iteration somewhere!
Use divide and conquer with multithreaded traversal. Make sure you return new/immutable transformed collection objects (if you want to avoid concurrency issues), and then you can finally merge (may be using another thread which will wake up after all the worker threads finished transformer tasks on the divided lists?).
If lack of memory in creating these intermediate collections, then synchronize on your source collection. Thats the best you can do.
No you have to use a loop for that.
You have to perform the operation on each reference variable to the Strings in the List, so a loop is required.
If its at the List level, obviously there are some operations (removeAll, etc.).
The java API provides special class to store and manipulate group of objects. One Such Class is Arraylist
Note that Arraylist class is in java.util.ArrayList
Create an ArrayList as you would any objects.
import java.util.ArrayList;
//..
ArrayList ajay = new ArrayList();
Here
ArrayList -> Class
ajay -> object
You can optionally specify a capacity and type of objects the Arraylist will hold:
ArrayList ajay<String> = new ArrayList<String>(10);
The Arraylist class provides a number of useful methods for manipulating objects..
The add() method adds new objects to the ArrayList.And remove() method remove objects from the List..
Sample code:
import java.util.ArrayList;
public class MyClass {
public static void main(String[ ] args) {
ArrayList<String> ajay = new ArrayList<String>();
ajay.add("Red");
ajay.add("Blue");
ajay.add("Green");
ajay.add("Orange");
ajay.remove("Green");
System.out.println(colors);
}
}
Output for this Code:
[Red,Blue,Orange]
Accepted answer link is broken and solution offered is deprecated:
CollectionUtils::forAllDo
#Deprecated
public static <T,C extends Closure<? super T>> C forAllDo(Iterable<T> collection, C closure)
Deprecated. since 4.1, use IterableUtils.forEach(Iterable, Closure) instead
Executes the given closure on each element in the collection.
If the input collection or closure is null, there is no change made.
You can use IterableUtils::forEach(Closure c)
Applies the closure to each element of the provided iterable.

Printing out items in any Collection in reverse order?

I have the following problem in my Data Structures and Problem Solving using Java book:
Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.
First, I believe it is asking you to write a method. Like:
void printReverseList(Collection col) {}
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).
That could technically count as 1 routine (all have the same name).
I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.
You might want to read this.
Isn't there a base Collection class?
Probably worth looking here as a starting point: Collections.

Categories