Encapsulation and Requiring Files
By encapsulating all the logic for an object, whether it’s a Dog or a User or an IceCreamShop, you are able to keep all of the logic and responsibilities of your object within its own scope. This lets you avoid having to worry about other objects using methods that they shouldn’t have access to.
Let’s take one last look at how your Dog methods took advantage of encapsulation. Let’s say you also had some methods for your pet parrot in there as well. Here’s what your code might have looked like:
def drink_water_from_bowl(dog)
# code for method
end def wants_to_play?(dog)
# code for method
end def fly_away(parrot)
# code for method
end def wag_tail(dog)
# code for method
end
And here’s what it would look like using OOP:
class Dog
def drink_water_from_bowl
# code for method
end def wants_to_play?
# code for method
end def wag_tail
# code for method
end
end class Parrot
def fly_away
# code for method
end
end
Not only is it much more apparent which actions are supposed to be performed by which objects, but now you won’t have to worry about accidentally calling fly_away on your dog. Who knows what could have happened there!
To build off the benefits of encapsulation, OOP helps keep your code readable. By keeping all of its instance methods tabbed in one level deep, it becomes much simpler to skim through your files.
Requiring Files
To take this organization to the next level, let’s address one last convention when it comes to classes. As a rule of thumb, each class should exist in its own file. This way, when you’re working on an application that has multiple classes, like ClothingStore and Customer, you know exactly where to look to make changes to your code.
These files should have the same name as the class they contain, with a few slight changes. Instead of naming your files in upper camel case (ClothingStore.rb), you should name them using snake case, like you would name a variable (clothing_store.rb).
But how do you get those files to interact with each other? Files don’t just magically know that there are other files that need to be included in your project. You’ll need to explicitly require those files.
Let’s say you’ve got three files: clothing_store.rb, customer.rb, and app.rb. To include the contents of the first two files in the last file, you can use require_relative. Let’s see that in action.
# app.rb require_relative "clothing_store.rb"
require_relative "customer.rb" # The rest of your code...
This code will look for the files you specify relative to the current file. That means that ifcustomer.rb was one directory level above the current directory, you’d writerequire_relative “../customer.rb".
Additionally, Ruby allows you to omit the .rb file extension by default. So your app.rb file can be written instead as:
# app.rb require_relative "clothing_store"
require_relative "customer" # The rest of your code...
- Nearly everything in Ruby is an object!
- You can define your own classes in addition to the standard Ruby classes like
Integerto create new types of objects. - To see which class a particular object is, you can use the
classmethod. - Objects have instance methods, or methods that can be called on a specific instance of a class, like
reversefor Strings. - To see which instance methods are available for a given object, you can use the
methodsmethod. - Getter and setter methods can be used to assign and retrieve the values of instance variables.
- Speaking of, instance variables are scoped to a particular class, and always start with a
@. attr_reader,attr_writer, andattr_accessorare handy shortcuts for getter and setter methods.- Ruby lets you write some things in more convenient ways, like leaving off parentheses. This issyntactic sugar
Encapsulation and Requiring Files的更多相关文章
- Adding Cache-Control headers to Static Files in ASP.NET Core
Thanks to the ASP.NET Core middleware pipeline, it is relatively simple to add additional HTTP heade ...
- Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define ...
Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define ... 这个错误是因为有两个相 ...
- The type javax.ws.rs.core.MediaType cannot be resolved. It is indirectly referenced from required .class files
看到了http://stackoverflow.com/questions/5547162/eclipse-error-indirectly-referenced-from-required-clas ...
- 未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\106f9ae8\cc0e1
在本地开发环境没问题,但是发布到服务器出现:未能写入输出文件"c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.Ne ...
- Find and delete duplicate files
作用:查找指定目录(一个或多个)及子目录下的所有重复文件,分组列出,并可手动选择或自动随机删除多余重复文件,每组重复文件仅保留一份.(支持文件名有空格,例如:"file name" ...
- Android Duplicate files copied in APK
今天调试 Android 应用遇到这么个问题: Duplicate files copied in APK META-INF/DEPENDENCIES File 1: httpmime-4.3.2.j ...
- Oracle客户端工具出现“Cannot access NLS data files or invalid environment specified”错误的解决办法
Oracle客户端工具出现"Cannot access NLS data files or invalid environment specified"错误的解决办法 方法一:参考 ...
- files list file for package 'xxx' is missing final newline
#!/usr/bin/python # 8th November, 2009 # update manager failed, giving me the error: # 'files list f ...
- Mac osx 安装PIL出现Some externally hosted files were ignored (use --allow-external PIL to allow).
出现这个问题Some externally hosted files were ignored (use --allow-external PIL to allow)的主要原因是PIL的一些依赖库还没 ...
随机推荐
- 重写TiledServiceLayer实现Arcgis访问Mapabc地图服务 (转载)
package com.baixin.main;/** * * @ClassName: MapAbcToArcGISTLayer * @Description: ArcGIS访问MapAb ...
- Javascript基础系列之(一)JavaScript语法
javascript的语法 1.区分大小写 javascript中,变量.函数.运算符都区分大小写. 2.弱类型变量 定义变量只用 "var"关键字 var age = 25; v ...
- 每天一个linux命令(30):cal 命令
cal命令可以用来显示公历(阳历)日历.公历是现在国际通用的历法,又称格列历,通称阳历.“阳历”又名“太阳历”,系以地球绕行太阳一周为一年,为西方各国所通用,故又名“西历”. 1.命令格式: cal ...
- 38.Android之ListView简单学习(一)
android中ListView用的很普遍,今天来学习下,本篇主要以本地数据加载到listview,后面会学习从网络获取数据添加到listview. 首先改下布局文件: <?xml versio ...
- 利用Spring中的HtmlUtils.htmlEscape(input)过滤html
fatherModule.setModuelName(HtmlUtils.htmlEscape(fatherModule.getModuelName())); log.info(HtmlUtils.h ...
- asp.net input怎么获取值
前台: <input type="hidden" name="content" value="content"> 后台: Req ...
- DLUTOJ 1142 高中的公式
传送门 Time Limit: 1 Sec Memory Limit: 128 MB Description 据说...高中学习了好多公式.所以...萌学长不知道该用什么公式来解决下面这个问题.对于 ...
- Android自动化测试框架对比
1.Monkeyrunner:优点:操作最为简单,可以录制测试脚本,可视化操作:缺点:主要生成坐标的自动化操作,移植性不强,功能最为局限:2.Rubotium:主要针对某一个APK进行自动化测试,AP ...
- POJ1258Agri-Net(prime基础)
Agri-Net Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 46811 Accepted: 19335 Descri ...
- POJ1088滑雪(dp+记忆化搜索)
滑雪 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 86411 Accepted: 32318 Description ...
- Adding Cache-Control headers to Static Files in ASP.NET Core