Open In App

What is class Invariant

Last Updated : 22 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Overview :
An invariant in Object-Oriented programming refers to some set of conditions or assertions that need to hold throughout the life of an object of a class. These assertions need to hold from the time the constructor is called for an object, at the end of each member (mutator) method call to the end of the destructor call. These conditions verify that an object’s behavior is justified during its lifetime and that the object maintains its well-defined state as intended. The invariant, however, need not hold true during the execution of a mutator method but must hold true at the end of it.

Example :
Creating a snake game –
Let’s say we were creating a snake game and our snake had the ability to teleport itself a few blocks in some direction. Let us also define our invariant that our snake’s head should not cross the playground bounds. Now, if we ensure that our invariant holds at the end of the function where we implement our teleportation ability, we are good. Otherwise, our assertions will fail, and we will find out that there probably is a bug in our code.

Code Implementation in C++ :
As a good programming practice, an invariant private member method is created whose duty is to check that all necessary conditions stay uncompromising and that all methods can make reasonable assumptions about the state of the object. We call this invariant member method at the end of constructors and every mutator method.

Code –

C++




#include <bits/stdc++.h>
using namespace std;
  
// self defined struct to 
// hold the position of snake
struct Pos
{
    int x;
    int y;
    Pos(int _x = 0, int _y = 0)
    {
        this->x = _x;
        this->y = _y;
    }
};
  
class Snake
{
private:
    int play_width; // right bound
    int play_height; // height bound
    Pos loc; // position of snake's head
    void Invariant()
    {
        assert(loc.x >= 0 && loc.x <= play_width);
        assert(loc.y >= 0 && loc.y <= play_height);
    }
public:
    // initialise the snake object with _width ans _height bounds
    // ans posx, posy current position
    Snake(int _width, int _height, Pos _p)
    {
        this->play_width = _width;
        this->play_height = _height;
        this->loc.x = _p.x;
        this->loc.y = _p.y;
        // call the invariant to ensure the object
        // was constructed correctly
        Invariant();
    }
  
    // teleport and add inc.x units to current X coordinate
    // ans inc.y units to Y coordinate of snake 
    void TeleportAhead(Pos inc)  
    {
        loc.x += inc.x;
        loc.y += inc.y;
        //ensure that our snake wasn't 
        // teleported out of play bounds
        Invariant();
    }
  
    // return current position
    // calling invariant is unnecessary
    // because this is an accessor method
    Pos GetLoc()
    {
        return loc;
    }
};
  
  
  
int main()
{
    Snake snek(30, 20, Pos(5, 5));
  
    // will throw assert error because
    // our snake is teleported out of bound
    snek.TeleportAhead(Pos(20, 20));
  
    // will also fail Invariant() assertion
    // because the snake is being spawned out
    // of bounds
    Snake snek2(10, 10, Pos(12, 8));
    return 0;
}




