Use Scala Case Objects for Java Enums? - java

Let's say I have the following object:
object CaseObjs {
trait Person
case object Female extends Person
case object Male extends Person
}
For purposes of Don't Repeat Yourself, I'd like to use these CaseObjs.Male and .Female as an Enum-like data structure in Java.
In other words, I'd like to use these case object's in Java rather than create a new Java enum that duplicates code.
Can I do this?

Short answer: No. See also this question
According to this old post on scala-lang the best way to achieve interoperability is to declare the enum in Java. I haven't found any reason to believe that has changed since then.
Using the different Scala variants will make your Java code look bad, and using Java enums from Scala is straight forward.

You mean you want to index out all children of a sealed class? Then I think this post will help you. Make sure that the implementation assumes that all the children of the class are directly-inheriting case objects. Also scala.Enumeration can be used if those children need not specific implementation.

Related

Java ArrayList subclass extraction

I'm creating an application where I use genetic algorithm (not implemented yet) to make creatures follow food and avoid obstacles.
I have in my simulation class (where the magic happens) an arraylist where all the creatures are stored. To be noted the arraylist is full of abstract class objects whereas my creatures are all a subclass of Creature.
My question is: how can I make another ArrayList or similar where i can iterate over the arraylist and extract a particular subclass? I had a look and it seems there is no way for me to do so because of how java Collections work. Is there any kind of workaround or some library that could make this possible for me?
It is important for me to have separate lists because I need to apply behaviours to different kind of creature and weigh them according to the "dna" of the creature.
GitHub repository for the whole project: https://github.com/Jamesinvi/Animosity/tree/master/Animosity
I tried this but I get a list of all creatures because they are all of the Creature class
//in PSEUDOCODE i would like to do this:
new ArrayList newlist=new ArrayList<Creature>();
for(Creature old:oldList){
if (old instanceof CreatureSubclass){
newlist.add(old);
}
}
Disclaimer: I am a student so forgive me if this is kind of a stupid question but I am struggling a bit with this. Thanks for the help :)
ArrayList <Creature>oldlist=new ArrayList<Creature>();
ArrayList <Creature>newlist=new ArrayList<Creature>();
for(int i=0;i<oldlist.size();i++){
if (oldlist.get(i) instanceof CreatureSubclass){
newlist.add(oldlist.get(i));
}
}
Totally agree with OldCurmudgeon. You should not extract the subclass.
If you really want to do that, one ugly method is to add a string as a member variable to Creature class called flag. So you could use the string comparison instead of instance of which is very dangerous.
if (oldCreature.flag.equals("SmallCreature"))
{
newList.add(oldCreature); // another possible error: do you need a new copy or just reference?
}
And you could consider use enum class instead of string, which would also be a feasible and simple solution.
public enum CreatureName{SmallCreature, LargeCreature}
And again if you want to apply different behaviors onto the different kinds of the subclass (dna), do you have ever considered the design patterns like strategy or abstract class? The visitor pattern may be a good one mentioned by JB Nizet. But it may be overkill for this question.

What is the pros and cons between Enum and enum-based class implementation in Java?

