Java type specific behaviour with generics2019 Community Moderator ElectionConditional behaviour based on concrete type for generic classIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java

What are substitutions for coconut in curry?

Is it true that good novels will automatically sell themselves on Amazon (and so on) and there is no need for one to waste time promoting?

Why do Australian milk farmers need to protest supermarkets' milk price?

Happy pi day, everyone!

How to simplify this time periods definition interface?

Are there other languages, besides English, where the indefinite (or definite) article varies based on sound?

What are the naunces between the use of 訊く instead of 聞く in the following sentence?

How big is a MODIS 250m pixel in reality?

Use of undefined constant bloginfo

If I can solve Sudoku can I solve Travelling Salesman Problem(TSP)? If yes, how?

How to use deus ex machina safely?

Are ETF trackers fundamentally better than individual stocks?

Why did it take so long to abandon sail after steamships were demonstrated?

A sequence that has integer values for prime indexes only:

Why doesn't using two cd commands in bash script execute the second command?

Hacking a Safe Lock after 3 tries

compactness of a set where am I going wrong

Why does Bach not break the rules here?

Who is flying the vertibirds?

What do Xenomorphs eat in the Alien series?

Could the Saturn V actually have launched astronauts around Venus?

How Could an Airship Be Repaired Mid-Flight

How can I track script which gives me "command not found" right after the login?

What should tie a collection of short-stories together?



Java type specific behaviour with generics



2019 Community Moderator ElectionConditional behaviour based on concrete type for generic classIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java










4















The problem is as follows:



There are the entities Box, Boxvalue, Boxstrategy and then as example "IntegerBoxStrategy".
The concept is quite simple, I'd like to put different kind of types in this box. Sometimes there will be an Integer inside this Box, sometimes a String. I want to be able to do specific conversion between these types (so type specific behaviour -> hence my strategy approach. Every type will require a specific strategy to convert) and these types can be specified with an ENUM.



So after googling a lot (though I'm quite sure this question might be marked as duplicate and say that I haven't googled enough ;) ) i'm trying this approach:
https://www.javaspecialists.eu/archive/Issue123.html



Concise summary of this approach: they use a strategy to implement a taxstrategy for taxpayers. UML will be more easy to understand:
UML class diagram for first link
Though in my case, I'd only have one "Taxpayer", aka the BoxType.



fyi: this question is really similar : Conditional behaviour based on concrete type for generic class though -> i want to be able to switch between my BoxValues, and convert "true" into "1". But I think that the approach of the answer might be helpful, Run time type identification. Which in my case would be used to match strategies with their according "supported types".



The problem with the first link is that in every specific strategy implementation, I'm going to have a huge switch. (sample code later on)



My question is not something like "solve this for me please" but more like point me in the general direction. If a simple example could be given how this could be done when you don't have to update every specific strategy implementation when you support a new "boxvaluetype", I'd be really happy. If posssible, I'd like the cleanest design implementation or approach according to the GRASP principles.



 public interface typeStrategy 
boolean canChangeToType(Object myvalue,ValueType type);
boolean correctType(Object myvalue);


class BoolTypeStrategy implements typeStrategy

@Override
public boolean canChangeToType(Object myvalue, ValueType type)
if (correctType(myvalue))
throw new IllegalArgumentException("your initial value should be a boolean!");
switch (type)
case INT:
return true;
case STRING:
return true;
default:
return false;



@Override
public boolean correctType(Object myvalue)
if (!(myvalue instanceof Boolean))
return false;
return true;




In the example, this ValueType is my Enum.



public class BoxValue<T> 
private T value;
private typeStrategy mystrategy;


public BoxValue(T value, typeStrategy strategy)
this.value = value;
this.mystrategy = strategy;


public T getValue()
return value;


public boolean canChangeToType(ValueType type)
return mystrategy.canChangeToType(value, type);




