0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

関数の呼び方(名前空間の参照 vs 関数名そのまま)

Posted at

ReactNativeで開発している時ふと感じた、関数呼び出しに関する疑問を解消するため備忘録。

(tts機能を例に、)関数呼び出しの仕方が次の二つで何が違うのかをみていきたいと思います。
(名前空間の参照か、関数名そのまま使いたいかによる違い)

// {}内関数名を呼び出し
import { speakText, stopText, initializeTts, removeTtsListeners } from './utils/ttsUtils';

// ttsUtils.tsに記述されている関数名をそのまま呼び出し
import * from './utils/ttsUtils';

import * as を使用する例

import * as を使用することで、モジュール内のすべてのエクスポートを名前空間としてまとめてインポートすることができる。その場合、ttsUtils.ts 内の関数を名前空間から参照して呼び出す形になる。

import * as TTSUtils from './utils/ttsUtils';

const AnotherComponent: React.FC = () => {
  return (
    <View>
      <Button title="Speak" onPress={() => TTSUtils.speakText('Hello, world!')} />
      <Button title="Stop" onPress={TTSUtils.stopText} />
    </View>
  );
};

メリット:競合防止

他のモジュールから同じ名前の関数をインポートする場合、名前空間を使うことで競合を回避できます。

TTSUtils.speakText(); // text-to-speech
ITSUtils.speakText(); // image-to-speech
GTSUtils.speakText(); // gesture-to-speech

デメリット:冗長になる可能性

関数を呼び出すたびに名前空間を明示する必要があり、文字列が長くなる場合が多い(例: TextToSpeechUtilities.speakText())。

関数名をそのまま使いたい場合

もし関数名をそのまま呼び出したい場合は、import * asではなく、個別にインポートする方法が適切である。

import { speakText, stopText } from './utils/ttsUtils';

const AnotherComponent: React.FC = () => {
  return (
    <View>
      <Button title="Speak" onPress={() => speakText('Hello, world!')} />
      <Button title="Stop" onPress={stopText} />
    </View>
  );
};

メリット:コードの簡潔さ

直接インポートして使用するため、読みやすく記述量が減る。

デメリット:依存の明示性が低下

関数が外部依存であることがコンポーネント内部から見えにくい。

どちらを使うべきか

少数の関数や値を使う場合は、個別インポートimport { speakText, stopText }を使う方がシンプル。

多くの関数や値を使う場合は、名前空間インポートimport * as TTSUtilsを使うほうが管理しやすそう。

というように、実装時のニーズに応じて使い分けると良いでしょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?