How to write a method that accepts stacks and queues? - java

So I have this really large method I wrote. If it's given a stack, it will return a stack. If it's given a queue, it will return a queue. It uses a lot of recursion, and it accepts a queue/stack and returns that same queue/stack modified accordingly.
I don't want to copy/paste my method just so I can change the type used inside, so is there any way I can make this generic? As in, it will accept any old collection and play with it? I tried just using Collection, but the trouble with that is it doesn't have a .remove() I can use with the stack/queue.
Any help would be greatly appreciated.
Thanks.

Make your method private, and create two public methods: one which takes a stack and one which takes a queue. have each of these methods cast and return the result of calling the private method. That way you avoid repetition while still having specific method signatures.

You could use Collection but then have special case handling just around your remove operations. Of course you'll have to figure out what to do when you get a collection that's not one of the two.
if (myCollection instanceof Queue) {
((Queue)myCollection).remove();
} else if (myCollection instanceof Stack) {
((Stack)myCollection).remove(thingy);
} else {
// Oops! Now what?
}

Queue and Stack both have a remove() method, but the method is not the same. Because of this, Java will need to know which of those methods to call when compiling the code. You will need to have 2 separate methods. Sorry

You need to write an interface that has the operations you need from both Stack and Queue, since you want to use recursion/operations upon both.
This new interface would have two concrete classes that would rely on instances of Stack and Queue underneath, then polymorphism would to the magic.
You can always have a method for 'getUnderlyingCollection()' so you could have the actual Stack or Queue, after the proper cast, but attain to polymorphic operations would make your recursive algorithm more generic.

I presume you mean java.util.Stack and java.util.Queue. Queue defines its own remove() method. Stack inherits its remove(...) methods from java.util.Vector, so I assume you actually mean pop()?
Two ways spring to mind:
Provide two public method overloads which both call a private method with two parameters, one of which is always null.
Define an interface with the common methods you need, with an anonymous inner class definition in each of two private methods (or a full concrete class definitions if they're sufficiently large).
Which you should choose depends on how many ugly conditional method calls you will need to do internally. An OO-purist would prefer the interface implementation regardless. :-)

Related

how can a method return a Set in java?

I am calling a method from an api that returns a Set Object. As far as I know, a Set is an interface, and you cannot instantiate an interface. I am able to take this set and call toArray() on it. what is Set actually returning then?
It does return a Set, but you must understand, that a Set is more than just the interface:
Every implementation of every class that implements Set can be returned.
public Set getMySet(){
return new HashSet();
}
since HashSet implements Set, this is valid code that will work.
Writing applications to interfaces rather than their implementations is a widely used practice. After all, all you need to write (and test) your code (for instance the UI using a service), is the interface.
You can't get the concrete implementations yet, they may not even exist yet, but you can already do all the work you need to do.
Returning an interface from a method means that the returned object will implement that interface.
In this case it means that the object returned will implement 'Set'. You will be able to call methods which are contained in that interface but will not be able to call methods from the implementing class.

Is there a way to define a contract to implement a method with no parameter restrictions (see explanation)?

I understand what interfaces and abstract classes are, but I don't know how to get the following functionality; if it's possible, that is. I have a bunch of classes which are each going to have a validate() method. Each method may take different parameters. For example, we could have classes with the following methods:
boolean validate();
boolean validate(Block[]);
boolean validate(BlockSet[]);
...
So, basically I want to know if I can use an interface or abstract class, or something else, to define a contract to have a method with a given name and return type implemented, but no restrictions on the set of parameters. Thanks in advance.
You can do this with validate(Object... args), but it's worth questioning whether you really want to. Interfaces and Abstract Classes are useful so that you can group a bunch of similar objects together, and have implementations do different things with the same operation. It seems to me that you wouldn't be able to call this method without knowing what the underlying implementation is, and therefore there is no reason to abstract them.
Try using varargs in an interface:
boolean validate(Object... args) or
'boolean validate(Block... blocks)`
if the Blocks are always a collection, use their supertype:
boolean validate(Collection<Block> blocks)
But then you may need to use some casts. Not best option.
If you want method to take any number pf parameters then you can use Varargs but if you want it to change Type also then its not feasible.
Also what you want to achieve is find a separate way of method overloading, but for that you will have to explicitly specify the methods.

