4

I want to know if there is a better way to write the following class

public class Helper
{
    public static boolean isMatch(final Collection<ClassA> customList)
    public static boolean containsProperty(final Collection<ClassA> customList, final String property)
}

The way the method is called is:

Helper.isMatch(customList);

What I would like to do is make the call as:

customList.isMatch();

Any advice would be great.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Pranav Shah
  • 3,233
  • 3
  • 30
  • 47
  • 2
    Sounds like you want extension methods such as are available in c#. This question covers some options: http://stackoverflow.com/questions/4359979/java-equivalent-to-c-sharp-extension-methods – Chris Farmer Jan 11 '13 at 21:25
  • 2
    what is isMatch supposed to do? – Farzad Jan 11 '13 at 21:26
  • The only way I see is composition here. – fge Jan 11 '13 at 21:29
  • @Farzad It doesn't matter what isMatch is doing. The point is that all the methods in this class will be working on Collection. So, I am trying to make the code easier to write for someone using this class – Pranav Shah Jan 11 '13 at 21:30
  • @ChrisFarmer Thanks Chris. I think C# is where I might have gotten the inspiration from. I will check the other post. Thanks – Pranav Shah Jan 11 '13 at 21:31
  • Why call it Helper? That could be anything.. Is the namespace include ?.collections.Helper? If not it's not a very good class name. – Matt Wolfe Jan 11 '13 at 21:32
  • @MattWolfe This is just a sample code. – Pranav Shah Jan 11 '13 at 21:40
  • @fge I am not sure how composition will make it such that I don't have to pass the collection as a parameter. – Pranav Shah Jan 11 '13 at 21:41
  • @PranavShah I meant decoration, sorry – fge Jan 11 '13 at 21:42
  • @PranavShah It does matter what "isMatch" is doing. You are using generics. Does "isMatch" behave differently depending on whether it is a Collection or a Collection? Your implementation will be different if you want these methods to behave different depending on what the generic type is. – mightyrick Jan 11 '13 at 21:52
  • @RickGrashel It is always ClassA. – Pranav Shah Jan 11 '13 at 23:00
  • Ok, in that case you can just create MyList and have it extend ArrayList (or whatever collection you prefer). Add your custom methods to that class and enjoy the fact that you inherit all of the other base methods from a Java list. – mightyrick Jan 11 '13 at 23:06

1 Answers1

1

If you use Guava, you can use, for instance, ForwardingList.

It forwards all default List method to the embedded instance, and you can add your own.

More details here.

fge
  • 119,121
  • 33
  • 254
  • 329