Skip to content

Commit 36e7e89

Browse files
committed
d minimum vararg
1 parent 2e2425a commit 36e7e89

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.spun.util;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
public class MinimumVarargSamples
6+
{
7+
@Test
8+
void testCompilation()
9+
{
10+
// begin-snippet: minimalVarargsException
11+
int smallest = findSmallest();
12+
// end-snippet
13+
}
14+
// begin-snippet: minimalVarargsRuntime
15+
public Integer findSmallest(Integer... numbers)
16+
{
17+
if (numbers == null || numbers.length < 1)
18+
{ throw new IllegalArgumentException("you must have at least one number"); }
19+
// rest of the code
20+
// end-snippet
21+
return 42;
22+
}
23+
// begin-snippet: minimalVarargsCompileTime
24+
public Integer findSmallest(Integer first, Integer... numbers)
25+
{
26+
Integer[] combined = ArrayUtils.combine(first, numbers);
27+
// rest of the code
28+
// end-snippet
29+
return 42;
30+
}
31+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<a id="top"></a>
2+
3+
# How to create non-empty arrays with var args
4+
5+
toc
6+
7+
## The problem
8+
9+
Let's say you want to accept a variable amount of arguments, but you have a minimum of one that is required.
10+
Most solutions for this occur at runtime. Of course, it would be better if they occurred at compile time.
11+
12+
### Runtime solution
13+
14+
snippet: minimalVarargsRuntime
15+
16+
### Compile time solution
17+
18+
An easy way to deal with this is force the first parameter by declaring it explicitly.
19+
If you do this, you will want to recombine this array almost immediately `ArrayUtils.combine(T, T...)` is an elegant way to do this.
20+
Please be aware that it will not work with primitives.
21+
22+
snippet: minimalVarargsCompileTime
23+
24+
### Advantages
25+
26+
If you use the runtime solution, the following will compile but throw an error when you run it.
27+
If you use the compile time solution, it will not compile.
28+
29+
snippet: minimalVarargsException
30+
31+
### Where to use this
32+
33+
Even though this only adds a small amount of complexity, we don't tend to use it for methods that are only called internally.
34+
However, it is highly suggested if you have a public facing method.
35+
36+
Following the philosophy of [poka-yoke](https://en.wikipedia.org/wiki/Poka-yoke) or mistake proofing.

0 commit comments

Comments
 (0)