Chain of Responsibility Logging

I have an abstract class called ChainHandler and many implementations of the ChainHandler.
Other programmers will write other implementations of that ChainHandler.
My program implements the Chain of Responsibility design pattern.
Each concrete implementation of the ChainHandler implements a handle method.
public abstract void handle(SomeclassA a);
If one handler can handle "a", it handles it and the chain stops. If not,"a" is passed to the next Handler until it hits the end of the chain.
I want each concrete handler to have a list of all "a"s it was able to handle. But I don't want to make the concrete classes developer to remember to write it to a list on success.
Is there a elegant way of doing it?
My best idea was the following:
1 - Change the handle method to protected at the concrete classes, make it return a boolean and change the name to innerhandle;
2 - Change the handle method at the abstract class to public and it calls the innerhandle. On success, it adds the object to the list.
The second option is surely better (and it relies on the Template method pattern) making it harder for someone implementing a subclass of doing it wrong, you can even make the handle method final so no one will ever be able to change it's behavior and break without noticing it.
The servlet API has such an example, the init method that takes a ServletConfig parameter can be overridden and it's rather common to see people forgetting to call super and the original init(ServletConfig) method, so you should try to avoid this same mistake.

Using an Interface in another interface

I am not sure how to proceed with adding element to the Priority Queue. I don't want code to be spoon feed to me, can someone just explain to me how to use interface passed to another interface as parameter and a class implementing one of its method. Please give me pointers, I will look it up and learn how to implement this code.
QueueItem class
public interface QueueItem
{
/**
* Returns the priority of this item. The priority is guaranteed to be
* between 0 - 100, where 0 is lowest and 100 is highest priority.
*/
public int priority();
}
PriorityQueue class
public interface PriorityQueue
{
/**
* Inserts a queue item into the priority queue.
*/
public void insert(QueueItem q);
/**
* Returns the item with the highest priority.
*/
public QueueItem next();
}
QuickInsertQueue class
public class QuickInsertQueue implements PriorityQueue {
#Override
public void insert(QueueItem q) {
// TODO Auto-generated method stub
}
#Override
public QueueItem next() {
// TODO Auto-generated method stub
return null;
}
}
I have to Write a QuickInsertQueue class that implements the PriorityQueue
interface having insert() method O(1).
You are already on the right track. Your interfaces are defined and your class definition has the correct implementation attached. Since you say you dont want code spoon fed to you which I applaud - the next step you want to implement is actually adding the HashMap instance variable to your class, since that is your underlying storage. And in your method implementation for insert, you will be adding your variable to the map.
Eventually you are going to need to read about Generics.
Ted and Perception have you told you what you need. One more suggestion I have is you need to find the right data structure to use so that insertion would be O(1). I suggest you look at heaps. Specifically looking at min-heaps allows you to insert in contant time. Look here. I hope this helps.
You use an interface to guarantee that any object you receive will behave according to the interface. That's why your QuickInsertQueue needs to implement the methods of PriorityQueue. The only information it can use about the inserted objects, though, is that they behave according to the QueueItem interface—that is, they have a priority() method that returns an int. Your implementation can rely on that, but nothing else, about the objects it will be managing.
You are on the right track.
So, without getting into code level details that you are right you should figure out on your own, how it (is supposed to) work in an ideal world is -
All interaction in your system between different kind of objects is defined by using interfaces. i.e. if you need to find out "how do things interact in my application" you should need to look no further than all the interfaces. (Everything else is implementation detail.) In other words, all the real work is done by classes (that implement interfaces) but the interaction is defined by the interfaces.
One implementation class e.g. QuickInsertQueue, should not need to know anything about other implementations. (e.g. implementation of QueueItem) i.e. QueueItem does not need to know about what class is implementing PriorityQueue nor does PriorityQueue need to know about the class that implements QueueItem. (For this to work, make sure an in interface has all the methods necessary to allow others to interact with it. Also note that classes can implement multiple interfaces)
Practically,
Unless you are make use of things like factory method pattern and/or IoC containers like Spring or Guice, you will have at the least, an implementation instance (i.e. an object of a class) instantiating other implementations (objects of other classes) in your system.
(In this case, data structure to use so that insertion should be O(1) is an implementation detail quuestion/discussion)

