This is not about BrainF*ck. Please refer to the last section for the "ultimate" question.
I am terribly sorry, if that has been asked before, but I just couldn't find a page where this has been asked before.
I basically have a java project set up, that let's you write BrainF*ck code and then execute it. For those who don't know, BrainF*ck is a very simple programming language that only uses one-character commands.
I have set it up to where all the implemented letters have individual classes that extend to a Token superclass.
public abstract class Token {
private final char token;
public Token(char c) {
this.token = c;
}
public final char getToken() {
return token;
}
public abstract void tokenCalled();
}
So as an example, for the Token '+' I would have the class set up like this.
public class PlusToken extends Token {
public PlusToken() {
super('+');
}
#Override
public void tokenCalled() {
//increment value by 1
}
}
This works all fabulously well.
Now for my project, I wanted the user to be able to create his own classes and put them in a pre-existent folder where my program will loop through the classes and include those Tokens into my projects. I have an arraylist set up that contains all the Tokens, so the only problem I'm having is: How do I read those classes, check if they are instances of Token and save those in my arraylist to use them?
This is about Java's reflection. Keywords for search: "java reflect all subclasses", and you will find a lot.
How do you find all subclasses of a given class in Java?
The "ClassPathScanningCandidateComponentProvider" answer may meet your need.
But in my opinion, there are simpler word-arounds. Something like following will simplely do the job:
public abstract class Token {
public static HashMap<Character, Class<Token>> all = new HashMap<Character, Class<Token>>();
private final char token;
public Token(char c) {
this.token = c;
all.put(c, this.getClass());
}
public final char getToken() {
return token;
}
public abstract void tokenCalled();
}
Related
In my Android application I have a class which gives me static string values; something like this:
public class VehicleInfo {
public static String getVehicleEnginePower(boolean isNew) {
return isNew ? "1800CC" : "1600CC";
}
}
Now I have another category, so I will have to pass another Boolean, and I will get the value I need. However, these categories will keep on increasing. So I looked into the Open/Closed principle which looks promising for quick enhancement. To ensure this I will make the VehicleInfo class as an Interface and then I will have other classes implement VehicleInfo.
public interface VehicleInfo {
String getVehicleEnginePower();
}
public class NewVehicle implements VehicleInfo {
#Override
public String getVehicleEnginePower() {
return "1800CC";
}
}
and the other category classes will also be something like this. In this way I will have to add another class for all the new categories.
The question I wanted to ask is: is there a way that I can have single instance of this interface? Because in the whole application flow, a user will only be able to see one category until he switches to another category.
I don't want to instantiate these classes at multiple points. To clarify my question, I want to do something like this at the start of my application:
if (isNew) {
VehicleInfo vehicleInfor = new NewVehicle();
}
And in the whole application, whenever I call VehicleInfo.getVehicleEnginePower, it should always return engine power from the NewVehicle class.
Is something like this possible? Or am I just being silly and I will have to instantiate this interface on multiple points?
Maybe you need a singleton here
public class VehicleInfoManager {
private static VehicleInfoManager INSTANCE = new VehicleInfoManager();
private VehicleInfo currentVehicleInfo;
public static VehicleInfoManager getInstance() {
return INSTANCE;
}
public void setCurrentVehicleInfo(VehicleInfo info) {
this.currentVehicleInfo = info;
}
public String getVehicleEnginePower() {
return this.currentVehicleInfo.getVehicleEnginePower();
}
private VehicleInfoManager() {
// Constructor private by default
}
}
Then you can call it from everywhere like this
VehicleInfoManager.getInstance().getVehicleEnginePower()
//Or set current info like this
VehicleInfoManager.getInstance().setCurrentVehicleInfo(new NewVehicle())
Just be careful as currentVehicleInfo is null by default so you need to handle null pointer cases.
If I understand your question correctly.
My solution to this would be Enum
public enum VehicleEnginePower {
NEW ("1800CC"),
OLD ("1600CC"),
private final String name;
private Modes(String s) {
name = s;
}
public String toString() {
return this.name;
}
}
Then you can do
if (isNew) {
String powerOfEngine = VehicleEnginePower.NEW.toString();
}
I'm trying to write a web service method that has a an object as one of it's parameters and that object has a property that is another object type. There seems to be no problem with passing in a object as long as all of the objects properties are primitive types. As soon as one of the properties is another object it has issues even if that embedded object is made of all primitives.
I'm using SoapUI to test it and the error I get is org.xml.sax.SAXException: No deserializer for {http://WebService}MyEmbeddedObject
I'm thinking there must be an easy way to tell it to deserialize the embedded object too but can't for the life of me figure out how. At this point I'll take the hard way too I just need a solution, I can always try to improve it later.
The method in the web service I'm writing looks like this:
public boolean MethodName(MyObject object, String sessionID) throws Exception
{
//do Stuff
}
The MyObject Class looks like this:
public class MyObject implements java.io.Serializable
{
public String Description;
public MyEmbeddedObject Thing1;
public MyEmbeddedObject Thing2;
public MyEmbeddedObject[] Things;
}
The MyEmbeddedObject Class looks like this:
public class MyEmbeddedObject implements java.io.Serializable
{
public String SubThing1;
public String SubThing2;
public String SubThing3;
}
In my case this problem had nothing to do with implementing java.io.Serializable. In fact you could remove that and it will work just fine as long as you fix the actual problem.
The actual problem being that you can't use an object as an argument unless all of it's properties are primitive types UNLESS you also use that embeded object in the method itself. It seems to be some sort of compiler voodoo if you ask me but here's the solution in code. Hopefully this makes sense. I'll even take it one level deeper just for illustration purposes.
One thing you'll notice that I've changed in the solution is that the "MyEmbeddedObject" class is much more complicated looking. This is because I didn't know how to properly define arrays in java at the time I asked this question. I assumed it was the same as C# and unfortunately for me that compounded my problem but I eventually figured it out by banging my head long enough and reviewing sample code from the vendor this project is for.
Program
public boolean MethodName(MyObject object, String sessionID)
{
//do Stuff
}
public MyEmbeddedObject unusedMyEmbeddedObject()
{
return null;
}
public MyDoubleEmbeddedObject unusedMyDoubleEmbeddedObject()
{
return null;
}
In a separate class file
public class MyObject
{
public String description;
public MyEmbeddedObject thing1;
public MyEmbeddedObject thing2;
}
In a separate class file
public class MyEmbeddedObject
{
public MyDoubleEmbeddedObject subThing1;
private MyDoubleEmbeddedObject[] subThings;
public MyDoubleEmbeddedObject[] getSubThings()
{
return this.subThings;
}
public void setSubThings(final MyDoubleEmbeddedObject[] value)
{
this.subThings = value;
}
}
In a separate class file
public class MyDoubleEmbeddedObject
{
public String subSubString1;
public String subSubString2;
public String subSubString3;
}
I know that it isn't possible to extend enum in Java, but I am trying to find an elegant solution for the below
I am trying to model enums (or classes) which will contain http end points of various web services across regions, say I have service A and B, each will have 4 region specific end points in US, EU, JP or CN. (This is basically for some seperate debug code that I am writing, in production the end points will be picked from configuration)
I was hoping to do something like this (not compliant java code).
public enum IEndPoint {
NA_END_POINT,
EU_END_POINT,
JP_END_POINT,
CN_END_POINT,
}
public enum ServiceAEndPoint extends IEndPoint {
NA_END_POINT("http://A.com/");
EU_END_POINT("http://A-eu.com/");
JP_END_POINT("http://A-jp.com/");
CN_END_POINT("http://A-cn.com/");
}
I could do this using interfaces where I have a method for each region, but in my opinion the enum way is more expressive, is there any better way I could model this ? What I am looking for is if there is any better way to model the inheritence relation and also having the expressive power of enumerations.
ServiceAEndPoint.NA_END_POINT
vs
serviceAEndPoint.getNAEndPoint()
I'm assuming that you will also want a ServiceBEndPoint enum (and similar). In which case I don't think your model really makes that much sense.
IEndPoint is really an enumeration of the kind of environments/regions where a service might be running. It is not an enumeration of the services themselves. Each individual service (A, B or whatever) will have different addresses for each of the regions.
Therefore I would stick with just the IEndPoint enum, and then in some service-specific code have a lookup map that will give you the address for a given end-point. Something like this:
public enum IEndPoint {
NA_END_POINT,
EU_END_POINT,
JP_END_POINT,
CN_END_POINT,
}
public class ServiceABroker {
private static final Map<IEndPoint, String> addressesByEndPoint;
static {
addressesByEndPoint = new EnumMap<>();
addressesByEndPoint.put(NA_END_POINT, "http://A.com/");
addressesByEndPoint.put(EU_END_POINT, "http://A-eu.com/");
addressesByEndPoint.put(JP_END_POINT, "http://A-jp.com/");
addressesByEndPoint.put(CN_END_POINT, "http://A-cn.com/");
}
public String getAddressForEndPoint(IEndPoint ep) {
return addressesByEndPoint.get(ep);
}
}
If these are static final constants, then just put them in an interface. Name the interface something like IServiceAEndPointKeys, where the keys part is a convention.
Here's where I consider enums to be more appropriate and useful:
Example 1: File type. An enum containing jpg, pdf etc.
Example 2: Column definitions. If I have a table with 3 columns, I would write an enum declaring ID, Name, Description (for example), each one having parameters like column header name, column width and column ID.
Im not sure I understand you question, but you can add methods to an enum for example you could do something like the following:
public enum ServiceAEndPoint{
NA_END_POINT("http://A.com/");
EU_END_POINT("http://A-eu.com/");
JP_END_POINT("http://A-jp.com/");
CN_END_POINT("http://A-cn.com/");
private final String url;
private EndPoint(String url){
this.url=url;
}
public String getURL(){
return url;
}
}
Enums cannot be extended in such a manner, mostly because enums cannot be sub-classed or the constraints they must adhere to will not be possible to impose.
Instead leverage interfaces, like so
public interface IEndPoint;
public enum DefaultEndPoints implements IEndPoint {
NA_END_POINT,
EU_END_POINT,
JP_END_POINT,
CN_END_POINT,
}
public enum DefaultServiceEndPoints implements IEndPoint {
NA_END_POINT("http://A.com/");
EU_END_POINT("http://A-eu.com/");
JP_END_POINT("http://A-jp.com/");
CN_END_POINT("http://A-cn.com/");
}
public void doSomething(IEndPoint endpoint) {
...
}
The reason why one can't subclass in the manner you wish is related to the contract that enums will be both equal via .equals(object) and via ==. If you could subclass, would this make sense?
if ( (DefaultEndPoints)JP_END_POINT == (DefaultServiceEndPoints)JP_END_POINT) {
}
if you say "yes" then I would expect to be able to do this
DefaultEndPoint someEndpoint = DefaultServiceEndPoints.JP_END_POINT;
which would leave a door open for error, as there is no guarantee that a enum entry in one enum declaration is in the other enum declaration.
Could it be different? Perhaps, but it isn't, and changing it would definately introduce a lot of complications that would have to be thoroughly thought out (or it would open avenues to work around Java's strong static-type checking).
You may want to consider something like this:
public abstract class EndpointFactory {
public abstract String getNAEndPoint();
public abstract String getEUEndPoint();
}
public class ServiceAEndpointFactory extends EndpointFactory {
public static final String NA_END_POINT = "http://A.com/";
public static final String EU_END_POINT = "http://A-eu.com/";
public String getNAEndPoint() {
return ServiceAEndpointFactory.NA_END_POINT;
}
public String getEUEndPoint() {
return ServiceAEndpointFactory.EU_END_POINT;
}
}
public class ServiceBEndpointFactory extends EndpointFactory {
public static final String NA_END_POINT = "http://B.com/";
public static final String EU_END_POINT = "http://B-eu.com/";
public String getNAEndPoint() {
return ServiceAEndpointFactory.NA_END_POINT;
}
public String getEUEndPoint() {
return ServiceAEndpointFactory.EU_END_POINT;
}
}
Then you can refer to your strings directly like this:
ServiceAEndpointFactory.NA_END_POINT;
Or, you can use the base object if the type of service is not known until execution:
EndpointFactory ef1 = new ServiceAEndpointFactory();
String ep = ef1.getNAEndPoint();
The drawback of this is the redefinition of the get*Endpoint() functions in each sub-class. You could eliminate that by moving the static final variables to be not static in the base class and putting the getter/setter in the base class only one time. However, the drawback of that is you are not able to reference the values without instantiating an object (which essentially emulates what I find valuable with ENUMs).
How does a pattern like this appeal to you? I let the enum implement an interface and implement the interface in a Debug set and a Release set. The release set can then derive the property name from the enum name - which is neat.
public interface HasURL {
public String getURL();
}
public enum DebugEndPoints implements HasURL {
NA,
EU,
JP,
CN;
#Override
public String getURL() {
// Force debug to go to the same one always.
return "http://Debug.com/";
}
}
public enum NormalEndPoints implements HasURL {
NA,
EU,
JP,
CN;
final String url;
NormalEndPoints () {
// Grab the configured property connected to my name.
this.url = getProperty(this.name());
}
#Override
public String getURL() {
return url;
}
}
How do you deal with having only single inheritance in java? Here is my specific problem:
I have three (simplified) classes:
public abstract class AbstractWord{
String kind; // eg noun, verb, etc
public String getKind(){ return kind; }
}
public class Word extends AbstractWord{
public final String word;
ctor...
public void setKind(){
// based on the variable word calculate kind..
}
}
public class WordDescriptor extends AbstractWord{
ctor..
public void setKind(String kind){this.kind = kind;}
}
This is what I consider my most basic implementation but I want to make other implementations.
Lets say that I want to add a new variable say wordLength but I want to add it using inheritance. Meaning I do NOT want modify that original AbstractWord class. Ie something along the lines of this:
public class Length{
private int length;
public int getLength(){return length};
}
public class BetterWord extends AbstractWord AND Length{
public void setLength(){
// based on the variable word calculate Length..
}
}
public class BetterWordDescriptor extends AbstractWord AND length{
public void setLength(int length){this.length = length;}
}
I know that java does not let me do this but it has made my code very ugly. Right now whenever I add a field I am just adding it to AbstractWord but then I either need to rename that AbstractWord (and Word and WordDescriptor). (I can't just add the field to the other one because of backwards compatibility, it break equals methods and stuff like that).
This seems like a pretty common design issue but I have racked my head and I cannot come up with any beautiful solutions.
Is there a design pattern that addresses this? I have some potential solutions but I wanted to see if there was something that I was missing.
thanks,
Jake
Update: Length refers to the number of syllables in the word (sorry about the lack of clarity)
Favor composition over inheritance.
Solution takes into consideration that there could be another type of word that may need WordLengthSupport.
Similarly other interfaces could be created and implemented and various word types can have mix and match of those interfaces.
.
public class WordLength {
private int length = 0;
public int getLength(){return length};
public void setLength(int length){this.length = length};
}
.
public interface WordLengthSupport {
public WordLength getWordLength();
}
.
public class BetterWord extends AbstractWord
implements WordLengthSupport {
WordLength wordLength;
public WordLength getWordLength() {
if(wordLength==null) {
// each time word changes
// make sure to set wordLength to null
calculateWordLength();
}
return wordLength;
}
private void calculateWordLength() {
// This method should be
// called in constructor
// or each time word changes
int length = // based on the variable word calculate Length..
this.wordLength = new WordLength();
this.wordLength.setLength(length);
}
}
.
public class BetterWordDescriptor extends AbstractWord
implements WordLengthSupport {
WordLength wordLength;
public WordLength getWordLength(return wordLength);
public void setWordLength(WordLength wordLength) {
// Use this to populate WordLength of respective word
this.wordLength = wordLength;
}
}
.
The Strategy Pattern deļ¬nes a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
This solution does not use strategy pattern but can be refactored for same.
Just use composition instead of inheritance:
a BetterWord is-an AbstractWord that has-a Length:
public class BetterWord extends AbstractWord {
private Length length;
public void setLength(int value){
length.setLength(value);
}
}
EDIT
If the API needs an object of type Length, just add a getter:
public class BetterWord extends AbstractWord {
private Length length;
public void setLength(int value){
length.setLength(value);
}
public Length getLength() {
return length
}
}
Or rename the implementation Length to LengthImpl and define an interface Length, because a class can implement multiple interfaces.
With your specific example you could use the decorator pattern in conjunction with interfaces to supplement your Word class with additional functionality; e.g.
// *Optional* interface, useful if we wish to reference Words along with
// other classes that support the concept of "length".
public interface Length {
int getLength();
}
// Decorator class that wraps another Word and provides additional
// functionality. Could add any additional fields here too.
public class WordExt extends AbstractWord implements Length {
private final Word word;
public class(Word word) {
this.word = word;
}
public int getLength() {
return word.getKind().length();
}
}
In addition it's worth noting that the lack of multiple inheritence in Java isn't really the issue here; it's more a case of reworking your design. In general it's considered bad practice to over-use inheritence as deep inheritence hierarchies are difficult to interpret / maintain.
Looking at it, my first feeling is that your model is a bit complicated.
A word has a String to describe the word itself being stored in the Word object along with a class to say it's a noun, verb, adjective, etc. Another property of a Word is the length of the string stored in the Word object.
Think of things in terms of "is-a" and "has-a" relationships and you can remove a lot of complexity.
For instance why do you need a WordDescriptor that extends AbstractWord? Is a word going to change from a verb to an adjective? I would have thought that the word type was set when the object was created and would not change during the lifetime of the Word object. Once you had a Word object for the word "Australia" the Kind of word would not change for the lifetime of the object.
Hmmm. Maybe you might have a Word object representing the word "bark" after instantiating the object with a type of "verb" to describe the sound a dog makes. Then you realise that you actually needed to have the Word object to represent a noun that describes the covering of a tree. Possible, but both the dog's bark and the tree's bark can exist.
So I think the model you've chosen is a bit too complicated and that your question can be resolved by going back and simplifying your original object model.
Start by asking yourself a question for each of the inheritance aspects of your basic model.
When I say Class B extends Class A, can I say that Class B "is-a" Class A and that I am specialising its behaviour?
For example, a base class Animal can be extended to provide the specialised class of Kangaroo. Then you can say that "the kangaroo "is-a" Animal. You are specialising the behaviour.
Then look at the attributes, a Kangaroo has a Location attribute to describe where it is found. Then you can say a Kangaroo "has-a" location. A Kangaroo "is-a" location doesn't make sense.
Similarly, a Word "has-a" length. And the statement a Word "is-a" length just doesn't make sense.
BTW All Australian references in this post are deliberate to celebrate Australia Day which is today 26th January!
HTH
(I can't just add the field to the other one because of backwards compatibility, it break equals methods and stuff like that).
It won't break source compatibility. Not unless you're doing something really crazy in your equals methods.
And renaming your classes is generally not the way to handle binary compatibility.
The problem is not "how to deal with single inheritance". What you're missing is not really a design pattern but learning to design the API separately from the implementation.
I would implement it like so:
public interface WordDescriptor {
void getKind();
Word getWord();
}
public interface Word {
String getWord();
}
public class SimpleWord implements Word {
private String word;
public SimpleWord(String word) { this.word = word; }
public String getWord() { return word; }
}
public class SimpleWordDescriptor implements WordDescriptor {
private Word word;
private String kind;
public SimpleWordDescriptor(Word word, String kind) {
this.word = word;
this.kind = kind; // even better if WordDescriptor can figure it out internally
}
public Word getWord() { return word; }
public String getKind() { return kind; }
}
With this basic setup, when you want to introduce a length property, all you have to do is this:
public interface LengthDescriptor {
int getLength();
}
public class BetterWordDescriptor extends SimpleWordDescriptor
implements LengthDescriptor {
public BetterWordDescriptor(Word word, String kind) {
super(word, kind);
}
public int getLength() { getWord().length(); }
}
The other answers that uses composition of properties as well as the Decorator pattern are also entirely valid solutions to your problem. You just need to identify what your objects are and how "composable" they are, and how they are to be used - hence designing the API first.
/**
* First example
*/
class FieldsOfClassA {
public int field1;
public char field2;
}
interface IClassA {
public FieldsOfClassA getFieldsA();
}
class CClassA implements IClassA {
private FieldsOfClassA fields;
#Override
public FieldsOfClassA getFieldsA() {
return fields;
}
}
/**
* seems ok for now
* but let's inherit this sht
*/
class FieldsOfClassB {
public int field3;
public char field4;
}
interface IClassB extends IClassA {
public FieldsOfClassA getFieldsA();
public FieldsOfClassB getFieldsB();
}
class CClassB implements IClassB {
private FieldsOfClassA fieldsA;
private FieldsOfClassB fieldsB;
#Override
public FieldsOfClassA getFieldsA() {
return fieldsA;
}
#Override
public FieldsOfClassB getFieldsB() {
return fieldsB;
}
}
/**
wow this monster got bigger
imagine that you will need 4 lvl of inheritance
it would take so much time to write this hell
I'm even not talking that user of those iface will think
what fields i will need fieldsA fieldsB fieldsC or another one
So composition does not work here
and your pathetic tries are useless
When u think about Oject Oriented programming
u need BIG models with 6-7 lvls of multiple inheritance
because that is good test and because corresponds to models of real life or math models tested by civilization for 4 thousands years.
If your models require 2 lvl of inheritance stop pretending u using OO
U can easily implement it with any language even procedural one like C or Basic language
*/
I have been struggling for some time trying to define a generic interface, but I fail to
achieve what I want. The following is a simplified example of the problem.
Let's say I have a generic Message class
public class Message<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
and then I want to define an interface for transfering things:
public interface Transfer<Message<T>> {
public void send(Message message);
}
The problem is that the compiler does not accept this, and always complains about
the second '<' character, no matter what variations I try.
How do I specify this interface so that it is bound to a generic type (based on Message)
and also have access to the parameterized type?
My plan was to use this interface like the following:
public class Carrier<Message<T>> implements Transfer<Message<T>> {
public void send(Message message) {
T content = message.getContent();
print(content);
}
public static void print(String s) {
System.out.println("The string equals '" + s + "'");
}
public static void print(Integer i) {
System.out.println("The integer equals " + i);
}
public static void main(String[] args) {
Carrier<Message<String>> stringCarrier = new Carrier<Message<String>>();
Message<String> stringMessage = new Message<String>("test");
stringCarrier.send(stringMessage);
Carrier<Message<Integer>> integerCarrier = new Carrier<Message<Integer>>();
Message<Integer> integerMessage = new Message<Integer>(123);
integerCarrier.send(integerMessage);
}
}
I have done some searching and reading (among other things Angelika's generics faq), but I am not able to tell if this is not possible or if I am doing it wrong.
Update 2009-01-16: Removed the original usage of "Thing" instead of "Message< T >" (which was used because with that I was able to compile without getting syntax errors on the interface).
It looks to me like you want:
public class Carrier<Thing extends Message<Foo>, Foo>
implements Transfer<Thing>
That way the compiler will know that thing is a Message<Foo> and will therefore have a getContent() method.
You'll need to use it as:
Carrier<Message<String>, String>
But you've currently got a bit of a disconnect. You're implementing Transfer<Thing> but you're trying to use thing as if it's a Message<Thing> look at your send method - you're calling it with a String and an Integer. Those classes don't have getContent() methods.
I suspect you should actually be implementing Transfer<Message<Thing>> instead of Transfer<Thing>
Regardless of how you solve your generics problem, your code will not compile because you do not have a print method that takes a type of T as a parameter.
I believe you will have to do instance of checks if you want the functionality you are looking for. So, I don't think you gain any value from the generic type in this case.
You only need to specify T for the class, and then use Message< T > for your argument/return types.
public interface Transfer<T> {
public void send(Message<T> message);
}
The reason you don't use Message< T > is because you're providing the 'this is a message' context in your arguments and return types.