I've recently come across an article discussing the use of an enum-based class implementation in C#, which is quite impressive. The second one here is in Java. However, my colleagues suggest me to use Enum instead.
Could anyone point out any pros and cons using each of them, and when to use it?
The Java article you quote is from 2001. Back then, Java didn't have enums, and the methods the author describes are what programmers used to do back then to work around Java's deficiency. Java 5 introduced enums in 2004 and now the older patterns are obsolete. So your colleagues are rght: you should use enums.
The Java standard enum implementation is already fully class based - you can define any methods, member variables, etc you like inside standard Java enums.
There is an excellent description of this with examples in the official enum documentation:
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Additionally the EnumSet, EnumMap, etc collection classes are extremely powerful and efficient. EnumSet has similar performance to using raw bitfields! You only get access to those classes if you use a proper enum though.
In Java, Enum types act as a class that is declared with their unique name. It is pretty much like the any other class that is designed to create constant values. Recently, I also came across to an info that before the declaration of Enums in Java, an enum like class was created. Just like the article that was suggested on this question, it seems that previous to JVM 1.5, class based enums were widely used.
You can check this source: http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html
I think it is a very good explanation on Java Enums and Why they are created. The article claims 3 advantages for Enum:
1)Type Safety.
2)Unless the class was worked thoroughly, the Enum class was prone to printing problems. When coder wanted a string result to be returned, an primitive value was returned. To my experience, with some additions to the class, this is avoided. But question is, is it convenient for the coder.
3)Again, access was based on an instance of the class. Thus, coder cannot access to the Enum option directly. Coder must use the class name.
As a result: for convenience and code readability issues, Enums are a good choice. Plus, Enum Structure is similar to an individual classes that are nested within a carrier class. If coder wants to enhance the Enum Design and create their own style, they can turn back to the old manually coded class based system.
The major difference is that Java's enums are more simple, one may not switch on the C# enum-based class implementation and enum-based class is more of a class than of an enumerated data type, i.e. it can be extended. Whereas enum can't be derived from another class and can not be extended.
Java alternative for C# enum-based class could be like:
public abstract static class CreditCard {
enum CreditCardType{
AMERICAN_EXPRESS, MASTER, VISA, DISCOVER;
}
CreditCardType type;
public abstract void operation1();
public abstract void operation2();
}
HI I will suggest to use enum if you know how to use it.
because their are many reasons some of them are
uses less memory
having some constant value
less process time
easy to understand
reuseability
easy to debug
like that it is having many advantage but other-hand it is having many disadvantage also like
limited use means we are having some limitation by using enum

How to create an array of the methods of a class in Java

Good day.
I have a class that I’m going to use to generate math exercises for training purposes. The class is made of a series of method, each one of them generates one type of exercises.
I’d like then to make a method that generates one random exercise of a random type. To do this I thought to store the methods name in an array an call a random entry.
So far so good.
Since in the future I’m going to add methods to generate new exercise types, I’d like to know if there is a way to generate dynamically the array of the methods: once the class is loaded, the constructor will check the methods available and store their name in an array.
Is that possible? And, if so, how?
You can use reflection to discover class' methods.
However in my opinion, it's a bad architecture. Better way to handle different exercises is creating an interface IExercise that will be implemented by *Exercise classes. Then create those objects, put them into an array and pick one randomely. Then call specified method from interface or something...
Instead of storing the names you can store Method proxies
Method[] methods = getClass().getDeclaredMethods();
You need to go through these are ignore any method you add which are not tests.
I highy recomend looking up a Strategy Pattern:
http://en.wikipedia.org/wiki/Strategy_pattern
How would you apply it to your problem? Just create objects that imlement common interfaces (one that gives you method for creating the exercise) and use List of this objects.
You will also practice a very useful pattern!
You can use Reflection API to check Available methods using
Method[] methods= Class.forName("ClassTo test").getDeclaredMethods();
Having said that there are so many things can go wrong while invoking a method.
You can avoid it by just having
interface IExercise
{
void createExercise();
}
class Exercise1 implements IExercise
{
#Override
public void createExercise()
{
}
}
And then you can use IExercise[] to generate Exercise Randomly.
I think you are safer by using the Command pattern and storing each exercise as a command class implementing a marker interface (ICommand). Afterwards you can use reflection to detect at run-time all classes that implement ICommand on the classpath to have a list of exercises you can run. This would also save you from having to add every new type of exercise you design in a collection in your random selection code.
http://en.wikipedia.org/wiki/Command_pattern
This is somewhat similar to the Strategy pattern suggested below.
Create objects like:
MathExample math = new MathExample();
And add them to ArrayList<Objects>
I think, it is better to create chain of responsibility and stroe commands in array. Randomly choose command and put to the chain.

Best way to add functionality to built-in types

