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的一些依赖库还没 ...
随机推荐
- js与jquery的区别
var html = $('<a target="_blank" href="' + adCompContent.clickURL + '">< ...
- [BZOJ2659][WC2012]算不出的算式(几何)
题目:http://www.lydsy.com:808/JudgeOnline/problem.php?id=2659 分析:很巧的想法,原式的值就是y=q/p x这条直线的下面和左边的点的个数.处理 ...
- 10.C#匿名函数的变量捕获(五章5.5)
首先感谢园友的指定,后续的文章一定会多码多想,出来的文章才有说服力.那今天接上篇我们来聊一聊匿名函数,对于匿名函数,我们知道使用delegate关键字,那我们来需要知道匿名函数在变量是的处理方式,先说 ...
- 自己在OC考试中的试题
Objective-C考试 [关闭] ※ 选择题(共40题,每题2分) 1. 以下说法正确的是________. 答案:(C) A.alloc,retain,release,dealloc都会使对 ...
- 将定时任务cron 解析成中文
在使用定时器 quartz 时,其中的cron 表达式,老板表示作为开发的你能看懂外,其他的非开发同事可能看不懂,要用一个他们能看懂的方式表达出来. 还好我们的项目要求的表达式不是特别的麻烦,所以就写 ...
- Java设计模式-代理模式(Proxy)
其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你 ...
- Struts2(二)---将页面表单中的数据提交给Action
问题:在struts2框架下,如何将表单数据传递给业务控制器Action. struts2中,表单想Action传递参数的方式有两种,并且这两种传参方式都是struts2默认实现的,他们分别是基本属性 ...
- jstl是自动就有的吗,不是的Unknown tag (c:if).
这个错误的原因就是没有导包 http://www.runoob.com/jsp/jsp-jstl.html 这个网站有方法
- poj 1061 扩展欧几里得解同余方程(求最小非负整数解)
题目可以转化成求关于t的同余方程的最小非负数解: x+m*t≡y+n*t (mod L) 该方程又可以转化成: k*L+(n-m)*t=x-y 利用扩展欧几里得可以解决这个问题: eg:对于方程ax+ ...
- POJ2965The Pilots Brothers' refrigerator(枚举+DFS)
The Pilots Brothers' refrigerator Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 22057 ...
- Adding Cache-Control headers to Static Files in ASP.NET Core