As you can see, huge switches solve the problem.. So what design patterns, what suggestions are recommended to solve this problem? (fyi: I'd like to resolve this in Java 8, as i am aware that there are these strange "var" types in Java10+)










share|improve this question



















  • 1





    Please don't link to external resources without summarizing what's being said there. If the target page goes permanently offline the link will be useless and the question will lack important informations.

    – BackSlash
    Mar 7 at 13:48











  • Got it! I'll update it in a second, thank you for your comment!

    – Wannes Fransen
    Mar 7 at 13:48











  • Edited, if it's still not good enough then i'll write / copy paste parts of the problem / solution.

    – Wannes Fransen
    Mar 7 at 13:55












  • I don't think it's a good idea to have the type itself include the other types it can convert itself to. Conversion is something that is done to the type (or rather, between two types), so I'd see that as a concern for an outside service class.

    – daniu
    Mar 7 at 14:00











  • @daniu , Thank you for your response. Aren't you either 1. creating crazy amount of methods then? 2. Or solving this with method overloading or 3. switch inside switch statements? That is ofcourse all inside of your service class

    – Wannes Fransen
    Mar 7 at 14:10
















4















The problem is as follows:



There are the entities Box, Boxvalue, Boxstrategy and then as example "IntegerBoxStrategy".
The concept is quite simple, I'd like to put different kind of types in this box. Sometimes there will be an Integer inside this Box, sometimes a String. I want to be able to do specific conversion between these types (so type specific behaviour -> hence my strategy approach. Every type will require a specific strategy to convert) and these types can be specified with an ENUM.



So after googling a lot (though I'm quite sure this question might be marked as duplicate and say that I haven't googled enough ;) ) i'm trying this approach:
https://www.javaspecialists.eu/archive/Issue123.html



Concise summary of this approach: they use a strategy to implement a taxstrategy for taxpayers. UML will be more easy to understand:
UML class diagram for first link
Though in my case, I'd only have one "Taxpayer", aka the BoxType.



fyi: this question is really similar : Conditional behaviour based on concrete type for generic class though -> i want to be able to switch between my BoxValues, and convert "true" into "1". But I think that the approach of the answer might be helpful, Run time type identification. Which in my case would be used to match strategies with their according "supported types".



The problem with the first link is that in every specific strategy implementation, I'm going to have a huge switch. (sample code later on)



My question is not something like "solve this for me please" but more like point me in the general direction. If a simple example could be given how this could be done when you don't have to update every specific strategy implementation when you support a new "boxvaluetype", I'd be really happy. If posssible, I'd like the cleanest design implementation or approach according to the GRASP principles.



 public interface typeStrategy 
boolean canChangeToType(Object myvalue,ValueType type);
boolean correctType(Object myvalue);


class BoolTypeStrategy implements typeStrategy

@Override
public boolean canChangeToType(Object myvalue, ValueType type)
if (correctType(myvalue))
throw new IllegalArgumentException("your initial value should be a boolean!");
switch (type)
case INT:
return true;
case STRING:
return true;
default:
return false;



@Override
public boolean correctType(Object myvalue)
if (!(myvalue instanceof Boolean))
return false;
return true;




In the example, this ValueType is my Enum.



public class BoxValue<T> 
private T value;
private typeStrategy mystrategy;


public BoxValue(T value, typeStrategy strategy)
this.value = value;
this.mystrategy = strategy;


public T getValue()
return value;


public boolean canChangeToType(ValueType type)
return mystrategy.canChangeToType(value, type);




As you can see, huge switches solve the problem.. So what design patterns, what suggestions are recommended to solve this problem? (fyi: I'd like to resolve this in Java 8, as i am aware that there are these strange "var" types in Java10+)










share|improve this question



















  • 1





    Please don't link to external resources without summarizing what's being said there. If the target page goes permanently offline the link will be useless and the question will lack important informations.

    – BackSlash
    Mar 7 at 13:48











  • Got it! I'll update it in a second, thank you for your comment!

    – Wannes Fransen
    Mar 7 at 13:48











  • Edited, if it's still not good enough then i'll write / copy paste parts of the problem / solution.

    – Wannes Fransen
    Mar 7 at 13:55












  • I don't think it's a good idea to have the type itself include the other types it can convert itself to. Conversion is something that is done to the type (or rather, between two types), so I'd see that as a concern for an outside service class.

    – daniu
    Mar 7 at 14:00











  • @daniu , Thank you for your response. Aren't you either 1. creating crazy amount of methods then? 2. Or solving this with method overloading or 3. switch inside switch statements? That is ofcourse all inside of your service class

    – Wannes Fransen
    Mar 7 at 14:10














4












4








4


2






The problem is as follows:



There are the entities Box, Boxvalue, Boxstrategy and then as example "IntegerBoxStrategy".
The concept is quite simple, I'd like to put different kind of types in this box. Sometimes there will be an Integer inside this Box, sometimes a String. I want to be able to do specific conversion between these types (so type specific behaviour -> hence my strategy approach. Every type will require a specific strategy to convert) and these types can be specified with an ENUM.



So after googling a lot (though I'm quite sure this question might be marked as duplicate and say that I haven't googled enough ;) ) i'm trying this approach:
https://www.javaspecialists.eu/archive/Issue123.html



