Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Class invariant
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====C++==== The [[Loki (C++)]] library provides a framework written by [[Richard Sposato]] for checking class invariants, static data invariants, and [[exception safety]] level. This is an example of how a class can use Loki::Checker to verify that invariants remain true after an object changes. The example uses a geopoint object to store a location on Earth as a coordinate of latitude and longitude. The geopoint invariants are: * latitude may not be more than 90Β° north. * latitude may not be less than -90Β° south. * longitude may not be more than 180Β° east. * longitude may not be less than -180Β° west. <syntaxhighlight lang="C++"> #include <loki/Checker.h> // Needed to check class invariants. #include <Degrees.hpp> class GeoPoint { public: GeoPoint(Degrees latitude, Degrees longitude); /// Move function will move location of GeoPoint. void Move(Degrees latitude_change, Degrees longitude_change) { // The checker object calls IsValid at function entry and exit to prove this // GeoPoint object is valid. The checker also guarantees GeoPoint::Move // function will never throw. CheckFor::CheckForNoThrow checker(this, &IsValid); latitude_ += latitude_change; if (latitude_ >= 90.0) latitude_ = 90.0; if (latitude_ <= -90.0) latitude_ = -90.0; longitude_ += longitude_change; while (longitude_ >= 180.0) longitude_ -= 360.0; while (longitude_ <= -180.0) longitude_ += 360.0; } private: /** @note CheckFor performs validity checking in many functions to determine if the code violated any invariants, if any content changed, or if the function threw an exception. */ using CheckFor = ::Loki::CheckFor<const GeoPoint>; /// This function checks all object invariants. bool IsValid() const { assert(this != nullptr); assert(latitude_ >= -90.0); assert(latitude_ <= 90.0); assert(longitude_ >= -180.0); assert(longitude_ <= 180.0); return true; } Degrees latitude_; ///< Degrees from equator. Positive is north, negative is ///< south. Degrees longitude_; ///< Degrees from Prime Meridian. Positive is east, ///< negative is west. } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)