Back to Home

OOPS - Attribute vs State

February 16, 20193 minutes read
OOPS - Attribute vs State

In Object oriented programming objects are the fundamental unit. Usually an object is defined to have two characteristics.

State and behavior

State is defined through variables, properties or functions (getter and setter) depends on the language.

Behavior is usually defined through functions.

Most of the times, the term state represent both attribute and state of an object. But state and attribute are not same.


Attributes are immutable. When you create an object you set attributes. And those attribute values most likely do not change throughout the lifetime of object.

For example consider the below pseudocode.

class Dog {
// Attributes

// State

// Behavior

The object dog here holds two attributes color and age. When you create a dog object you define the age and color. Actually you can create an object with colour attribute set to Black. So logically you are creating a Black dog. And the dog remains Black throughout the object lifetime. If you want to create a red dog you may have to create another dog object with red colour.

The way of creating objects with immutable attributes varies from language to language. Typical method is to create properties with private set function.

In above example color is an attribute. That doesn't mean color has to be an attribute in all cases. It will change based on the context. For example consider consider traffic light as an object, where color is not an attribute but a state.


States are mutable. The state of an object changes several times throughout it's lifetime. The state gets changes either by some function applied on the object or through an event outside of the object. There are other scenarios but these are the typical cases. For example if the run function called frequently in dog object the thirsty state may toggle to true.

Sometimes in programming you may need to create an object without state but only attributes. Those objects are actually passive and do not have any behaviours. It is literally representing a group of logically related attributes.

Every object oriented programming language must have an option to create such objects. We can use structs in C# and objects with private set functions in Java.

This is one of the criteria to decide between struct and class in C#. When we create such structures in C#, make sure it is always immutable. Because mutable structures and public fields are always dangerous.

Understand why mutable structs are evil.

Why public fields are demonized in Java?