Concise summary of this approach: they use a strategy to implement a taxstrategy for taxpayers. UML will be more easy to understand:
UML class diagram for first link
Though in my case, I'd only have one "Taxpayer", aka the BoxType.



fyi: this question is really similar : Conditional behaviour based on concrete type for generic class though -> i want to be able to switch between my BoxValues, and convert "true" into "1". But I think that the approach of the answer might be helpful, Run time type identification. Which in my case would be used to match strategies with their according "supported types".



The problem with the first link is that in every specific strategy implementation, I'm going to have a huge switch. (sample code later on)



My question is not something like "solve this for me please" but more like point me in the general direction. If a simple example could be given how this could be done when you don't have to update every specific strategy implementation when you support a new "boxvaluetype", I'd be really happy. If posssible, I'd like the cleanest design implementation or approach according to the GRASP principles.



 public interface typeStrategy 
boolean canChangeToType(Object myvalue,ValueType type);
boolean correctType(Object myvalue);


class BoolTypeStrategy implements typeStrategy

@Override
public boolean canChangeToType(Object myvalue, ValueType type)
if (correctType(myvalue))
throw new IllegalArgumentException("your initial value should be a boolean!");
switch (type)
case INT:
return true;
case STRING:
return true;
default:
return false;



@Override
public boolean correctType(Object myvalue)
if (!(myvalue instanceof Boolean))
return false;
return true;




In the example, this ValueType is my Enum.



public class BoxValue<T> 
private T value;
private typeStrategy mystrategy;


public BoxValue(T value, typeStrategy strategy)
this.value = value;
this.mystrategy = strategy;


public T getValue()
return value;


public boolean canChangeToType(ValueType type)
return mystrategy.canChangeToType(value, type);




As you can see, huge switches solve the problem.. So what design patterns, what suggestions are recommended to solve this problem? (fyi: I'd like to resolve this in Java 8, as i am aware that there are these strange "var" types in Java10+)










share|improve this question
















The problem is as follows:



There are the entities Box, Boxvalue, Boxstrategy and then as example "IntegerBoxStrategy".
The concept is quite simple, I'd like to put different kind of types in this box. Sometimes there will be an Integer inside this Box, sometimes a String. I want to be able to do specific conversion between these types (so type specific behaviour -> hence my strategy approach. Every type will require a specific strategy to convert) and these types can be specified with an ENUM.



So after googling a lot (though I'm quite sure this question might be marked as duplicate and say that I haven't googled enough ;) ) i'm trying this approach:
https://www.javaspecialists.eu/archive/Issue123.html



Concise summary of this approach: they use a strategy to implement a taxstrategy for taxpayers. UML will be more easy to understand:
UML class diagram for first link
Though in my case, I'd only have one "Taxpayer", aka the BoxType.



fyi: this question is really similar : Conditional behaviour based on concrete type for generic class though -> i want to be able to switch between my BoxValues, and convert "true" into "1". But I think that the approach of the answer might be helpful, Run time type identification. Which in my case would be used to match strategies with their according "supported types".



The problem with the first link is that in every specific strategy implementation, I'm going to have a huge switch. (sample code later on)



My question is not something like "solve this for me please" but more like point me in the general direction. If a simple example could be given how this could be done when you don't have to update every specific strategy implementation when you support a new "boxvaluetype", I'd be really happy. If posssible, I'd like the cleanest design implementation or approach according to the GRASP principles.



 public interface typeStrategy 
boolean canChangeToType(Object myvalue,ValueType type);
boolean correctType(Object myvalue);


class BoolTypeStrategy implements typeStrategy

@Override
public boolean canChangeToType(Object myvalue, ValueType type)
if (correctType(myvalue))
throw new IllegalArgumentException("your initial value should be a boolean!");
switch (type)
case INT:
return true;
case STRING:
return true;
default:
return false;



@Override
public boolean correctType(Object myvalue)
if (!(myvalue instanceof Boolean))
return false;
return true;




In the example, this ValueType is my Enum.



