Refactor a chat message processing function
OpenAISoftware Engineer · Technical ScreenLast updated
This problem tests your ability to refactor procedural, error-prone code into a robust, extensible pipeline for parsing and managing chat message state.
Problem Statement
You are tasked with refactoring a legacy message processing function. The current implementation uses a monolithic block of nested if-else statements to handle three types of messages: standard (text), command (starting with /), and system (metadata updates).
Implement a MessageProcessor class that processes a list of raw strings and updates an internal state object.
Requirements
- Commands: If a message starts with
/, it must be parsed into a command name and arguments. Example:/set_user_status activebecomes{'type': 'command', 'name': 'set_user_status', 'args': ['active']}. - Standard: Normal text should be trimmed, and messages over 280 characters should be truncated to the first 280 characters with a '...' suffix.
- System: Messages starting with
[SYSTEM]should be marked astype: 'system'and the system message content stripped of the prefix. - State: Maintain a list of processed messages in a list
self.history.
Function Signature
class MessageProcessor:
def __init__(self):
self.history = []
def process_messages(self, raw_messages: list[str]) -> None:
# Implementation here
Constraints
raw_messageslength: 0 to 10,000.- Each string length: 0 to 1,000.
- Handle empty strings gracefully (ignore them).
Example
Input: [' Hello world ', '/set_theme dark', '[SYSTEM] User joined']
Output self.history:
[
{'type': 'standard', 'content': 'Hello world'},
{'type': 'command', 'name': 'set_theme', 'args': ['dark']},
{'type': 'system', 'content': 'User joined'}
]
Hints
Hint 1
Define a clear mapping or a strategy pattern to dispatch messages based on their prefix or structure rather than using a long series of if-else checks.
Hint 2
Use a helper method or private function to transform each raw string into a structured dictionary before appending it to the history.
Hint 3
Consider using regular expressions or Python's `.startswith()` and `.split()` methods to handle the parsing logic cleanly.
Follow-up questions
- How would you modify this class to support undoing the last command if a specific `undo` command is received?
- If this class needed to process millions of messages, how would you optimize the memory usage of `self.history`?
- How would you implement a validation layer to ensure that commands have the required number of arguments before they are added to the history?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.