algorithm – Transactions in code


There is some code like this:


The method ВключитьЩиты error has occurred, and therefore, I want everything to roll back. With databases, everything is easy, there are transactions. What about the code? Maybe you've come up with something? In order not to write a bunch of reverse steps.


Try to write your code like "dangerous changes – safe commit" + immutability.

// изменения
локальные корабли' = создать корабли с дефолтными координатами и включённым щитом();
локальный космос' = космос.ДобавитьКораблиИВернутьНовыйКосмос(корабли');
локальные противники' = обнаружить противников в (космос');

// безопасный коммит
космос = космос'
противники = противники'

If any part of the changes crashes, it affects only local objects that will be eaten by the garbage collector or RAII.

If all your objects are immutable, then the new local space is not a consumable thing: it shares most of its objects with the old space.

Scroll to Top