public class BoxValue<T> 
private T value;
private typeStrategy mystrategy;


public BoxValue(T value, typeStrategy strategy)
this.value = value;
this.mystrategy = strategy;


public T getValue()
return value;


public boolean canChangeToType(ValueType type)
return mystrategy.canChangeToType(value, type);




As you can see, huge switches solve the problem.. So what design patterns, what suggestions are recommended to solve this problem? (fyi: I'd like to resolve this in Java 8, as i am aware that there are these strange "var" types in Java10+)







java design-patterns switch-statement






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 13:54







Wannes Fransen

















asked Mar 7 at 13:40









Wannes FransenWannes Fransen

365




365







  • 1





    Please don't link to external resources without summarizing what's being said there. If the target page goes permanently offline the link will be useless and the question will lack important informations.

    – BackSlash
    Mar 7 at 13:48











  • Got it! I'll update it in a second, thank you for your comment!

    – Wannes Fransen
    Mar 7 at 13:48











  • Edited, if it's still not good enough then i'll write / copy paste parts of the problem / solution.

    – Wannes Fransen
    Mar 7 at 13:55












  • I don't think it's a good idea to have the type itself include the other types it can convert itself to. Conversion is something that is done to the type (or rather, between two types), so I'd see that as a concern for an outside service class.

    – daniu
    Mar 7 at 14:00











  • @daniu , Thank you for your response. Aren't you either 1. creating crazy amount of methods then? 2. Or solving this with method overloading or 3. switch inside switch statements? That is ofcourse all inside of your service class

    – Wannes Fransen
    Mar 7 at 14:10













  • 1





    Please don't link to external resources without summarizing what's being said there. If the target page goes permanently offline the link will be useless and the question will lack important informations.

    – BackSlash
    Mar 7 at 13:48











  • Got it! I'll update it in a second, thank you for your comment!

    – Wannes Fransen
    Mar 7 at 13:48











  • Edited, if it's still not good enough then i'll write / copy paste parts of the problem / solution.

    – Wannes Fransen
    Mar 7 at 13:55












  • I don't think it's a good idea to have the type itself include the other types it can convert itself to. Conversion is something that is done to the type (or rather, between two types), so I'd see that as a concern for an outside service class.

    – daniu
    Mar 7 at 14:00











  • @daniu , Thank you for your response. Aren't you either 1. creating crazy amount of methods then? 2. Or solving this with method overloading or 3. switch inside switch statements? That is ofcourse all inside of your service class

    – Wannes Fransen
    Mar 7 at 14:10








1




1





Please don't link to external resources without summarizing what's being said there. If the target page goes permanently offline the link will be useless and the question will lack important informations.

– BackSlash
Mar 7 at 13:48





Please don't link to external resources without summarizing what's being said there. If the target page goes permanently offline the link will be useless and the question will lack important informations.

– BackSlash
Mar 7 at 13:48













Got it! I'll update it in a second, thank you for your comment!

– Wannes Fransen
Mar 7 at 13:48





Got it! I'll update it in a second, thank you for your comment!

– Wannes Fransen
Mar 7 at 13:48













Edited, if it's still not good enough then i'll write / copy paste parts of the problem / solution.

– Wannes Fransen
Mar 7 at 13:55






Edited, if it's still not good enough then i'll write / copy paste parts of the problem / solution.

– Wannes Fransen
Mar 7 at 13:55














I don't think it's a good idea to have the type itself include the other types it can convert itself to. Conversion is something that is done to the type (or rather, between two types), so I'd see that as a concern for an outside service class.

– daniu
Mar 7 at 14:00





I don't think it's a good idea to have the type itself include the other types it can convert itself to. Conversion is something that is done to the type (or rather, between two types), so I'd see that as a concern for an outside service class.

– daniu
Mar 7 at 14:00













@daniu , Thank you for your response. Aren't you either 1. creating crazy amount of methods then? 2. Or solving this with method overloading or 3. switch inside switch statements? That is ofcourse all inside of your service class

– Wannes Fransen
Mar 7 at 14:10






@daniu , Thank you for your response. Aren't you either 1. creating crazy amount of methods then? 2. Or solving this with method overloading or 3. switch inside switch statements? That is ofcourse all inside of your service class

– Wannes Fransen
Mar 7 at 14:10













0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55045232%2fjava-type-specific-behaviour-with-generics%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55045232%2fjava-type-specific-behaviour-with-generics%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page