Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-oriented programming & transactions

A little intro:

Class contains fields and methods (let me skip properties this time).
Fields represent a state of the class.
Methods describe behavior of the class.

In a well-designed class, a method won't change the class's state if it throws an exception, right? (In other words, whatever happens, class's state shouldn't be corrupted)

Question:

Is there a framework, a design pattern, best practice or a programming language to call a sequence of methods in a transactional style, so that either class's state don't get changed (in case of exception), or everything succeeds?

E.g.:

// the class foo is now in the state S1
foo.MoveToState2();
// it is now (supposed to be) in the state S2
foo.MoveToFinalState();
// it is now (supposed to be) in the state, namely, S3

Surely, an exception might occur both in MoveToState2() and MoveToFinalState(). But from this block of code I want the class foo to be either in the state S1 or S3.

This is a simple scenario with a single class involved, no if's, no while's, no side effects, but I hope the idea is clear.

like image 733
bohdan_trotsenko Avatar asked Dec 29 '09 12:12

bohdan_trotsenko


1 Answers

Take a look at the Memento pattern

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

like image 158
Bozho Avatar answered Nov 15 '22 18:11

Bozho