Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

ยกระดับโค้ด Ruby: เชี่ยวชาญ Cohesion & Coupling สำหรับ OOP Design ที่สะอาด

Cohesion และ Coupling เป็นหลักการ OOP สำคัญที่สุด 2 ข้อ

Cohesion: ความสัมพันธ์ระหว่างเมธอดภายในคลาส ใช้ instance variables/parameters เดียวกัน ทำงานร่วมกันไปเป้าหมายเดียวกัน? หรือแต่ละเมธอดแยกจากกัน?

Coupling: คลาสขึ้นกับคลาสอื่นมากแค่ไหน "ผูกมัด" กันแน่นแค่ไหน และสามารถใช้งานแยกได้ไหม

เป้าหมาย: High Cohesion และ Low Coupling

An Example Of Cohesion

Low cohesion = ท็อปปิ้งแปลกบนพิซซ่า High cohesion = ทุกอย่างอยู่ที่ควรจะเป็น

class Library
  def lend_book; end
  def return_book; end
  def make_coffee; end  # ไม่เกี่ยวข้อง!
end

make_coffee ไม่ควรอยู่ใน Library แม้มี cafeteria ก็ไม่ควรเป็นหน้าที่ของ class นี้

แก้ไข: Extract เมธอดที่ไม่เกี่ยวข้องไป class ใหม่

วัด cohesion: เมธอดทำอะไร? ใช้ข้อมูลอะไร? ร่วมมือกับอ็อบเจ็กต์อะไร?

An Example Of Coupling

class ShoppingCart
  attr_accessor :items
  def initialize; @items = []; end
end
class Order
  def process_order(cart)
    cart.items.map(&:price).inject(:+)  # รู้รายละเอียด cart มากเกินไป
  end
end

Order coupled กับ ShoppingCart สูง รู้ items variable และคำนวณ เอง ถ้า ShoppingCart เปลี่ยน implementation Order ต้องแก้ด้วย

แก้ไข: ย้ายรายละเอียดการคำนวณไปอยู่ที่ ShoppingCart

class ShoppingCart
  def calculate_total
    items.map(&:price).inject(:+)
  end
end
class Order
  def process_order(cart)
    cart.calculate_total
  end
end

ลด coupling โดยย้ายรายละเอียดไปที่ที่มันเป็นของ มือถือแบตเตอรี่ถอดได้ = low coupling, แบตเตอรี่ติดตาย = high coupling

Summary

เรียนรู้ Cohesion & Coupling ช่วยประเมินว่าเมธอดในคลาสทำงานร่วมกันดีแค่ไหน และคลาสอิสระจากระบบอื่นแค่ไหน ลองเปิดโปรเจกต์ดูและปรับปรุง class ด้วยหลักการนี้!