Refactoring

引数改善(C#)

改善対象

public static void ShowPerson(string name, string address, string phone, int age)

{

// do something

}

Person.ShowPerson("Andy", "Tokyo", "123", 18);

★方法1

public interface IParam { }

public class PersonParam : IParam

{

public string Name { get; set; }

public string Address { get; set; }

public string Phone { get; set; }

public int Age { get; set; }

}

public class Params : Dictionary<string, IParam> { }

public static void ShowPerson( IParam param )

{

var p = param as PersonParam;

// do something

}

Params pas = new Params();

var person = new PersonParam()

{

Address = "Tokyo",

Name = "Andy",

Phone = "123",

Age = 18

};

pas.Add("keyName", person);

Person.ShowPerson( pas["keyName"] );

★方法2

public static void ShowPerson(string name = "Andy", string address = "Tokyo", string phone = "", int age = 0)

{

// do something

}

Person.ShowPerson(age: 18, phone: "123");

★方法3

public static void ShowPerson(PersonParam param)

{

// do something

}

public class PersonParam

{

private string name;

private int age;

private string address;

private string phone;

public PersonParam Name(string o)

{

this.name = o;

return this;

}

//...

}

PersonParam p = new PersonParam();

p.Age(18).Name("Andy").Address("Tokyo").Phone("123");

Person.ShowPerson(p);

C#

PHP

JavaScriptとjQuery

Java

if/else, switch/case削減

★Enum方法

public enum Status {

NEW(0),RUNNABLE(1),RUNNING(2),BLOCKED(3),DEAD(4);

public int statusCode;

Status(int statusCode){

this.statusCode = statusCode;

}

}

int statusCode = Status.valueOf("NEW").statusCode;

★Optional方法

Optional<User> userOptional = Optional.ofNullable(user);

userOptional.map(action1).orElse(action2);

★マッピング方法

int monthDays[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int getMonthDays(int month){

return monthDays[--month];

}

Map<?, Function<?> action> actionsMap = new HashMap<>();

actionsMap.put(value1, (someParams) -> { doAction1(someParams)});

actionsMap.put(value2, (someParams) -> { doAction2(someParams)});

actionsMap.put(value3, (someParams) -> { doAction3(someParams)});

actionsMap.get(param).apply(someParams);