Access Control
When designing a class interface, it’s important to consider just how much access to
your class you’ll be exposing to the outside world. Allow too much access into your
class, and you risk increasing the coupling in your application—users of your class will
be tempted to rely on details of your class’s implementation, rather than on its logical
interface. The good news is that the only easy way to change an object’s state in Ruby
is by calling one of its methods. Control access to the methods, and you’ve controlled
access to the object. A good rule of thumb is never to expose methods that could leave
an object in an invalid state. Ruby gives you three levels of protection.
• Public methods can be called by anyone—no access control is enforced.Methods
are public by default (except for initialize, which is always private).
• Protected methods can be invoked only by objects of the defining class and its
subclasses. Access is kept within the family.
• Privatemethods cannot be called with an explicit receiver—the receiver is always
self. This means that private methods can be called only in the context of the
current object; you can’t invoke another object’s private methods.
The difference between “protected” and “private” is fairly subtle and is different in
Ruby than in most common OO languages. If a method is protected, it may be called
by any instance of the defining class or its subclasses. If a method is private, it may
be called only within the context of the calling object—it is never possible to access
another object’s private methods directly, even if the object is of the same class as the
caller.
Ruby differs from other OO languages in another important way. Access control is
determined dynamically, as the program runs, not statically. You will get an access
violation only when the code attempts to execute the restricted method.
Specifying Access Control
You specify access levels to methods within class or module definitions using one or
more of the three functions public, protected, and private. You can use each function
in two different ways.
If used with no arguments, the three functions set the default access control of subsequently
defined methods. This is probably familiar behavior if you’re a C++ or Java
programmer, where you’d use keywords such as public to achieve the same effect.
class MyClass
def method1 # default is 'public'
#...
end
protected # subsequent methods will be 'protected'
def method2 # will be 'protected'
#...
end
private # subsequent methods will be 'private'
def method3 # will be 'private'
#...
end
public # subsequent methods will be 'public'
def method4 # and this will be 'public'
#...
end
end
Alternatively, you can set access levels of named methods by listing them as arguments
to the access control functions.
class MyClass
def method1
end
# ... and so on
public :method1, :method4
protected :method2
private :method3
end
It’s time for some examples. Perhapswe’remodeling an accounting system where every
debit has a corresponding credit. Because we want to ensure that no one can break this
rule, we’ll make the methods that do the debits and credits private, and we’ll define our
external interface in terms of transactions.
class Accounts
def initialize(checking, savings)
@checking = checking
@savings = savings
end
private
def debit(account, amount)
account.balance =
amount
end
def credit(account, amount)
account.balance += amount
end
public
#...
def transfer_to_savings(amount)
debit(@checking, amount)
credit(@savings, amount)
end
#...
end
Protected access is used when objects need to access the internal state of other objects
of the same class. For example, we may want to allow individual Account objects to
compare their raw balances but may want to hide those balances from the rest of the
world (perhaps because we present them in a different form).
class Account
attr_reader :balance # accessor method 'balance'
protected :balance # and make it protected
def greater_balance_than(other)
return @balance > other.balance
end
end
Because the attribute balance is protected, it’s available only within Account objects.
分享到:
相关推荐
从给定的文件信息中,我们可以提炼出一系列关于Ruby编程语言的重要知识点,涵盖基础语法、变量类型、数值操作、条件语句、循环结构以及字符串处理等核心领域。 ### Ruby基础语法 #### 注释 Ruby提供了两种注释方式...
"ruby笔记2ruby笔记2ruby笔记2"可能是指一系列关于Ruby学习的笔记,这些笔记可能涵盖了Ruby的基础概念、核心特性以及进阶话题。在Ruby的学习过程中,理解和掌握以下几个关键知识点至关重要: 1. **面向对象编程...
这份"Ruby学习资料(含参考手册和Programming Ruby)-中文.rar"压缩包包含了一系列的资源,帮助初学者和进阶者深入理解Ruby语言。 首先,"ruby中文文档(含参考手册和Programming Ruby).chm"是一个综合性的中文参考...
### Extjs 5 学习笔记之 SenchaCmd 深入解析 #### 一、SenchaCmd 的简介 SenchaCmd 是一个跨平台的命令行工具,它为基于 ExtJS 和 Sencha Touch 应用程序的开发周期提供了全面的支持。从创建应用程序的基础结构到...
在进行 Ruby on Rails 的开发之前,首先需要完成一系列的基础软件安装工作,包括但不限于 Ruby 语言环境、Rails 框架、版本管理工具等。 ##### 安装基础依赖 1. **更新系统包列表:** ```sh sudo apt-get update...
在本篇ROR(Ruby on Rails)学习笔记中,我们将深入探讨如何在Windows XP操作系统上进行环境的安装和配置。Ruby on Rails是一个流行的开源Web应用框架,它基于Ruby编程语言,以其“DRY”(Don't Repeat Yourself)...
摘要:一直想尝试Ruby On Rails,但是因为对apache,mysql都不熟,对Rails的环境搭建更是没信心,所以一直没有开始,从知道了InstantRails后,终于在windows上搭建了Ruby On Rails开发环境,开始了Rails的学习。...
### Solr学习笔记_v1.1 - 高性能搜索引擎的核心参数与查询语法详解 #### 一、Query参数:深入理解Solr查询的核心要素 Solr作为高性能的全文搜索引擎,其强大的查询能力很大程度上依赖于一系列精细调整的参数。以下...
### GDAL-Python库学习笔记 #### 一、GDAL 库简介 ##### 1.1 引言 GDAL(Geospatial Data Abstraction Library)是一个强大的库,旨在为栅格地理空间数据提供翻译与处理功能。对于从事地理信息系统(GIS)或遥感...
这个"java学习笔记JDK6课件和课本代码"资源很可能是包含了一系列的教程、PPT课件、示例代码和练习题,帮助初学者或者需要回顾JDK 6特性的开发者深入理解和实践。通过这些资料,你可以学习如何使用JDK 6中的新功能,...
### GDAL库学习笔记知识点概览 #### 一、GDAL库简介 - **定义与功能**:GDAL(Geospatial Data Abstraction Library)是一个用于处理栅格地理空间数据格式的开源库,由开放源代码地理空间基金会(Open Source ...
Java JDK 6学习笔记主要涵盖了Java开发工具集(Java Development Kit)的第六个主要版本,这是一个重要的里程碑,因为它为开发者提供了许多新特性和改进。在这个版本中,Java平台的稳定性和性能得到了显著提升,同时...
标题"rubylearningdotorg:Ruby学习课程"表明这是一个关于学习Ruby编程语言的资源,可能包括一系列的教程、笔记或实践活动,适合初学者和有一定基础的开发者。"肯·麦卡登"可能是课程的创建者或主要贡献者,他可能是...
GDAL不仅提供了一个统一的数据模型来处理多种格式的栅格数据,还附带了一系列命令行工具,用于数据转换和处理。 GDAL的核心功能在于其强大的数据格式支持,能够读取和写入众多的栅格数据格式,包括但不限于JPG、GIF...
1. **安装Ruby**:确保已安装Ruby,并通过在终端中运行`ruby -v`检查版本,应显示“ruby 1.8.7”或更高版本。对于Windows用户,可以从RubyInstaller.org获取Ruby。 2. **安装Android SDK**:需要安装Android SDK,...
这篇"JSON学习笔记"可能涵盖了以下几个关键知识点: 1. JSON的基本结构:JSON数据由键值对(key-value pairs)组成,键和值之间用冒号隔开,键值对之间用逗号分隔。键必须是字符串,而值可以是字符串、数字、布尔值...
该库由开源地理空间基金会(OSGeo)提供,采用X/MIT开源许可证,支持多种编程语言,如C/C++、Python、Ruby、VB、Java、C#等。GDAL被广泛应用于地理信息系统(GIS)和遥感(RS)领域。 GDAL安装: 1. GDAL的安装过程...