Skip to main content
Programming from zero

Build hostnames with a default environment

easyFunctions

Problem statement

Sometimes a function has an input that is usually the same. A hostname builder, for example, almost always targets prod. A default value lets callers leave that input out, and the function fills in the default for them.

Common mistake: putting a parameter with a default before one without.

TEXT
Wrong: def build_hostname(env="prod", name):

Python refuses this with a SyntaxError. Parameters that have a default must come last, after the ones without.

Your task: write a function that builds a hostname in the form <name>.<env>.internal, with env defaulting to prod. Print build_hostname("web-01") and build_hostname("db-01", "staging").

Expected output:

TEXT
web-01.prod.internal
db-01.staging.internal

Approach

Give env a default, and let callers pass it only when they want something else:

  • Python: def build_hostname(name, env="prod"): sets the default right in the definition.
  • C++: const std::string& env = "prod" does the same. (const std::string& just means "read this text without copying it", so treat it as a normal string for now.)
  • Java has no default values. Instead you write two versions of the method with the same name. The short one calls the longer one with "prod" filled in.
def build_hostname(name, env="prod"):
    return f"{name}.{env}.internal"

print(build_hostname("web-01"))
print(build_hostname("db-01", "staging"))