Similar Reads

Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Java.net.Authenticator class in Java
Authenticator class is used in those cases where an authentication is required to visit some URL. Once it is known that authentication is required, it prompts the user for the same or uses some hard-coded username and password. To use this class, following steps are followed- Create a class that extends the Authenticator. Lets name it customAuth.Ov
3 min read
Range Class | Guava | Java
Guava’s Range represents an interval, for example, a < range < b. Here range includes any value between a and b, called endpoints which form the boundary. Any value between the boundary is a contiguous span of values of type Comparable. Declaration : The declaration for com.google.common.collect.Range<C> class is : @GwtCompatible public
5 min read
Ordering Class | Guava | Java
A comparator, with additional methods to support common operations. This is an "enriched" version of Comparator. The common ways to get an instance of Ordering are : Subclass it and implement compare(T, T) instead of implementing Comparator directly. Pass a pre-existing Comparator instance to from(Comparator). Use the natural ordering, natural(). D
4 min read
BigIntegerMath Class | Guava | Java
BigIntegerMath is used to perform mathematical operations on BigInteger values. Basic standalone math functions are divided into the classes IntMath, LongMath, DoubleMath, and BigIntegerMath based on the primary numeric type involved. These classes have parallel structure, but each supports only the relevant subset of functions. Similar functionali
3 min read
IntMath Class | Guava | Java
Introduction : IntMath is used to perform mathematical operations on Integer values. Basic standalone math functions are divided into the classes IntMath, LongMath, DoubleMath, and BigIntegerMath based on the primary numeric type involved. These classes have parallel structure, but each supports only the relevant subset of functions. Declaration :
3 min read
LongMath Class | Guava | Java
LongMath is used to perform mathematical operations on Long values. Basic standalone math functions are divided into the classes IntMath, LongMath, DoubleMath, and BigIntegerMath based on the primary numeric type involved. These classes have parallel structure, but each supports only the relevant subset of functions. Declaration : The declaration f
3 min read
Ints Class | Guava | Java
Ints is a utility class for primitive type int. It provides Static utility methods pertaining to int primitives, that are not already found in either Integer or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Ints extends Object Below table shows the Field summary for Guava Ints Class : Some of the methods provided by Ints Cl
3 min read
Chars Class | Guava | Java
Chars is a utility class for primitive type char. It provides Static utility methods pertaining to char primitives, that are not already found in either Character or Arrays. All the operations in this class treat char values strictly numerically, i.e, they are neither Unicode-aware nor locale-dependent. Declaration : @GwtCompatible(emulated=true) p
3 min read
Longs Class | Guava | Java
Longs is a utility class for primitive type long. It provides Static utility methods pertaining to long primitives, that are not already found in either Long or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Longs extends Object Below table shows the Field summary for Guava Longs Class : Some of the methods provided by Guava
3 min read
Bytes Class | Guava | Java
Bytes is a utility class for primitive type byte. It provides Static utility methods pertaining to byte primitives, that are not already found in either Byte or Arrays and interpret bytes as neither signed nor unsigned. The methods which specifically treat bytes as signed or unsigned are found in SignedBytes and UnsignedBytes. Declaration : @GwtCom
3 min read
Shorts Class | Guava | Java
Shorts is a utility class for primitive type short. It provides Static utility methods pertaining to short primitives, that are not already found in either Short or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Shorts extends Object Below table shows the Field summary for Guava Shorts Class : Some of the methods provided by
3 min read
Doubles Class | Guava | Java
Doubles is a utility class for primitive type double. It provides Static utility methods pertaining to double primitives, that are not already found in either Double or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Doubles extends Object Below table shows the Field summary for Guava Doubles Class : Some of the methods provi
3 min read
Booleans Class | Guava | Java
Booleans is a utility class for primitive type Boolean. It provides Static utility methods pertaining to boolean primitives, that are not already found in either Boolean or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Booleans extends Object Below given are some methods provided by Guava Booleans Class : Exceptions : ensur
3 min read
Floats Class | Guava | Java
Floats is a utility class for primitive type float. It provides Static utility methods pertaining to float primitives, that are not already found in either Float or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Floats extends Object Below table shows the Field summary for Guava Floats Class : Some of the methods provided by
3 min read
CBSE 12th class Paper Solved - 2015-16 session
Sample Question Paper – Set II Computer Science (083) Class- XII (2015-16) Time: 3hrs M.M: 70Instructions: i. All Questions are Compulsory. ii. Programming Language: Section A : C++ iii. Programming Language: Section B: Python iv. Answer either Section A or B, and Section C is compulsory Section : A (C++) Q1 a. Define Macro with suitable example. 2
15+ min read
FileWriter Class in Java
Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java. This class inherits from OutputStreamWriter class which in turn inherits from the Writer class.The constructors o
7 min read
Generic Class in Java
Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means
4 min read
What is the valid range of a Class A network address?
Let us know what an IP address is first, if you already know, skip this section. IP (Internet Protocol): It is one of the fundamental protocols in order to have communications on the Internet. IP describes how the information is addressed, routed by networking devices. An IP address is a number identifying of a computer or another device on the Int
2 min read
Java Guava | factorial(int n) method of IntMath Class with Examples
The factorial(int n) method of Guava's IntMath Class returns the product of the first n positive integers, which is n!. Syntax: public static int factorial(int n) Parameter: The method accepts only one parameter n which is of integer type and is to be used to find the factorial. Return Value: This method return following values: This method returns
2 min read
IdentityHashMap class in Java
The IdentityHashMap implements Map interface using Hashtable, using reference-equality in place of object-equality when comparing keys (and values). This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals() method wh
13 min read
Java.util.zip.DeflaterOutputStream class in Java
Java.util.zip.DeflaterInputStream class in Java This class implements an output stream filter for compressing data in the "deflate" compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream. Constructors and Description DeflaterOutputStream(OutputStream out) : Creates a new output stream with
3 min read
Java.io.ObjectOutputStream Class in Java | Set 2
Java.io.ObjectOutputStream Class in Java | Set 1 More Methods: void write(byte[] buf) : Writes an array of bytes. This method will block until the byte is actually written. Syntax :public void write(byte[] buf) throws IOException Parameters: buf - the data to be written Throws: IOException void write(byte[] buf, int off, int len) : Writes a sub arr
8 min read
Java.lang.Boolean Class in Java
Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolea
8 min read
Java.Lang.Float class in Java
Float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of the Float class can hold a single float value. There are mainly two constructors to initialize a Float object- Float(float b): Creates a Float o
6 min read
Java.Lang.Short class in Java
Short class is a wrapper class for the primitive type short which contains several methods to effectively deal with a short value like converting it to a string representation, and vice-versa. An object of Short class can hold a single short value. There are mainly two constructors to initialize a Short object- Short(short b): Creates a Short objec
6 min read
Java.lang.Integer class in Java
Integer class is a wrapper class for the primitive type int which contains several methods to effectively deal with an int value like converting it to a string representation, and vice-versa. An object of the Integer class can hold a single int value. Constructors: Integer(int b): Creates an Integer object initialized with the value provided.Syntax
15 min read
Java.lang.Enum Class in Java
Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable As we can see, that Enum is an abstract class, so we can not create obje
8 min read
How to run java class file which is in different directory?
In this article, we will learn about how to use other project's utilities, classes, and members. Before proceeding let's learn about some keywords. classpath Classpath is the location from where JVM starts execution of a program. Similar to the classic dynamic loading behavior, when executing Java programs, the Java Virtual Machine finds and loads
6 min read
Practice Tags :
three90RightbarBannerImg