yns
yns

Reputation: 450

checking the number of arguments before calling the method in Java

In my program, I have a method which is below;

private void foo(String title, String[] subtitles, int ... subtitleValues)

My requirement is ;

I don't want to take both arguments and check their counts in foo function and say your table can not be created because of unequal subtitles and subtitleValues. What I want is; prevent user to send unequal arguments. How can I do that?

Thanks in advance

PS : I didn't find a proper title, so if you have, please feel free to change it.

Upvotes: 0

Views: 130

Answers (3)

Joachim Sauer
Joachim Sauer

Reputation: 308021

You can't do it like this. What you can do to make your method harder to call wrongly is to use a fluent API for a builder like this:

class FooBuilder {
  public static FooBuilder withTitle(String title);
  public FooBuilder withSubtitle(String subtitle, int subtitleValue);
  public Foo build();
}

I left out the implementation for brevity. Then you can call it like this:

Foo foo = FooBuilder.withTitle("MyTitle").withSubtitle("st1", 1).withSubtitle("st2", 2).build();

Upvotes: 4

Jan Zyka
Jan Zyka

Reputation: 17898

In this case you should create probably separate class Subtitle which represents subtitles. And create appropriate constructor or method for adding subtitles one by one.

Then rephrase your foo method as:

private void foo(String title, List<Subtitle> subtitles)

Upvotes: 0

Buhb
Buhb

Reputation: 7149

Create a class containing a subtitle, subtitleValue pair. Have your method accept a vararg (or list, or array) of instances of this class.

Upvotes: 2

Related Questions