Write a FeatureFlags class with a private nested Flag class and a private map; offer public methods to enable a flag for a percentage of users and to test whether a given user ID gets it (deterministically).
Solution
Main.java
import java.util.HashMap;
import java.util.Map;
final class FeatureFlags {
private static final class Flag { // private: callers never see this type
final int percent;
Flag(int percent) { this.percent = percent; }
}
private final Map<String, Flag> flags = new HashMap<>();
public void enable(String name, int percent) {
if (percent < 0 || percent > 100) throw new IllegalArgumentException("0-100");
flags.put(name, new Flag(percent));
}
public boolean isOn(String name, int userId) {
Flag f = flags.get(name);
return f != null && bucket(name, userId) < f.percent;
}
private static int bucket(String name, int userId) { // stable 0-99 bucket per flag and user
return Math.floorMod((name.hashCode() * 31) + userId * 7919, 100);
}
}
public class Main {
public static void main(String[] args) {
FeatureFlags ff = new FeatureFlags();
ff.enable("dark-mode", 100);
ff.enable("new-checkout", 30);
int on = 0;
for (int user = 1; user <= 1000; user++) if (ff.isOn("new-checkout", user)) on++;
System.out.println(ff.isOn("dark-mode", 42) + " " + ff.isOn("beta-chat", 42) + " " + (ff.isOn("new-checkout", 7) == ff.isOn("new-checkout", 7)));
System.out.println("new-checkout users: " + on + " of 1000");
}
}
Output Verified by compiling and running
true false true
new-checkout users: 300 of 1000
The Flag type and the bucketing formula are private details; the public API is just enable and isOn. Because 7919 and 100 share no factor, users spread evenly, so exactly 30% are in.
More Access Modifiers and Packages practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!