Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

documenting side-effects of javascript methods

I'm trying to improve the documentation of my javascript code, and am following the JSDoc guidelines https://jsdoc.app/.

I can't find how to document an intentional side-effect. For example the following method:

/**
  * @description
  *   Paints the object red.
  * @return
*/
Painter.paintItRed = function(someObj){
    someObj.color = "red";
};

How do you document the fact that the method acts directly on the passed object? A different example:

/**
  * @description
  *   If the user has not setUp a config, show config Modal.
  * @return
*/
User.checkConfig = function(user){
    if(!user.config.valid){
       showConfigModal();
    }
};

These are contrived examples and probable "code smells", but that's another issue. I'm looking at some best-practices on how to document such behavior (for good or bad). Something perhaps better than //IMPORTANT!! This method is dangerous!

like image 671
mastaBlasta Avatar asked Aug 14 '14 18:08

mastaBlasta


People also ask

What are side effects in Javascript?

Any operation that is not directly related to the final output of the function is called a Side Effect . Now let us see an impure function where we mutate the input and do something that we are not supposed to in a pure function.

How do I avoid side effects in code?

Use pure functions wherever you can. A pure function does not produce side effects. Given the same inputs, a pure function will always return the same output. Notice how much of the program state can be represented as lists of things.


1 Answers

Since version 3.6.0, JSDoc has an undocumented @modifies tag for exactly this purpose.
See commit 2f99af8 and issue 1283.


Previous answer, included for the reference to adding your own tag. There is no standardized way of doing this. At least not in JavaDoc, which, to be fair, is what JSDoc is mimicking. There is an issue to add it to JSDoc, by the way, that is actually referencing this question.

If you really want to document this, you can add a custom tag, like you can for JavaDoc. You could use that to add, for example, an @affects tag. It could be used as follows.

/**
 * @description
 *   Paints the object red.
 * @param someObj
 *   The object to be painted.
 * @affects
 *   someObj.color
 */
Painter.paintItRed = function(someObj) {
    someObj.color = 'red';
};

Defining a custom tag in JSDoc is not hard, also see this related question.

like image 95
Just a student Avatar answered Oct 30 '22 20:10

Just a student