|
|
<!-- --- title: OpenFOAM C++ Coding Patterns (dictionary) -->
|
|
|
|
|
|
[Back to _coding patterns_](/coding/patterns/patterns)
|
|
|
|
|
|
***We are happy to incorporate content from volunteers!!***
|
|
|
|
|
|
|
|
|
## Coding Patterns
|
|
|
|
|
|
### Reading dictionary entries
|
|
|
|
|
|
```
|
|
|
const scalar value(dict.get<scalar>("value"));
|
|
|
|
|
|
const word modelType(dict.get<word>("type"));
|
|
|
|
|
|
const vector dirn(dict.get<vector>("direction"));
|
|
|
```
|
|
|
|
|
|
- These retrieve values with input checking on type and excess tokens.
|
|
|
|
|
|
**Anti-pattern**: using dictionary `lookup()` returns an stream,
|
|
|
which needs additional handling for primitives and does not incorporate
|
|
|
input checking:
|
|
|
```
|
|
|
const scalar value(readScalar(dict.lookup("value"));
|
|
|
|
|
|
const word modelType(dict.lookup("type"));
|
|
|
|
|
|
const vector dirn(dict.lookup("direction"));
|
|
|
```
|
|
|
|
|
|
|
|
|
When reading into _existing_ entries:
|
|
|
```
|
|
|
dict.readEntry("value", value);
|
|
|
|
|
|
dict.readIfPresent("value", value);
|
|
|
|
|
|
// or
|
|
|
if (dict.readIfPresent("value", value))
|
|
|
{
|
|
|
... more actions
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: using raw dictionary `lookup()` or doing the
|
|
|
conditionals manually:
|
|
|
```
|
|
|
dict.lookup("value") >> value;
|
|
|
|
|
|
if (dict.found("value"))
|
|
|
{
|
|
|
dict.lookup("value") >> value;
|
|
|
|
|
|
... more actions
|
|
|
}
|
|
|
```
|
|
|
|
|
|
|
|
|
### Writing dictionary entries
|
|
|
|
|
|
```
|
|
|
os.writeEntry("key", value);
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: doing everything yourself is messy and repetitive:
|
|
|
```
|
|
|
os.writeKeyword("key") << value << token::END_STATEMENT << nl;
|
|
|
```
|
|
|
|
|
|
### Writing sub-dictionary entries
|
|
|
|
|
|
```
|
|
|
os.beginBlock("entries");
|
|
|
|
|
|
os.writeKeyword("key", value);
|
|
|
...
|
|
|
|
|
|
os.endBlock();
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: doing everything yourself:
|
|
|
```
|
|
|
os.indent();
|
|
|
os.write("entries") << nl;
|
|
|
os.indent();
|
|
|
os << token::BEGIN_BLOCK << nl;
|
|
|
os.incrIndent();
|
|
|
|
|
|
os.writeKeyword("key") << value << token::END_STATEMENT << nl;
|
|
|
...
|
|
|
|
|
|
os.decrIndent();
|
|
|
os.indent();
|
|
|
os << token::END_BLOCK << nl;
|
|
|
```
|
|
|
|
|
|
----
|
|
|
|
|
|
Copyright (C) 2019 OpenCFD Ltd. |