The magic behind this question is some mysterious guy called "transaction".
In software, all-or-nothing operations are called transactions. Transactions allow you to group several operations into a single unit of work that either fully happens or fully doesn't happen. If everything foes well, then the transaction is a success. But if anything goes wrong, the slate is wiped clean and it is as if nothing ever happened.
You have given a perfect example of a real-world transaction. If the database name changing fails, the person could think about he/she has changed his/her name but actually not. There a re various ways declaring transactions and because you have hidden your database implementation behind the scheme, so I don't know which database approach you are using. (e.g. JDBC, Hibernate ORM, or something else).
You can even think about let your database implementation throw an exception when database operation fails. Check the following code snippet.
Class A
{
private String name; //名称
private DbOper oper=new DbOper(); //操作数据库的类
//改变名称
public void setName(String name)
{
try
{
oper.changName(name); //同时改变数据库中的数据
this.name=name; //改变对象中的属性
}
catch (DbException dbexcept)
{
// handles with the database exception
// e.g. log an error message to the end operator...
}
}
}
The above code can guarantee the name property is never set in your object model if the database operation fails, although it looks very simple and fragile.
Hope this helps.
Regards,
Jiafan