How can you use Git to implement feature toggles in a codebase?

A feature toggle uses a runtime flag, not a long-lived Git branch, to control whether a piece of code executes; Git's role is simply to let you merge that code into main early, behind the flag, using short-lived branches.

Key Points: • Develop the feature on its own short-lived branch, then merge it into main as soon as it's reasonably stable, even if it isn't finished. • Wrap the new behavior in a conditional driven by a config file, environment variable, or a feature-flag service rather than by which branch is checked out. • This is the core idea behind trunk-based development: toggles replace long-lived feature branches, avoiding painful merge conflicts later. • Toggles let you test in production safely and roll back instantly by flipping the flag, without a redeploy. • Remove the toggle and the dead code path once the feature is fully rolled out, to avoid flag debt accumulating.

Example: Instead of keeping a feature branch alive for weeks, the team merges the new checkout flow into main immediately, gated by a flag such as feature.newCheckout.enabled, and turns it on only for internal users first.

Code Example:

# application.properties
feature.newCheckout.enabled=false
if (featureFlags.isEnabled("newCheckout")) {
    checkoutServiceV2.process(order);
} else {
    checkoutService.process(order);
}

Interview Tip: A concise interview answer is:

"I keep the branch short-lived and merge into main quickly, but gate the new code behind a runtime flag from a config file, environment variable, or feature-flag service. That way Git history stays clean and I can enable or disable the feature instantly without redeploying."