1

Suppouse the next example extracted from another OLOO question:

var Foo = {
    init: function(who) {
        this.initialized = true;
        this.me = who;
    },
    checkIfInitialized: function() {
        if(!this.initialized) throw new Error('Not initialized')
    },
    identify: function() {
        checkIfInitialized()
        return "I am " + this.me;
    },
    sayHi: function() {
        checkIfInitialized()
        return "Hi " + this.me;
    },
    sayGoodBye: function() {
        checkIfInitialized()
        return "Goodbye " + this.me;
    }
};

Here, I want to throw an error or deny the call of identify if the object was not initialized before call the function. However, I dont want to add a verifier inside each public routine of the Object.

How can I handle it without duplicating that behaviour?

  • why not use a class or constructor? – Daniel A. White Feb 23 '21 at 18:27
  • @DanielA.White because I am studying OLOO, not classes – Manuel Diez Feb 23 '21 at 18:37
  • What does "initialised" mean exactly to you? Does `const o = Object.create(Foo); o.init(null)` count as initialised? What about `o.init()`? Do you really care? There is no way to do this without explicitly calling a validation method. But you shouldn't need this anyway. It's the responsibility of the caller to invoke the method on a valid object, even more so in a loose pattern like OLOO - [rubbish in, rubbish out](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out). – Bergi Feb 23 '21 at 19:10
  • @Bergi I agree with that, it is the responsability of the caller invoking that method from a valid object. But if the caller do the wrong path calling the method before initializing or from an state that the object is not valid, where would you make the validation? – Manuel Diez Feb 24 '21 at 00:03
  • I'm not quite sure what validation you're thinking of. If it's `if (typeof this.me != 'string') throw new Error("Cannot invoke identify() on object without .me string property")`, that would need to go inside the `identify` function of course. Also for the single method in your example there won't be any duplication… It would be helpful if you could [edit] your question to include a more real-world example and included the code that you think is duplicated, so that we can advise how to make it dry. – Bergi Feb 24 '21 at 00:58
  • @Bergi I edited the code, is it more clear now? I apologize about it. Is the call of 'checkIfInitialized' method a violation of dry? – Manuel Diez Feb 24 '21 at 14:17
  • It would need to be `this.checkIfInitialised()` or `checkFooIsInitialised(this) ` – Bergi Feb 24 '21 at 20:56

0 Answers0