I have a curious question, I hope someone can help me.
I am using Java.
I receive a Set from a method. This TypeA is exactly what I want, but I would like to add some more functionalities to it, in order to increase code cleanness.
In C# I could write Extension Methods, but I don’t think Java has something like that, so I would like to create a new type, TypeB, that contains a TypeA variable and performs the extra function that I want (something like an Wrapper/Adapter). but the problem is:
I can’t do
Set<TypeB> mySet = myMethod();
or
Set<TypeB> mySet = (Set<TypeB>)myMethod();
What would be perfect would be something like that
Set<TypeB> mySet = new Set<TypeB>(myMethod());
But Set is a Java type, so I can’t add a constructor to it.
How could I do so I can parse it in a clean way?
If I add a method like
Set<TypeB> mySet = parse(myMethod());
I would have to iterate through all items in myMethod, which would not be very performatic.
Is there any better solution than creating this method?
Thanks,
Oscar
What if you added functionality not by inheriting from TypeA, but by using functions (static methods):
So instead of:
Write:
C# extension methods are just syntactic sugar for this technique anyway.
This is one of my favorite design patterns. I call it “functions”, and it is highly underrated. 😛
If you can’t do it this way (and thus you wouldn’t be able to with extension methods either), then you must be adding state to TypeA, in which case you have to allocate more memory for each object in your set, which means you can’t avoid iterating.