zoukankan      html  css  js  c++  java
  • Effective Java 64 Strive for failure atomicity

    Principle

    Failure atomic - A failed method invocation should leave the object in the state that it was in prior to the invocation.

       

    Ways to achieve failure atomic

    1. Method operates on Immutable objects

    It's free to failure atomic since the state of the immutable objects is consistent when it's created and can't be modified thereafter.

    2. Method operates on mutable objects

    • Check parameters for validity before performing operation(Item 38).

       

    public Object pop() {

    if (size == 0)

    throw new EmptyStackException();

    /* If there is no such checking there will be non-abstract exception thrown by the app and the size field will be in an invalid state after the exception. */

    Object result = elements[--size];

    elements[size] = null; // Eliminate obsolete reference

    return result;

    }

    • Order the computation

      Any part that may fail takes place before any part that modifies the object.

    3. Write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began.

    This approach is used mainly for durable (disk-based) data structures.

    4. Perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete.

    Collections.sort dumps its input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.

       

    Summary

    Any generated exception that is part of a method's specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.

       

  • 相关阅读:
    UIImageView添加圆角
    iOS开发之NSRunLoop的进一步理解
    OC与Swift混编
    源码:自己用Python写的iOS项目自动打包脚本
    iOS 自定义Tabbar实现push动画隐藏效果
    IOS开发基础篇--CAShapeLayer的strokeStart和strokeEnd属性
    Swift 之 函数与闭包的应用实例
    Facebook iOS App如何优化启动时间
    iOS 中的 Deferred Deep Linking(延迟深度链接)
    Cocos2d-x使用UserDefault数据持久化实例:保存背景音乐和音效设置
  • 原文地址:https://www.cnblogs.com/haokaibo/p/strive-for-failure-atomicity.html
Copyright © 2011-2022 走看看