Currently I'm reading "Java concurrency in practice", which contains this sentence:
Since the action of a thread accessing a stateless object can't affect the correctness of operations on other threads, stateless objects are thread-safe.
So, what is stateless object?
Stateful Objects are that objects which have changeable members or mutable members, that may vary what transactions or operations were previously performed on the object. For a same operation performed many times, the result outputed may be different from previous result's.
Key Difference Between Functional Programming and OOP Functional programming has a stateless programming model. Object-oriented programming has a stateful programming model. In functional programming, a state does not exist. In object-oriented programming, the state exists.
Static methods? Yes, when they are stateless. Some of the reactions to my last blog post on Named Constructors in PHP, originate from the notion that static methods are inherently bad and should never be used. This is rather overgeneralized.
A stateful object is an instance of a class that may morph itself into various states. For example an object can be created, but not initialized, later initialized and ready for being used and at the end it can be disposed (but still remain accessible in memory).
Stateless object is an instance of a class without instance fields (instance variables). The class may have fields, but they are compile-time constants (static final).
A very much related term is immutable. Immutable objects may have state, but it does not change when a method is invoked (method invocations do not assign new values to fields). These objects are also thread-safe.
If the object doesn't have any instance fields, it it stateless. Also it can be stateless if it has some fields, but their values are known and don't change.
This is a stateless object:
class Stateless { void test() { System.out.println("Test!"); } }
This is also a stateless object:
class Stateless { //No static modifier because we're talking about the object itself final String TEST = "Test!"; void test() { System.out.println(TEST); } }
This object has state, so it is not stateless. However, it has its state set only once, and it doesn't change later, this type of objects is called immutable:
class Immutable { final String testString; Immutable(String testString) { this.testString = testString; } void test() { System.out.println(testString); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With