Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method accepting two different types as parameter

I am writing a method that should accept as its parameter an object of one of two types which do not share a parent type other than Object. For example, the types are Dreams and Garlic. You can do both dreams.crush() and garlic.crush(). I want to have a method utterlyDestroy(parameter), that would accept as its parameter both Dreams and Garlic.

utterlyDestroy(parameter) {     parameter.crush() } 

Both Garlic and dreams are a part of some library, so having them implement an interface ICrushable (so that I could write utterlyDestroy(ICrushable parameter) ) is not an option.

My method body is quite long so overloading it would mean duplicating code. Ugly. I am sure I could use reflection and do some class hacking. Ugly.

I tried using generics but apparently I cannot write something like

utterlyDestroy(<T instanceof Dreams || T instanceof Garlic> parameter) 

Is it possible to typecast Garlic to Dreams?

utterlyDestroy(Object parameter) {     ((Dreams)parameter).crush() } 

This would still be ugly though. What are my other options and what is the preferred method of dealing with the situation?

like image 279
JohnEye Avatar asked May 27 '12 21:05

JohnEye


People also ask

Can a method accept multiple parameters?

Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):

How do you use the same method with different parameters?

In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }

Can a method have multiple parameters Java?

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

Can a method have two return types in Java?

No, you don't have two return types. It's a generic method you are seeing.


1 Answers

How about this:

interface ICrushable {     void crush(); }  utterlyDestroy(ICrushable parameter) {     // Very long crushing process goes here     parameter.crush() }  utterlyDestroy(Dreams parameter) {     utterlyDestroy(new ICrushable() { crush() {parameter.crush();}); }  utterlyDestroy(Garlic parameter) {     utterlyDestroy(new ICrushable() { crush() {parameter.crush();}); } 

New development should implement the ICrushable interface, but for the existing Classes, the parameter is wrapped in an ICrushable and passed to the utterlyDestroy(ICrushable) that does all the work.

like image 169
Devon_C_Miller Avatar answered Sep 28 '22 03:09

Devon_C_Miller