Web制作、Web開発の歩き方

インターフェースを理解して、設計力を高めよう

第2話:インターフェースの実例

(最終更新日:2024.1.21)

Linuxのイメージ
この記事は5分で読めます!
(絵が小さい場合はスマホを横に)

「インターフェース is 何?、その2」

前回、インターフェースの概要や定義について学んだ。 今回はインターフェースの役割と、簡単な使用例を通して、インターフェースについての具体的なイメージを掴んでいこう。


1.インターフェースの役割

プログラミングにおけるインターフェースは、ソフトウェアコンポーネントが互いに独立している状態、つまり疎結合を促進する役割を果たす。 疎結合は、一方の変更が他方に少ない影響を与えることを意味し、インターフェースは異なるコンポーネント間の具体的な実装の詳細を隠蔽することでこれを実現する。 さらに、インターフェースによって定義された契約に従って、異なる状況で同じコンポーネントを再利用することが可能になる。 これにより、汎用的なインターフェースを持つことで、さまざまな状況や要求に対応可能なソフトウェアを設計できる。

拡張性と保守性もインターフェースの重要な機能だ。 インターフェースを使用することで、システムを拡張する際に既存のコードに大幅な変更を加える必要がなくなり、システムの保守が容易になり、エラーの追跡と修正が簡単になる。 インターフェースはまた、複雑な実装を隠蔽し、より高いレベルの抽象化を提供する。 システムを管理しやすい階層に分割し、それぞれのレイヤーがインターフェースを通じて相互作用することで、全体のモジュール性と可読性が向上する。

技術の進化に対応するための柔軟性と互換性もインターフェースが提供する。 新しい技術や方法論が登場した際に、既存のシステムを容易に更新できるようになり、 同じインターフェースを実装する異なるクラスやモジュールが互いに交換可能になるため、より柔軟なソフトウェア設計が可能になる。 さらに、インターフェースを利用することで、実装の詳細を隠蔽し、コンポーネントの単位のテストを容易に行うことができる。 これにより、エラーの特定と解決が迅速に行えるようになる。

本項以降では、プログラミングにおけるインターフェースの多様な役割を詳細に解説する。 疎結合の促進、再利用性の向上、拡張性と保守性の強化、抽象化と階層化の促進、柔軟性と互換性の確保、そしてテストとデバッグの容易化といった点を通じて、 インターフェースがプログラミング設計において果たす重要な役割を理解させることを目的とする。 これにより、インターフェースの基本的な概念に加えて、その実践的な価値を認識できるようになる。

機器間の約束事は決まっていて
他の機能(アプリ)に影響しない
(プログラムコンポーネント間でも同じ)


2.簡単なインターフェースの例

今回はTypeScriptを用いて、インターフェースの具体例を紹介しよう。 TypeScriptでは、インターフェースはクラスやオブジェクトの型を定義するために使用される。 これにより、特定のプロパティやメソッドを持つことを保証できる。

下記ではinterfaceとしてPersonを定義し、それに合った情報を出すと、いつも同じ挨拶をするようになる。

TypeScriptのインターフェースの例

次にWeb APIを利用する場合を取り上げる。 fetch APIを使用してWebサービスにアクセスし、TypeScriptの型を活用してレスポンスの形式を定義する。

下記では天気情報APIからデータを取得し、TypeScriptの型を用いてレスポンスの形式を定義している。 Promise< WeatherResponse>は、TypeScriptの非同期の際の特有の書き方である。

APIで用いるインターフェースの例

最後にGUIの開発例を取り上げる。 ReactやSvelteなどのフレームワークを使用したTypeScriptでのGUI開発で、コンポーネントのプロパティや状態をTypeScriptの型で定義する。

下記ではReactを使用、TypeScriptの型を用いてレスポンスの形式を定義している。 ログインフォームコンポーネントを作成し、入力値やイベントハンドラをTypeScriptの型を使ってinterfaceを定義している。

Reactのログインフォームの例

TypeScriptでは、インターフェースを使用してオブジェクトの形状を定義し、APIのレスポンス型やGUIコンポーネントのプロパティを厳密に管理する。 これにより、より堅牢で保守しやすいアプリケーション開発が可能になる。 これらの具体的な例を通じて、TypeScriptでのインターフェースの利用方法とその重要性を理解することができたと思う。


3.まとめ

今回はインターフェースの役割と具体的な実装例について取り上げた。 インターフェースを用いて、実装するイメージが少しついたと思う。 上記では取り上げなかったが、クラスに対するメソッドの定義もインターフェース上で行うことができる。 下記に簡単に示す。次回は、インターフェースのより良い設計について説明する。

メソッドを定義したinterface

▼参考図書、サイト

 「ちょうぜつソフトウェア設計入門―PHPで理解するオブジェクト指向の活用」 技術評論社 田中ひさてる
C#入門編(12)オブジェクト指向【インターフェイス】 C#で学ぶプログラミング入門
インターフェース (interface) サバイバルTypeScript


Understand Interfaces to Improve Your Design Skills Part 2: Practical Examples of Interfaces (Last updated: Jan 21, 2024) Image representing Linux Estimated reading time: 5 minutes (If the images appear small, try rotating your smartphone sideways.) "What is an Interface? – Part 2" In the previous part, we covered the basic definition and overview of interfaces. In this article, we'll dive into the roles interfaces play and explore simple examples to help you better visualize how they work. [Contents] Role of Interfaces Simple Interface Examples Summary 1. Role of Interfaces In programming, an interface helps promote *loose coupling*, where software components operate independently. Loose coupling means that changes to one part of a system have minimal impact on others. Interfaces enable this by hiding the implementation details between components. By adhering to contracts defined by interfaces, you can reuse components in different contexts. Well-defined interfaces allow developers to design software that's adaptable to various scenarios and requirements. Interfaces also contribute to extensibility and maintainability. You can extend systems without making major changes to existing code, simplifying maintenance and reducing the risk of introducing new bugs. Interfaces hide complexity and promote higher levels of abstraction, improving modularity and readability by organizing the system into manageable layers. They also provide flexibility and compatibility to keep up with evolving technologies. When new tools or approaches emerge, systems can be updated easily if components share the same interface—this interchangeability enables more robust design. Interfaces also support unit testing by hiding implementation details, making it easier to isolate and fix errors. The following sections will break down these roles in detail—how interfaces facilitate loose coupling, improve reusability, boost extensibility and maintainability, support abstraction and layering, ensure flexibility and compatibility, and simplify testing and debugging. You'll gain a solid understanding of the critical role interfaces play in programming design. Rules between devices are fixed and don't affect other features (apps) (Same goes for program components) 2. Simple Interface Examples Let’s explore some practical examples of interfaces using TypeScript. In TypeScript, interfaces define the structure of classes or objects, ensuring they include specific properties or methods. Below is an example where an interface named `Person` is defined. When used, it ensures consistent greetings. Example of an Interface in TypeScript Next, let's consider using a web API. Using the `fetch` API, we access a web service and define the expected response structure with a TypeScript interface. The example below shows how to get data from a weather API and define the response shape using TypeScript. The `Promise` syntax is common for handling asynchronous data in TypeScript. Example of Interface in API Usage Lastly, here’s an example from GUI development. In frameworks like React or Svelte, TypeScript interfaces define component props and state types. In the example below, React is used with TypeScript to define a login form component, using an interface to structure input values and event handlers. Login Form Example Using React In TypeScript, interfaces are used to define object shapes, manage API response types, and specify GUI component properties. This results in more robust and maintainable applications. These examples should help you understand how interfaces are used in real development with TypeScript. 3. Summary In this article, we explored the role of interfaces and some practical implementation examples. Hopefully, you've now gained a clearer image of how to use interfaces in your own code. While we didn't cover it in detail, you can also define methods for a class via an interface. Here's a simple example. In the next article, we’ll discuss how to design better interfaces. Interface Defining Class Methods ▼Reference Books & Websites  "Chouzetsu Software Design Intro – Understanding Object-Oriented Programming through PHP" by Hisateru Tanaka, Gijutsu-Hyoron Co.  C# Intro (12): Object-Oriented Programming [Interface] – Learn Programming with C#  Interface – Survival TypeScript