The document discusses various techniques for refactoring Ruby code including improving readability, maintainability, and extensibility while preserving existing behavior. It provides examples of simplifying conditional logic, reducing duplication, improving brevity, and leveraging built-in Ruby methods and syntax.
56. Delegation
class User
has_one :account
def balance
self.account.balance
end
def balance=(amount)
self.account.balance=(amount)
end
end
57. Delegation
class User
has_one :account
delegate :balance, :balance=, :to => :account
end
58. Memoization
class Avatar
def file_size
if @file_size
return @file_size
else
result = some_expensive_calculation
result += more_expensive_calculation
@file_size = result
end
end
end
59. Memoization
class Avatar
extend ActiveSupport::Memoizable
def file_size
result = some_expensive_calculation
result += more_expensive_calculation
end
memoize :file_size
end
Code refactoring is the process of changing a computer program's source code without modifying its external functional behavior in order to improve some of the nonfunctional attributes of the software.\n\nIt can be as simple as renaming a method or a class or making cosmetic changes (e.g. adding whitespace, aligning indentation or breaking long lines of code). Though that’s a worthy topic, I am not going to focus on cosmetic style choices today. Instead I’m going to share some examples of simple recurring code patterns that are candidates for refactoring.\n\nDisclaimer: You may find that some of the following techniques convolute logic. If so, don’t use them. Work with your team to establish what is acceptable and develop your own style guide. Also, if performance is a concern, always profile.\n
The goal is to improve readability, not impede it.\n\nWe’re not compressing javascript files here.\n\nIn fact, refactoring may be removing unnecessarily complex implementations or use of design patterns.\n\n
Advantages include \nimproved code readability and reduced complexity to improve the maintainability of the source code,\nas well as a more expressive internal architecture or object model to improve extensibility.\n
\n
You’ll see that I have a title for each of these patterns. Some came from the internets, some from people I’ve worked with, and some I just made up.\n
\n
\n
\n
\n
Forces a boolean return value. True unless @foo is nil or false.\n\nTwo logical NOT operators\n
Using the ternary operator\n
Forces a boolean return value. True unless @foo is nil or false.\n\nTwo logical NOT operators\n