MST

星途 面试题库

面试题:Ruby代码可维护性之方法设计

请简述在Ruby中,如何设计一个方法来提升代码的可维护性。比如从方法的参数数量、返回值处理以及方法功能的单一性等方面进行说明,并举例代码展示。
22.1万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

1. 控制方法参数数量

  • 原则:方法参数数量不宜过多,过多参数会使方法难以理解和维护。一般建议方法参数不超过3 - 4个。如果参数过多,可以考虑将相关参数封装成对象。
  • 示例
# 过多参数的情况
def calculate_area(length, width, height, shape_type)
  case shape_type
  when :rectangle
    length * width
  when :cuboid
    2 * (length * width + length * height + width * height)
  end
end

# 封装参数的情况
class ShapeParams
  attr_accessor :length, :width, :height, :shape_type
  def initialize(length, width, height, shape_type)
    @length = length
    @width = width
    @height = height
    @shape_type = shape_type
  end
end

def calculate_area(params)
  case params.shape_type
  when :rectangle
    params.length * params.width
  when :cuboid
    2 * (params.length * params.width + params.length * params.height + params.width * params.height)
  end
end

params = ShapeParams.new(5, 3, 2, :cuboid)
area = calculate_area(params)

2. 清晰的返回值处理

  • 原则:方法的返回值应该是明确且符合预期的。避免返回多个不同类型的值,除非使用特定的数据结构(如数组、哈希)来清晰组织。
  • 示例
# 不清晰的返回值
def divide_numbers(a, b)
  if b == 0
    return 'Error: Division by zero'
  else
    return a / b
  end
end

# 清晰的返回值(使用哈希)
def divide_numbers(a, b)
  if b == 0
    { status: :error, message: 'Division by zero' }
  else
    { status: :success, result: a / b }
  end
end

result = divide_numbers(10, 2)
if result[:status] == :success
  puts "The result is #{result[:result]}"
else
  puts result[:message]
end

3. 保持方法功能单一性

  • 原则:一个方法应该只做一件事,这样可以使代码更易读、易维护,并且方便复用。
  • 示例
# 功能不单一的方法
def process_user(user)
  user.validate
  user.save
  user.send_welcome_email
end

# 功能单一的方法
def validate_user(user)
  user.validate
end

def save_user(user)
  user.save
end

def send_welcome_email(user)
  user.send_welcome_email
end

user = User.new
validate_user(user)
save_user(user)
send_welcome_email(user)