The WebIDL compiler currently translates a dictionary such as this,
dictionary Foo {
int field;
}
into a C++ class like this,
class Foo {
public:
bool hasField() const { return has_field_; }
int field() const {
DCHECK(has_field_);
return field_;
}
void setField(int value) {
has_field_ = true;
field_ = value;
}
private:
bool has_field_ = false;
int field_;
};
The problem with this is that it makes failure to check the return value of hasField() first a runtime error rather than a compile-time error. Now that we have access to this type from Blink we should start using base::Optional to represent optional fields. The new class definition would be:
class Foo {
public:
const base::Optional<int>& field() const {
return field_;
}
void setField(int value) {
field_ = value;
}
private:
base::Optional<int> field_;
};
Not only is this code simpler but by returning a base::Optional from the field accessor we force callers to consider whether or not the value was populated in the dictionary. This prevents uninitialized accesses from creeping into code which is not exercised in web tests with DCHECKs enabled.
Callers who previously checked hasField() can now use field().has_value() or simplify their code with convenience functions such as field().value_or(kDefaultValue).
Comment 1 by yukishiino@chromium.org
, Jan 7Owner: peria@chromium.org
Status: Assigned (was: Untriaged)