moveSlides() の中に updateButtons() や updateDots() を入れてもよいのですか?

期待する動作になっていれば間違いではありませんが、関数は名前に見合った処理のみを書いておくと保守しやすくなります。
2021年10月19日
ユーザー

moveSlides()の中にupdateButtons()updateDots()を入れると、重複が減ると思うのですが、この書き方はありなのでしょうか? いろいろな書き方があるとは思うのですが、「この書き方でも全然問題ない、むしろ良い」や「この書き方だと不都合がある」などデメリットもあれば教えていただきたいです。
どうぞ、よろしくお願いいたします。

"use strict";

{
  const next = document.getElementById("next");
  const prev = document.getElementById("prev");
  const ul = document.querySelector("ul");
  const slides = ul.children;
  const dots = [];
  let currentIndex = 0;

  function updateButtons() {
    prev.classList.remove("hidden");
    next.classList.remove("hidden");

    if (currentIndex === 0) {
      prev.classList.add("hidden");
    }
    if (currentIndex === slides.length - 1) {
      next.classList.add("hidden");
    }
  }

  function moveSlides() {
    // 2行追加
    updateDots();
    updateButtons();
    const slideWidth = slides[0].getBoundingClientRect().width;
    ul.style.transform = `translateX(${-1 * slideWidth * currentIndex}px)`;
  }

  function setupDots() {
    for (let i = 0; i < slides.length; i++) {
      const button = document.createElement("button");
      button.addEventListener("click", () => {
        currentIndex = i;
        // updateDots();
        // updateButtons();
        moveSlides();
      });
      dots.push(button);
      document.querySelector("nav").appendChild(button);
    }

    dots[0].classList.add("current");
  }

  function updateDots() {
    dots.forEach((dot) => {
      dot.classList.remove("current");
    });
    dots[currentIndex].classList.add("current");
  }

  updateButtons();
  setupDots();

  next.addEventListener("click", () => {
    currentIndex++;
    // updateButtons();
    // updateDots();
    moveSlides();
  });

  prev.addEventListener("click", () => {
    currentIndex--;
    // updateButtons();
    // updateDots();
    moveSlides();
  });

  window.addEventListener("resize", () => {
    moveSlides();
  });
}

この回答を見るにはプレミアムサービスへの登録が必要です

プレミアムサービスとは?