We are happy to incorporate content from volunteers!!
Coding Patterns - selectors
Lookups for New() selectors
\since 2112
const word modelType(coeffs.get<word>("type"));
auto* ctorPtr = dictionaryConstructorTable(modelType);
if (!ctorPtr)
{
FatalIOErrorInLookup
(
dict,
"fvOption",
modelType,
*dictionaryConstructorTablePtr_
) << exit(FatalIOError);
}
return autoPtr<option>(ctorPtr(name, modelType, coeffs, mesh));
This contains the following aspects:
- The dictionary
get<word>
for retrieval with input checking - The lookup uses
dictionaryConstructorTable()
instead of the HashTable which adds in additional checks and compatibility aliases. - Exit immediately upon error, leaving the good case to drop through.
- Use of the
FatalErrorInLookup
orFatalIOErrorInLookup
macros to wrap standard boilerplate text for the output.
Lookups for New() selectors
\since 1912
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 offind()
to ensure that theconst_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()
orgood()
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
orFatalIOErrorInLookup
macros to 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-2020 OpenCFD Ltd.