I wonder what is the best way in terms of strict OOP to add functionality to built-in types like Strings or integers or more complex objects (in my case the BitSet class).
To be more specific - I got two scenarios:
Adding a md5 hashing method to the String object
Adding conversion methods (like fromByteArray() or toInteger()) to the BitSet class.
Now I wonder what the best practices for implementing this would be.
I could e.g. create a new Class "BitSetEx" extending from BitSet and add my methods. But I don't like the idea since this new class would need describing name and "BitSetWithConversionMethods" sound really silly.
Now I could write a class consisting only of static methods doing the conversions.
Well I got a lot of ideas but I wan't to know what would be the "best" in sense of OOP.
So could someone answer me this question?
There are a few approaches here:
Firstly, you could come up with a better name for the extends BitSet class. No, BitsetWithConversionMethods isn't a good name, but maybe something like ConvertibleBitSet is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a HashableString (bearing in mind that you can't extend String, as Anthony points out in another answer). This approach of naming child classes with XableY (or XingY, like BufferingPort or SigningEmailSender) can sometimes be a useful one to describe the addition of new behaviour.
That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc.
So without knowing your design, I would suggest maybe two classes; in the BitSet example, have both a BitSet and (say) a BitSetConverter which is responsible for the conversion. If you wanted to get really fancy, perhaps even:
interface BitSetConverter<T> {
T convert(BitSet in);
BitSet parse(T in);
}
then you might have:
BitSetConverter<Integer> intConverter = ...;
Integer i = intConverter.convert(myBitSet);
BitSet new = intConverter.parse(12345);
which really isolates your changes, makes each different converter testable, etc.
(Of course, once you do that, you might like to look at guava and consider using a Function, e.g. a Function<BitSet, Integer> for one case, and Function<Integer, BitSet> for the other. Then you gain a whole ecosystem of Function-supporting code which may be useful)
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods.
As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so BitSetEx allready sounds better then the BitSetWithConversionMethods you propose.
You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the fromByteArray() you want to make) so you want those methods to be in that class. Extending is the way to go.
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options:
1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality.
2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like
class OurStringUtil {
....
public static int getMd5Hash(String string) {...}
....
}
Take a look at the Apache StringUtils stuff, it follows this approach; it's wonderful.
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it.
Two possible approaches are writing wrappers such as StringWrapper(String) with your extra methods, or some kind of StringUtils class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).

Diff between two instances of same class [duplicate]

This question already has answers here:
find out the differences between two java beans for version tracking
(4 answers)
Closed 6 years ago.
I have two instances of the same class. I need to find property(s) which are different amongst them (basically value of the property, say firstName might be different in both). The fields are primitive, complex as well as collections.
Basically, I need to find differences between two instances and if the fields are different in both the instances, I will copy value of the field from first instance to a third instance (diff object).
I think I can use reflection, but the classes are very complex and it might become error prone.
Your question is a bit unclear. First you said "two instances of the same class", then you said "the classes are very complex". Is this a generic solution to find differences between instances for any class, or is it just a specific case? The other ambiguity is what you mean by "copy the differences". For example, if its a String, then what is the difference between the two strings that would get copied into the new instance? If its a collection, what is the difference between the collections? What if you have two ArrayLists that have the same things in different orders.
If its a specific case, then you can just create a method on the class where you pass in an instance of the same class. Then you can iterate over each field and compare the differences.
public TheClass difference(TheClass that) {
TheClass newClass = new TheClas()
if (this.getName().equals(that.getName()) == false ) {
newClass.setName(that.getName());
}
...
}
But this can get out of hand depending on how deep your object graph is.
Perhaps the builder pattern might come in handy here if you're trying to build a generic/reusable solution. You might look at the Apache Commons code base and see how they implement HashCodeBuilder and ToStringBuilder. They even have a reflection version of the utilities. See how they handle deep and shallow equals.
There is no other way than to use reflection if you want to do it generically. If your fields have getters then you could keep comparing it with equals method. Then you have know the fields at compile time.
write a method like
public YourClass diff(YourClass other) {
// diff code here
}
or
public static YourClass diff(YourClass first, YourClass second) {
// diff code here
}
and wrap some unit tests around the implementations.
Reflection might seem more complicated, but it has the following advantages:
1) It can be generic and you can make the same code work with any class
2) It will not have to be changed if the class evolves.
If you want to go with reflection, you can use Class.getDeclaredFields() (google for "java class api 6") to get all the fields on the class, and then you can use the Field api to get the values for an object. If you wanted to be really fancy, you have a static String[] "diffIgnoredFields" and include field names you want to ignore in the diff.
You need to be careful. Some formulations of this problem are essentially the same as the Subgraph Isomorphism Problem which is known to be NP complete.

Categories

Resources