Sonar Issue: Update this function so that its implementation is not identical to the one on line 159

Viewed 32

Im trying to make my Project a little better by fixing all issues with sonar and I am stuck on the error displayed in the title. The function is loading a blender model with the help of three.js and sonar tells me to not use the function more than once but I need to load multiple models with this function.

function raining(temp, timezone) {
  let rain = [];
  
  function loadGLTF() {
    let Loader = new GLTFLoader();

    Loader.load("./model/rain.gltf", (gltf) => {
      Mesh = gltf.scene;
      Mesh.scale.set(0.2, 0.2, 0.2);
      scene.add(Mesh);
      camera.target = Mesh;
      Mesh.position.x = 0;
      Mesh.position.y = -0.4;
      Mesh.position.z = 0;
    });
  }

I can put the loadGLTF function out of the raining one but how can I use the function again to load my second model ./model/snow.gltf

1 Answers

This sonar error is not very friendly... What it really means is that you are defining a function that is the exact replica of another function defined somewhere else (on line 159).

This often is the case with redundant callbacks.

It's hard to suggest the best refactor here since we have a very small portion of your code. My guess is that the callback to Loader.load is the function being repeated. If that's the case, simply create it as a function and reuse it.

The problem could also be the loadGLTF function. First, you define it inside another function, that means it will always be "rebuilt" when raining() is called.

The best would be to define it outside of rain, and then call it inside rain.

Going further, you could refactor this to be generic for any mesh you'd like to load:

// Define Loader outside of function, keep only one and reuse it.
const Loader = new GLTFLoader();
function loadGLTF(path) {
    Loader.load(path, (gltf) => {
      Mesh = gltf.scene;
      Mesh.scale.set(0.2, 0.2, 0.2);
      scene.add(Mesh);
      camera.target = Mesh;
      Mesh.position.x = 0;
      Mesh.position.y = -0.4;
      Mesh.position.z = 0;
    });
}

You could go further by passing a second parameter to define the position and scale if it is not always the same.

Related