KatInterview

Variable-Argument Functions Across Languages, with a Safe Logger

Data Structure DesignModel answer
HardModel answerData Structure Designvariadic-functionstype-safetycalling-conventions

Last updated

Compare how two languages implement functions with a variable number of arguments, then design a type-checked key-value logger that avoids injection and needless allocation.

Many languages let a function accept a variable number of arguments, such as printf in C, *args in Python, ...T in Go and T... in Java.

Pick two languages (for example C/C++ and Python, or Go and Java) and explain the following for each.

  1. Mechanics. How does the caller pass the extra arguments, and how does the callee read them? Cover the calling convention (stack, registers, or a container object) and how the callee learns the count and types.
  2. Type safety. What does the compiler or runtime check? Contrast raw varargs with templates, generics or typed alternatives.
  3. Cost. What are the performance, stack and heap implications?
  4. Forwarding. How do you pass the variable arguments on to another function?

Then design and implement a type-safe logger that accepts a level, a message and key-value fields, and formats them into a single line efficiently. Discuss:

  • format-string vulnerabilities,
  • boxing and reflection overhead,
  • overload or keyword ambiguity,
  • log forging through unescaped values.

Also provide unit tests and state the time and space complexity of your formatting routine.

Hints

Hint 1

Start by listing the three questions every variadic design must answer: where the extra arguments live, how the callee knows their count and types, and whether anything checks them. Then compare one unchecked model with one checked model.

Hint 2

For the logger, treat the message as data and never as a format string. Validate keys and value types up front, and check the log level before doing any validation or formatting work.

Hint 3

Build the output by collecting parts in a list and joining once, and quote or escape values containing spaces, equals signs, quotes or newlines. For tests, cover an odd number of positional pairs, a field named like a parameter, bool versus int, and a disabled level.