|
|
<!-- --- title: OpenFOAM C++ Coding Patterns (selectors) -->
|
|
|
|
|
|
[Back to _coding patterns_](/coding/patterns/patterns)
|
|
|
|
|
|
***We are happy to incorporate content from volunteers!!***
|
|
|
|
|
|
|
|
|
## Coding Patterns
|
|
|
|
|
|
### Lookups for New() selectors
|
|
|
|
|
|
```
|
|
|
const word modelType(coeffs.get<word>("type"));
|
|
|
|
|
|
auto cstrIter = dictionaryConstructorTablePtr_->cfind(modelType);
|
|
|
|
|
|
if (!cstrIter.found())
|
|
|
{
|
|
|
FatalIOErrorInLookup
|
|
|
(
|
|
|
dict,
|
|
|
"fvOption",
|
|
|
modelType,
|
|
|
*dictionaryConstructorTablePtr_
|
|
|
) << exit(FatalIOError);
|
|
|
}
|
|
|
|
|
|
return autoPtr<option>(cstrIter()(name, modelType, coeffs, mesh));
|
|
|
```
|
|
|
|
|
|
This contains the following aspects:
|
|
|
- The dictionary `get<word>` for retrieval with input checking
|
|
|
- The lookup into the HashTable uses `cfind()` instead of `find()` to
|
|
|
ensure that the `const_iterator` version will always be used.
|
|
|
- The type is `auto`, since the compiler can correctly deduce the
|
|
|
iterator type and we can only make things worse (more typing, wrong
|
|
|
information) if we add this ourselves.
|
|
|
- Check for the iterator validity using `found()` or `good()` methods.
|
|
|
Internally these are identical to comparing with an end iterator,
|
|
|
but we save typing and potential mismatches by using these dedicated
|
|
|
methods.
|
|
|
- Exit immediately upon error, leaving the _good_ case to drop through.
|
|
|
- Use of the `FatalErrorInLookup` or `FatalIOErrorInLookup` macros which
|
|
|
wrap standard boilerplate text for the output.
|
|
|
|
|
|
**Anti-pattern**: The equivalent longhand version (pre-v1912)
|
|
|
illustrates the type of repetitive text we avoid:
|
|
|
```
|
|
|
FatalIOErrorInFunction(dict)
|
|
|
<< "Unknown fvOption type " << modelType
|
|
|
<< "\n\nValid fvOption types :\n"
|
|
|
<< dictionaryConstructorTablePtr_->sortedToc() << nl
|
|
|
<< exit(FatalIOError);
|
|
|
```
|
|
|
|
|
|
----
|
|
|
|
|
|
Copyright (C) 2019 OpenCFD Ltd. |