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

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived