1
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?

クラスのメンバの更新(関数・switch)

Posted at

今回学んだのは、クラスに 変更用のメソッド を追加して、クラスのインスタンスをスマートに更新する方法!

関数 や switch を作ったり使ったりしてコードの改善?に挑戦してみた!



問題概要

  • Employee クラスに numbername がある

  • getnum()getname() で取得できる

  • 今回はさらに change_num()change_name() を作って、作った後でも番号や名前をサクッと変えられるようにする!


入力例:

4
make 3 nana
getnum 1
change_num 1 5
getnum 1

出力例:

3
5






✅ OKコード例:

const rl = require('readline').createInterface({input:process.stdin});
const lines = [];

rl.on('line', (input) => {
    lines.push(input);
});

rl.on('close', () => {
    const N = Number(lines[0]);
    
    class Employee{
        
        constructor(number, name){
            this.number = Number(number);
            this.name = name;
        }
        
        getnum() {
            return this.number;
        }
        
        getname() {
            return this.name;
        }
        
        change_num(newNum){
            this.number = Number(newNum);
        }
        
        change_name(newName){
            this.name = newName;
        }
    }
    
    
    const employees = [];
    
    for(let i = 1; i <= N; i++){
        const tokens = lines[i].split(' ');
        const command = tokens[0];
        
        if(command === 'make'){
            const number = tokens[1];
            const name = tokens[2];
            employees.push(new Employee(number, name));
        }
        
        else {
            const index = Number(tokens[1]) - 1;
            
            if (command === 'getnum'){
                console.log(employees[index].getnum());
            }
            
            else if (command === 'getname'){
                console.log(employees[index].getname());
            }
            
            else if (command === 'change_num'){
                employees[index].change_num(tokens[2]);
            }
            
            else if (command === 'change_name'){
                employees[index].change_name(tokens[2]);
            }
        }
    }
});

外から直接プロパティをいじらず、メソッド経由で変更!






✨改良コード例:

const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];

rl.on('line', (input) => lines.push(input));

rl.on('close', () => {
  const N = Number(lines[0]);

  class Employee {
    constructor(number, name) {
      this.number = Number(number);
      this.name = name;
    }

    getnum() {
      return this.number;
    }

    getname() {
      return this.name;
    }

    change_num(newNum) {
      this.number = Number(newNum);
    }

    change_name(newName) {
      this.name = newName;
    }
  }



  const employees = [];

  const getIndex = (n) => {
      return Number(n) - 1;
  };
  
  for (let i = 1; i <= N; i++) {
    const [command, arg1, arg2] = lines[i].split(' ');

    switch (command) {
      case 'make':
        employees.push(new Employee(arg1, arg2));
        break;

      case 'getnum': {
        const index = getIndex(arg1);
        if (employees[index]) console.log(employees[index].getnum());
        break;
      }

      case 'getname': {
        const index = getIndex(arg1);
        if (employees[index]) console.log(employees[index].getname());
        break;
      }

      case 'change_num': {
        const index = getIndex(arg1);
        if (employees[index]) employees[index].change_num(arg2);
        break;
      }

      case 'change_name': {
        const index = getIndex(arg1);
        if (employees[index]) employees[index].change_name(arg2);
        break;
      }
    }
  }
});

✅ どこを?

🔹1️⃣ switch でコマンドを整理

if-else が減り、パターン追加が簡単。



🔹 2️⃣ 分割代入で可読性UP

const [command, arg1, arg2] = lines[i].split(' ');

👉 毎回 tokens[0] とか書かない。

arg は argument(引数) の略



🔹 3️⃣ getIndex 関数で範囲チェックを共通化

Number(arg1) – 1 を使い回せる。



🔹 4️⃣ if(employees[index]) の存在をチェック

undefined なら何もしないのでエラー防止。

一応の存在確認の保険なのでなくてもいける。






🗒️めも&まとめ

  • switchif-else より追加しやすく見やすい(今回の場合)。

  • 入力パーツを名前で扱うことで意図が明確。

  • バリデーションが1行で済む。

✨「読みやすく、拡張しやすいコード」 を目指す!




僕の失敗談(´;ω;`)と解決法🐈

1
0
2

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
1
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?