What is an idempotent operation?

前端 未结 15 913
情话喂你
情话喂你 2020-11-22 03:27

What is an idempotent operation?

相关标签:
15条回答
  • 2020-11-22 03:55

    Quite a detailed and technical answers. Just adding a simple definition.

    Idempotent = Re-runnable

    For example, Create operation in itself is not guaranteed to run without error if executed more than once. But if there is an operation CreateOrUpdate then it states re-runnability (Idempotency).

    0 讨论(0)
  • 2020-11-22 03:55

    In short, Idempotent operations means that the operation will not result in different results no matter how many times you operate the idempotent operations.

    For example, according to the definition of the spec of HTTP, GET, HEAD, PUT, and DELETE are idempotent operations; however POST and PATCH are not. That's why sometimes POST is replaced by PUT.

    0 讨论(0)
  • 2020-11-22 03:58

    Just wanted to throw out a real use case that demonstrates idempotence. In JavaScript, say you are defining a bunch of model classes (as in MVC model). The way this is often implemented is functionally equivalent to something like this (basic example):

    function model(name) {
      function Model() {
        this.name = name;
      }
    
      return Model;
    }
    

    You could then define new classes like this:

    var User = model('user');
    var Article = model('article');
    

    But if you were to try to get the User class via model('user'), from somewhere else in the code, it would fail:

    var User = model('user');
    // ... then somewhere else in the code (in a different scope)
    var User = model('user');
    

    Those two User constructors would be different. That is,

    model('user') !== model('user');
    

    To make it idempotent, you would just add some sort of caching mechanism, like this:

    var collection = {};
    
    function model(name) {
      if (collection[name])
        return collection[name];
    
      function Model() {
        this.name = name;
      }
    
      collection[name] = Model;
      return Model;
    }
    

    By adding caching, every time you did model('user') it will be the same object, and so it's idempotent. So:

    model('user') === model('user');
    
    0 讨论(0)
提交回复
热议问题