Last active
December 30, 2015 05:39
-
-
Save markusl/7784108 to your computer and use it in GitHub Desktop.
Purpose of this document is to define how boost::optional is used in unified way throughout the code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* RULES | |
* 1. Prefer using is_initialized() for checking the contents if the | |
* value is not assigned to a boost::optional right before | |
* 2. Prefer get() over 'operator ->', to make visible what's happening | |
* 3. Use get_value_or() if applicable, this makes the control flow less complex | |
* 4. Optionally prefix variable with 'opt' or postfix with 'Optional' | |
* | |
* DOCS http://www.boost.org/doc/libs/1_55_0/libs/optional/doc/html/index.html | |
* | |
* Visual Assist X automatically converts dot (.) to '->' if such operator exists. Use BACKSPACE to | |
* undo this change or disable feature from 'Vissual Assist X options / Advanced / Corrections'. | |
*/ | |
// Example 1 - OK - 'is_initialized' indicates it's a boost::optional | |
const auto PolymeshData = MaybeGetPolymeshData(); | |
if(PolymeshData.is_initialized()) { | |
const Polymesh_t &Polymesh = PolymeshData.get(); | |
const auto Extrema = Polymesh.GetExtrema(); | |
// … | |
} | |
else { | |
// log an error | |
} | |
// Example 2 - OK - it is obvious that this is a boost::optional | |
const boost::optional<Polymesh_t> PolymeshData = GetPolymeshData(); | |
if(PolymeshData) | |
{ | |
const auto Extrema = PolymeshData.get().GetExtrema(); | |
} | |
// Example 3 - OK if the algorithm can work with an empty or default values | |
const boost::optional<Polymesh_t> PolymeshData = GetPolymeshData(); | |
const Polymesh_t &Polymesh = PolymeshData.get_value_or(GetEmptyPolymesh()); | |
const auto Extrema = PolymeshData.get().GetExtrema(); | |
// Example 4 - NOT OK - Hides the boost::optional completely from user | |
const auto PolymeshData = GetPolymeshData(); | |
if(PolymeshData) | |
{ | |
const auto Extrema = PolymeshData->GetExtrema(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment