定义
实现失败原子性的方法
不可变对象
示例:
// exemplo simplificado de um objeto imutável
public final class immutableobject {
private final int value;
public immutableobject(int value) {
this.value = value;
}
public int getvalue() {
return value;
}
}
操作前参数验证
示例:
// verificação de estado em um método stack.pop()
public object pop() {
if (size == 0) {
throw new illegalstateexception("stack is empty");
}
object result = elements[--size];
elements[size] = null; // evitar vazamento de memória
return result;
}
操作排序
示例:
// adicionando elemento em treemap (simulação) public void addelement(treemapmap, string key, integer value) { if (key == null || value == null) { throw new illegalargumentexception("key or value is null"); } map.put(key, value); // falhas na comparação ocorrem antes de alterar a estrutura }
临时副本
示例:
// simulação de operação em cópia temporária public void sortlist(listlist) { list temp = new arraylist<>(list); try { collections.sort(temp); list.clear(); list.addall(temp) ; } catch (exception e) { // a lista original permanece intacta } }
恢复代码
示例:
public void updateRecord(Database db, Record record) {
Record backup = db.getRecord(record.getId()); // Fazer backup
try {
db.update(record);
} catch (Exception e) {
db.update(backup); // Reverter em caso de falha
}
}
值得注意的例外
成本和复杂性
良好实践
最终总结