ทำไมเราต้องใช้ classes แทนที่จะเขียนโค้ดเป็นก้อนใหญ่สกปรก? ในระดับพื้นฐาน classes จัดระเบียบโค้ดและข้อมูลเป็นหน่วยที่เป็นตรรกะ แต่สำคัญกว่านั้นคือ Abstraction (การนามธรรม)
What Is An Abstraction? (การนามธรรมคืออะไร?)
คีย์บอร์ดที่ใช้พิมพ์ประกอบด้วยสายไฟ, สวิตช์, ที่พลาสติก, บอร์ดวงจร แต่มันคือ "คีย์บอร์ด" เพราะประกอบร่วมกันอย่างถูกต้อง การนามธรรมคือ ไม่ต้องรู้รายละเอียดภายในก็ใช้งานได้ เพียงเสียบแล้วพิมพ์ได้เลย Classes ทำให้เราสร้าง abstraction ได้เช่นกัน
Why Is Abstraction Important? (ทำไมการนามธรรมจึงสำคัญ?)
Abstraction ช่วยจัดการ Complexity (ความซับซ้อน) ตาม Steve McConnell: "เหตุผลสำคัญที่สุดในการสร้าง class คือลดความซับซ้อนของโปรแกรม" ทำได้โดยการ ซ่อนรายละเอียด (instance variables, internal methods, algorithms, data structures) และเปิดเผยเฉพาะ public interface (public methods)
ตัวอย่าง: GPS class ใช้ array เก็บข้อมูล index 0 = latitude, index 1 = longitude ผู้ใช้ไม่ควรต้องรู้รายละเอียดนี้
How To Write a Good Class (การเขียน Class ที่ดี)
หัวข้อกว้าง ต้องปฏิบัติตาม SOLID principles สำคัญที่สุดคือ class ต้องมี Role (บทบาท) ชัดเจน ไม่ใช่ก้อนเมธอดสุ่ม แยก business logic (คำนวณ, กฎ) จาก presentation logic (จัดรูปแบบ) เพราะเป็น role ต่างกัน
โค้ดที่ผสมผสาน responsibilities:
require 'rest-client'
require 'nokogiri'
class ImageCounter
def initialize(url)
@url = url
end
def find_images_and_report
data = RestClient.get(@url).body
html = Nokogiri::HTML.parse(data)
images = html.css("img")
report = ""
report << "=" * 40 << "\n"
report << "Found #{images.size} images on #{@url} \n"
report << "=" * 40 << "\n"
end
end
ควรแยก responsibilities เพื่อ Code Reuse สลับ presentation layer ได้ หรือเปลี่ยน business rules แล้ว reuse presentation เดิม
แนวคิดเพิ่มเติม: Cohesion & Coupling, Tell don't ask, Law of Demeter
Summary
เรียนรู้ว่าเราเขียน classes เพื่ออะไร Abstraction คืออะไร ทำไมสำคัญ พื้นฐานการเขียน class ที่ดี และแนวทางศึกษาต่อ หากไม่ต้องการโค้ดกลายเป็น "Big Ball of Mud" ให้เริ่มนำไปปฏิบัติวันนี้!