I am writing a small wrapper around OpenGL so that I can use it in an object-oriented way. I have created a class called a buffer, and in its constructor I would like it to validate the type of buffer that it has been passed against lots of GLenum types. Here is the relevant portion of the code:
Buffer::Buffer(GLenum type) {
// Validate 'type'.
switch (type) {
// *** These are the valid values ***
case GL_ARRAY_BUFFER:
case GL_ATOMIC_COUNTER_BUFFER:
case GL_COPY_READ_BUFFER:
case GL_COPY_WRITE_BUFFER:
// *** Lots more valid values here... ***
break; // Jump out of the switch statement.
default:
throw std::logic_error("Invalid GLenum 'type' in Buffer constructor.");
}
type_ = type;
target_ = target;
glGenBuffers(1, &buffer_);
}
In this code, the switch
statement would step in to the appropriate value, and pass through the other valid values until it broke out of the switch
statement. All other values would step into the default
clause and throw an exception. I could, however, also use an if
statement:
if (type != GL_ARRAY_BUFFER &&
type != GL_ATOMIC_COUNTER_BUFFER &&
type != GL_COPY_READ_BUFFER &&
type != GL_COPY_WRITE_BUFFER &&
// *** Lots more valid values here... ***
) {
throw std::logic_error("Invalid GLenum 'type' in Buffer constructor.");
}
// ...
}
However, this uses a lot of repetition of type !=
and isn't necessarily any clearer. Is there an accepted convention when doing this, for code clarity and for speed? Should I be validating my inputs at all, when not doing so could cause undefined behaviour?