Any problem with doing the main work of a class in its constructor?

I have always felt that in general the main work of a class should be done in its instance methods, while the constructor should only get the instance into a usable inital state.
But I find that in practice there are situations where it seems to make more sense to put essentially all the actual work into the constructor.
One example: I need to retrieve some DBMS-specific information from the database. The most natural way to me seemed to have a class DBMSSpecInfo, with a constructor:
public DBMSSpecInfo(java.sql.Connection conn) throws SQLException{
// ... retrieve info from DBMS
}
/** #returns max size of table in kiB */
public int getMaxTableSize() {//...}
/** #returns max size of index in kiB */
public int getMaxIndexSize() {//...}
/** #returns name of default schema */
public String getDefaultSchema() {//...}
You would construct the class once, the constructor would fetch all data, then you could use various getters to retrieve the info you need.
Of course I could put the method somewhere else, and only use DBMSSpecInfo for the return value (essentially using DBMSSpecInfo only as a value holder), but it feels ugly to create a class just for returning values from a single function.
So what do you think? Are there problems with performing the main work in the constructor? Is it "un-idiomatic" in Java? Or is it an acceptable (though possibly uncommon) practice?
The main practical problem is unit-testing - you won't be able to instantiate the object without doing actual work. (Or you'd have to mock all the classes that participate in this work).
Related talk: OO Design for testability. It gives examples of why doing work in constructors is bad for unit-testing.
I would prefer separating the creation code from the class itself in such cases. It could be put into a static factory method, or a separate factory class (which can also be a public static inner class). The choice depends on the complexity of the code and the design context (which we don't know in this case).
This would also allow you to do optimizations, like caching and reusing the class instance(s).
I'm big on pragmatism. If it works, do it! But in the name of purity and goodness, I'd like to make a design suggestion:
This class muddles up the data content with the mechanism for retrieving it. The object you end up using elsewhere is interesting only for the data it contains. So the "clean" thing to do would be to have a different class for digging out the information and then creating instances of this properties object.
That other class could have a longer lifetime, as you'd typically be calling a method to do the work, not the constructor. The constructor of DBMSSpecInfo might end up assigning a bunch of properties but not doing a lot of error-capable DB access work.
In your example I would make a static method GetDBMSSpecInfo(java.sql.Connection conn) that will return an instance of DBMSSpecInfo object or null if something goes wrong (in case you don't want to throw exceptions).
The DBMSSpecInfo object for me should not contain nothing more than get properties: MaxIndexSize, MaxTableSize, DefaultSchema, etc.
And I would make the constructor of this object private so that instances can only be created from the static method.
I don't think it is a good idea to do the main work in a constructor, since it doesn't have a return value. So it makes error processing more complicated IMO, since it forces you to use exceptions.
A disadvantage of doing the work in the constructor is that constructors can not be overridden (nor should they delegate to overridable methods).
Another is that a constructor is all-or-nothing. If the object contains data whose initializations exhibit indepedent failures, you deprive yourself of the capability to use what data could be procured successfully. Similarly, that you have to initialize the entire object, even if you just need part of it, might adversely affect performance.
On the other hand, doing it in the constructor allows initialization state (here: the connection to the database) to be shared, and released earlier.
As always, different approaches are preferable in different circumstances.
Doing all the work in the constructor can lead to "overload hell". You keep wanting to add more features and instead of just adding a new method, like you would in normal Object-Oriented development, you find yourself adding more and more overloaded constructors. Eventually, the constructors can grow so many overloads and parameters that it becomes unwieldy.
Just be careful that the object is not cloned/deserialised. Instances created this way do not use the constructor.
In my opinion the constructor should be lightweighted and should not throw exceptions.
I'd implement some kind of Load() method to retreive data from the database, or implement lazy loading.
No problem. JDK has a lot of classes that does network IO in constructors.

Categories