Ruby Coding Convention (Phần 4)
January 23, 2014
Trong phần này, tôi sẽ tiếp tục giúp mọi người tìm hiểu về Class, Modules, Exceptions, Collections
Classes & Modules
- Sử dụng một cấu trúc thống nhất cho các class mà bạn định nghĩa.
class Person extend SomeModule include AnotherModule SOME_CONSTANT = 20 attr_reader :attribute_name validates :attribute_name # public classes def some_method end # protected and private methos protected def some_protected_method end private def some_private_method end end
- Sử dụng
modulethay choclassnếu chỉ định nghĩa funtions.classchỉ nên dùng khi chúng ta tạo đối tượng mới khi dùng# bad class SomeClass def self.some_method # body omitted end def self.some_other_method end end # good module SomeClass module_function def some_method # body omitted end def some_other_method end end - Sử dụng
attr_readervàattr_accessorkhi có thể# bad class Person def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def first_name @first_name end def last_name @last_name end end # good class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end end - Thiết kế class dựa theo nguyên lý SOLID
- Tránh sử dụng
@khi không cần thiết phải sử dụng ở bên ngoài class - Tránh sử dụng
@@khi không cần thiết vì nó là biến toàn cụcclass Parent @@class_var = 'parent' def self.print_class_var puts @@class_var end end class Child "child" - Định nghĩa lại các hàm
to_s, as_jsonnếu bạn cầnclass Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def to_s "#{@first_name} #{@last_name}" end def as_json first_name: first_name, last_name: last_name end end - Sử dụng
def self.methodđể định nghĩa singleton methods.class TestClass # bad def TestClass.some_method # body omitted end # good def self.some_other_method # body omitted end end
Exceptions
- Chỉ sử dụng
raisekhi bắt một exception. Còn nếu không, hãy sử dụngfailbegin fail 'Oops' rescue => error raise if error.message != 'Oops' end - Không return trong
ensureblock, Khi bạn sử dụng return trong đó, sẽ không exception nào được raise. - Sử dụng tích hợp
beginblocks nếu có thể# bad def foo begin # main logic goes here rescue # failure handling goes here end end # good def foo # main logic goes here rescue # failure handling goes here end - Không sử dụng exceptions khi nó đóng vai trò trong luồng xử lý chính
# bad begin n / d rescue ZeroDivisionError puts 'Cannot divide by 0!' end # good if d.zero? puts 'Cannot divide by 0!' else n / d end
- Không rescuing
Exceptionclass.# bad begin exit rescue Exception puts "you didn't really want to exit, right?" # exception handling end # good begin # code obmitted rescue => e # exception handling end - Nếu bạn có nhiều rescues, hãy sắp xếp chúng hợp lý.
begin # some code rescue StandardError => e # some handling rescue Exception => e # some handling end



