プログラムを書き続けているとコードが肥大化して読みにくいし汚らしくなってきます。
なので整理しやすく機能別にコードを分割した方が効率的です。
分割する前のソース
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestProjects
{
class TestProgram
{
static void Main(string[] args)
{
Todo todoA = new Todo();
Todo todoB = new Todo();
todoA.timelimit = "2020/01/01";
todoA.job = "練習用プログラムを作る";
todoB.timelimit = "2020/02/15";
todoB.job = "ソースを分割する";
Console.WriteLine("期限{0}", todoA.timelimit);
Console.WriteLine("内容{0}", todoA.job);
Console.WriteLine("期限{0}", todoB.timelimit);
Console.WriteLine("内容{0}", todoB.job);
Console.ReadLine();
}
}
class Todo
{
public string timelimit { get; set; }
public string job { get; set; }
}
}
こんな単純なプログラムを用意しました。
ソースを別ファイルに分割
このプログラムのTodoクラスを別のファイルに分割します。
TestProgram.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestProjects
{
class TestProgram
{
static void Main(string[] args)
{
Todo todoA = new Todo();
Todo todoB = new Todo();
todoA.timelimit = "2020/01/02";
todoA.job = "練習用プログラムを作る";
todoB.timelimit = "2020/02/16";
todoB.job = "ソースを分割する";
Console.WriteLine("期限{0}", todoA.timelimit);
Console.WriteLine("内容{0}", todoA.job);
Console.WriteLine("期限{0}", todoB.timelimit);
Console.WriteLine("内容{0}", todoB.job);
Console.ReadLine();
}
}
}
ああああTodoクラスを削除して新しく作ったtodo.csに貼り付けます。
todo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestProjects
{
class Todo
{
public string timelimit { get; set; }
public string job { get; set; }
}
}
使い方は分割する前と全く同じです。
この例では分かりにくいかもしれませんが、機能や役割別にソースを分割することで保守性も向上するし、なんと言っても美しくコードを書くことができるので整理しながらコーディングすることをお勧めします。

コメント