DRY 与"只做一件事"

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

不要重复自己(DRY)

train = pd.read_csv('train.csv')
train_y = train['labels'].values
train_X = train[col for col in train.columns if col != 'labels'].values
train_pca = PCA(n_components=2).fit_transform(train_X)
plt.scatter(train_pca[:,0], train_pca[:,1])
val = pd.read_csv('validation.csv')
val_y = val['labels'].values
val_X = val[col for col in val.columns if col != 'labels'].values
val_pca = PCA(n_components=2).fit_transform(val_X)
plt.scatter(val_pca[:,0], val_pca[:,1])
test = pd.read_csv('test.csv')
test_y = test['labels'].values
test_X = test[col for col in test.columns if col != 'labels'].values
test_pca = PCA(n_components=2).fit_transform(train_X)
plt.scatter(test_pca[:,0], test_pca[:,1])
Python 函数编写

重复的风险

train = pd.read_csv('train.csv')
train_y = train['labels'].values
train_X = train[col for col in train.columns if col != 'labels'].values
train_pca = PCA(n_components=2).fit_transform(train_X)
plt.scatter(train_pca[:,0], train_pca[:,1])
val = pd.read_csv('validation.csv')
val_y = val['labels'].values
val_X = val[col for col in val.columns if col != 'labels'].values
val_pca = PCA(n_components=2).fit_transform(val_X)
plt.scatter(val_pca[:,0], val_pca[:,1])
test = pd.read_csv('test.csv')
test_y = test['labels'].values
test_X = test[col for col in test.columns if col != 'labels'].values
test_pca = PCA(n_components=2).fit_transform(test_X)  ### yikes! ###
plt.scatter(test_pca[:,0], test_pca[:,1])
Python 函数编写

重复的另一问题

train = pd.read_csv('train.csv')
train_y = train['labels'].values  ### <- there and there --v ### 
train_X = train[col for col in train.columns if col != 'labels'].values
train_pca = PCA(n_components=2).fit_transform(train_X)
plt.scatter(train_pca[:,0], train_pca[:,1])
val = pd.read_csv('validation.csv')
val_y = val['labels'].values  ### <- there and there --v ### 
val_X = val[col for col in val.columns if col != 'labels'].values
val_pca = PCA(n_components=2).fit_transform(val_X)
plt.scatter(val_pca[:,0], val_pca[:,1])
test = pd.read_csv('test.csv')
test_y = test['labels'].values  ### <- there and there --v ### 
test_X = test[col for col in test.columns if col != 'labels'].values
test_pca = PCA(n_components=2).fit_transform(test_X)
plt.scatter(test_pca[:,0], test_pca[:,1])
Python 函数编写

用函数避免重复

def load_and_plot(path):
  """加载数据集并绘制前两个主成分。

  Args:
    path (str): CSV 文件路径。

  Returns:
    tuple of ndarray: (features, labels)
  """
  data = pd.read_csv(path)
  y = data['label'].values
  X = data[col for col in data.columns if col != 'label'].values
  pca = PCA(n_components=2).fit_transform(X)
  plt.scatter(pca[:,0], pca[:,1])
  return X, y
train_X, train_y = load_and_plot('train.csv')

val_X, val_y = load_and_plot('validation.csv')
test_X, test_y = load_and_plot('test.csv')
Python 函数编写
def load_and_plot(path):
  """加载数据集并绘制前两个主成分。

  Args:
    path (str): CSV 文件路径。

  Returns:
    tuple of ndarray: (features, labels)
  """
  data = pd.read_csv(path)
  y = data['label'].values
  X = data[col for col in data.columns if col != 'label'].values

  pca = PCA(n_components=2).fit_transform(X)
  plt.scatter(pca[:,0], pca[:,1])

  return X, y
Python 函数编写
def load_and_plot(path):
  """加载数据集并绘制前两个主成分。

  Args:
    path (str): CSV 文件路径。

  Returns:
    tuple of ndarray: (features, labels)
  """
  # load the data
  data = pd.read_csv(path)
  y = data['label'].values
  X = data[col for col in data.columns if col != 'label'].values

  pca = PCA(n_components=2).fit_transform(X)
  plt.scatter(pca[:,0], pca[:,1])

  return X, y
Python 函数编写
def load_and_plot(path):
  """加载数据集并绘制前两个主成分。

  Args:
    path (str): CSV 文件路径。

  Returns:
    tuple of ndarray: (features, labels)
  """
  # load the data
  data = pd.read_csv(path)
  y = data['label'].values
  X = data[col for col in data.columns if col != 'label'].values

  # plot the first two principal components
  pca = PCA(n_components=2).fit_transform(X)
  plt.scatter(pca[:,0], pca[:,1])

  return X, y
Python 函数编写
def load_and_plot(path):
  """加载数据集并绘制前两个主成分。

  Args:
    path (str): CSV 文件路径。

  Returns:
    tuple of ndarray: (features, labels)
  """
  # load the data
  data = pd.read_csv(path)
  y = data['label'].values
  X = data[col for col in data.columns if col != 'label'].values

  # plot the first two principle components
  pca = PCA(n_components=2).fit_transform(X)
  plt.scatter(pca[:,0], pca[:,1])

  # return loaded data
  return X, y
Python 函数编写

只做一件事(Do One Thing)

def load_data(path):
  """加载数据集。

  Args:
    path (str): CSV 文件路径。

  Returns:
    tuple of ndarray: (features, labels)
  """
  data = pd.read_csv(path)
  y = data['labels'].values
  X = data[col for col in data.columns 
           if col != 'labels'].values
  return X, y
def plot_data(X):
  """绘制矩阵的前两个主成分。

  Args:
    X (numpy.ndarray): 要绘制的数据。
  """
  pca = PCA(n_components=2).fit_transform(X)
  plt.scatter(pca[:,0], pca[:,1])
Python 函数编写

只做一件事的优势

代码将变得:

  • 更灵活
  • 更易理解
  • 更易测试
  • 更易调试
  • 更易修改
Python 函数编写

代码异味与重构

"任何傻瓜都能写出计算机能看懂的代码。优秀的程序员写的是人能看懂的代码。"——Martin Fowler(1999)

Martin Fowler 的《重构》

Python 函数编写

Ayo berlatih!

Python 函数编写

Preparing Video For Download...