"To Be Or Not To Be" is a creative coding challenge that focuses on designing a fluent interface for testing assertions. It asks you to create an object or a function that allows for readable, chainable checks, such as expect(5).toBe(5) or expect(5).notToBe(10). The goal is to return true if the condition is met, but more importantly, to throw a specific error message if the assertion fails. This problem is less about complex algorithms and more about your ability to design clean, intuitive APIs that other developers can use for unit testing or data validation.
This "To Be Or Not To Be interview question" is incredibly popular at companies like Microsoft, Amazon, and Google because it tests "Developer Experience" (DX) thinking. Engineers aren't just expected to write code that works; they are expected to write code that makes other engineers more productive. By asking you to build a mini-assertion library, interviewers can see if you understand object-oriented design, error handling, and the "Builder" pattern. It's a great way to gauge your familiarity with the tools used in professional software development, such as testing frameworks.
The underlying pattern is the "Fluent Interface" or "Chaining" pattern. You are essentially creating a wrapper around a value that provides specialized methods for validation. When you call the main function, it returns an object containing these methods. These methods then perform the comparison and either return a success state or raise an exception. This pattern is widely used in everything from jQuery to modern Promise libraries and testing suites.
Imagine you are building a simple calculator. You want to make sure your add(2, 2) function actually returns 4. Using this pattern, you would write expect(add(2, 2)).toBe(4). Inside the expect function, the value 4 is stored. The .toBe(target) method then compares 4 with target. Since they match, it returns true. If you wrote expect(4).toBe(5), the method would see the mismatch and throw an error like Error: Not Equal. If you used .notToBe(5), it would verify they are different and return true.
One common pitfall is returning a boolean value false instead of throwing an actual Error object when the assertion fails. Most testing frameworks expect an exception to be raised so they can catch it and report it. Another mistake is over-complicating the logic; the core of the problem is simply comparison and error throwing. Candidates also sometimes forget to handle the "not" case correctly, where the logic is inverted.
To prepare for the "To Be Or Not To Be coding problem," study how popular testing libraries (like Jest or Chai) are structured. Practice creating objects that return other objects with methods, as this "cascading" structure is key to building fluent APIs. Understanding the difference between "deep equality" and "referential equality" is also helpful for more advanced versions of this question.