An application I'm working on has a field where a string can be entered.
Special characters in the string cause different things to be inserted when the string is evaluated, but these special characters can be preceded by an escape character (a backslash) which cause the special character to be output literally rather than its special meaning.
Think of it as similar to a regular expression: .
matches any character but \.
matches a dot.
What is the most intuitive thing to happen when the escape character is followed by a character which doesn't need escaping? For example, would it make more sense that:
- The escape character "escapes" the literal as itself:
\f
becomes 开发者_StackOverflowf
("an escaped f") - The escape character isn't an escape character unless it's followed by a special character:
\f
remains as\f
- Error! Throw an exception because the it's invalid to have an escape character not escaping anything
All of these are possible and in my opinion justifiable. But which makes more sense, and which is already most common in other languages?
I'd vote for the first solution. It makes forming strings easy: If you don't know if a character has a special meaning in your context, just escape it. It won't hurt.
Ultimately, the right answer is probably not language-agnostic. In Ada I'd expect option three, because it's largely about strictly enforcing strict rules. In Perl, I'd expect option one or two, because it's much more permissive as a rule.
Since I'm mostly a C++ programmer, I'd vote for option 4: arrange for a function to be called in such a case. The "faulty" sequence is passed to it as a parameter, and it's expected to either return an interpreted result or throw an exception.
If it was a native Windows API, I'd expect something close to the C++ solution, only it would build a chain of functions, starting from the most recently added, and working its way down the chain until a function either returned an interpreted result, or it got to the end of the chain where the default function would throw an exception.
精彩评论