|
c*****m 发帖数: 1160 | 2
我是这个意思,根据单一功能、明确名字的规范,getter和setter应该只处理一个变量
;如果需要增加逻辑在里面,就应该是另一个函数了。
如果我在debug过程中看到一个setter里面顺便修改了另外的值,那么我就需要跟踪所
有的getter/setter来确定是否还有类似的动作,很揪心的。
我所觉得getter/setter有用的地方就是做只读变量或者只写变量的时候。 |
|
L*********s 发帖数: 3063 | 3 如果setter只是用来给属性赋值,那么确实没必要弄setter和getter,
但是随着业务逻辑的发展,或者设计的变动,
往往我们要求在给属性赋值的同时还要干一些其他事情。
也许你辛辛苦苦写下了一百多行给某个public属性赋值的语句后,
忽然你的manager或客户要求你在给那个属性赋值的同时一定要synchronized()什么东
西,
这时你就必须在每个赋值的地方进行改动。
如果你当初只用setter,那么只要修改一下setter就可以了。
同时为了让你的合作者们使用这个类时也只用setter,就得把属性设为private,
然后就读数值就得用getter.
也许哪天你的客户要求关于这个属性的transaction都跟某个新建的网页同步,
或者要求跟某个新建的数据库同步,或者要求这个属性的值一旦变化便立即触发某个新
定义的事件。
这时你就必须添加无数的代码。
如果你当初用了getter和setter,事情就超级简单了, 基本不用改代码! 只需用鼠标设置
javabean, 然后所有的脏活累活container都自动帮你解决. |
|
m*****g 发帖数: 54 | 4 a better version
class Planet:
def getter(self):
return self.__diameter
def setter(self, value):
self.__diameter = value
diameter = property(getter, setter)
instance = Planet()
print(Planet.diameter) # call getter
instance.diameter = 1000 # cal setter |
|
d**********x 发帖数: 4083 | 5 Even for pure storage classes which never change it is still important to
use setter/getters for a more practical reason: debug.
if you simple use direct access, no logs can be printed and no break point
can be inserted for all of the acesses to the value -- in small projects you
can simple refactor to setter/getters, but in large project there will be
no practical way to do so.
Now
affected. |
|
c*****m 发帖数: 1160 | 6 zhaoce073 说可以在getter/setter里加入更多的process
goodbug说可以顺便管理其他变量
devilphoenix说方便debug
前两个理由是否违反“单一功能”的要求?比如md5计算,应该是另一个函数,而不是
getter了。如果顺便管理另一个函数,那么function名字就不应该是SetThisVariable(
),而应该是SetThisVariableAndAnotherVariable().
我觉得不超过 1/10的变量需要有这方面的需求;对于其他 9/10的变量就是verbose,
看起来不爽,当然也没有坏处。
you |
|
p**o 发帖数: 3409 | 7 在灵活一些的动态语言比如python里,推荐的做法是直接修改类成员属性,如果哪天需
求复杂化了,再通过@property修饰一层实现更复杂的封装,但是客户代码完全不必改
动,没有“必须在每个赋值的地方进行改动”这个问题。在Java里常写getters/
setters大概是Java语言本身的限制。我不太清楚其他的静态编译语言的最佳实践里是
否包含getters/setters。 |
|
l******e 发帖数: 1550 | 8 这帮小孩子(四岁到六岁),每次上课的时候都要过了好久才能安静下来,四个男生不
是追就是打。唯一上得顺利的一次课,是我一开始就让猜谜语。
“哪一种动物有两个梦想。 一是可以拍一张彩色照片,二是可以去除黑眼圈?"
小朋友一下子安静下来,说了好多小动物的名字。 后来还是那个最淘气的华裔小朋友
才对了。
其实上课的内容很容易,但是让他们坐下来,并且坐得住实在太难了。
大家有啥好的attention getter给奉献一下下吧。 |
|
|
l******e 发帖数: 1550 | 9 Seriously,你有没有什么好的attention getter,以前做presentation用过的也行。
当老师当成我这样子,真是悲催啊。 |
|
c*****m 发帖数: 1160 | 10
with
that
这两年经常看到一些class里面有这样的getter和setter,有什么好处?直接把这个变
量public出来不就可以了么?
相信是gof里面的一个设计模式,但是我看过几次都没有理解。 |
|
c*****m 发帖数: 1160 | 11
联结里的那个例子,用getter/setter完全没有好处啊。直接public出来不就行了? |
|
g*****g 发帖数: 34805 | 12 getter setter is a java bean spec. Many frameworks rely on it to do
reflection. You have to assume the method name or you can't find it. Thus in
java, you have to call it that way. Nothing wrong to introduce extra logic
in setter to keep the object state consistent. setter is meant to change a
state of one variable. What if another variable is dependent on this
variable? |
|
d****i 发帖数: 4809 | 13 学过C++的人应该十分明白这个道理,这个正是C++要求封装的原因。Java的setter和
getter和C++的数据封装原理是一样的。 |
|
d*****b 发帖数: 9 | 14 "也许你辛辛苦苦写下了一百多行给某个public属性赋值的语句后,
忽然你的manager或客户要求你在给那个属性赋值的同时一定要synchronized()什么东
西,这时你就必须在每个赋值的地方进行改动。"
这个概率对于大多数人来说也太低了吧...要是因此给每一个public属性都加上setter
和getter,是否感觉有点儿累.
该不该加,我认为还是应该具体问题具体分析. |
|
g*****g 发帖数: 34805 | 15 我老看看板上的帖子还算有依据。总比你靠谱多了,难道你还能统计了大多数学Java的?
发信人: moneybull (moneybull), 信区: Programming
标 题: Re: 为什么java要用setter和getter
发信站: BBS 未名空间站 (Tue Dec 18 09:56:11 2012, 美东)
大部分学Java的都是知其然而不知其所以然
学C++的,如果不知其所以然,很难混下去... |
|
y*******g 发帖数: 6599 | 16 java 不用getter/setter直接access 的话是静态绑定的。不太方便 |
|
l**********n 发帖数: 8443 | 17 http://www.javaworld.com/article/2073723/core-java/why-getter-a
They provide external access to implementation details. They violate the
encapsulation principle.
These procedural programmers read somewhere that fields should be private,
however, so they make the fields private and supply public accessor methods. |
|
d******e 发帖数: 2265 | 18 不是evil是stupid.
这是当年m$当道,软件升级会遇到的困难。
现在早就不需要了。特别是函数 1st citizen 加上immuatable class后,更佳不需要
考虑getter/setter
methods. |
|
i*****f 发帖数: 578 | 19 class Planet:
@property
def diameter(self):
# a getter
return self.__diameter
@diameter.setter
def diameter(self, diameter):
# a setter
if diameter<0:
raise ValueError("impossible")
self.__diameter = diameter
def __init__(self, diameter):
self.diameter = diameter
mars = Planet(100)
print mars.diameter
mars.diameter = -10 # ValueError |
|
i*****f 发帖数: 578 | 20 Looks somewhat weired compared to other language setter/getter |
|
g*****g 发帖数: 34805 | 21 对一个简单独立纯setter/getter的property来说,跟public member
并没有什么不同。问题在于未来不可预期。对于一个外部类来说,不做
encapsulation将来存在重构的风险。举两个简单的例子。
1. 你有一个String。你某天发现这个String有时候有white space需要trim。
用setter/getter,没有问题,可以在setter里面trim了。所有外部调用
setter/getter的类都不需要改动。反之,当你直接用public member的时候,
你要吗在所有引用的地方trim,要吗重新回到setter/getter。无论哪种
做法你改变的都是N个类,而不是一个。如果这是公共API,有不受你控制的
第三方的源码调用这个类,你直接就破坏了接口。
2. 你有两个变量a 和b,刚开始独立,后来突然来个要求a必须是b的2倍。
有getter/setter,不是问题。没有,结果可以想见。
一些函数语言如Scala,可以做到成员和函数的外部调用在语法上没有区别,
未来重构不是问题,这是其可以把成员确省成public的原因。我不知道C#
现在... 阅读全帖 |
|
f*******7 发帖数: 2210 | 22 请认真读规则,这叫proportional么?我真的无语了,请多学习下再发言。
108 district delegates are to be allocated to presidential contenders based
on the primary results in each of the 36 congressional districts: each
congressional district is assigned 3 National Convention delegates. These
delegates are allocated to the presidential contenders as follows:
If a candidate receives a majority of the vote (more than 50%), that
candidate is allocated all 3 of the district's delegates. [General Rules for
All Conventions and Meet... 阅读全帖 |
|
f*******7 发帖数: 2210 | 23 请认真读规则,这叫proportional么?我真的无语了,请多学习下再发言。
108 district delegates are to be allocated to presidential contenders based
on the primary results in each of the 36 congressional districts: each
congressional district is assigned 3 National Convention delegates. These
delegates are allocated to the presidential contenders as follows:
If a candidate receives a majority of the vote (more than 50%), that
candidate is allocated all 3 of the district's delegates. [General Rules for
All Conventions and Meet... 阅读全帖 |
|
d****p 发帖数: 685 | 24 This doesn't solve the problem: the getter/setter can be called anywhere by
anybody in the following form:
a.getter(B())
The solution is however good in the sense that it creates syntax
inconvenience for accessing A's member variables from Non-B classes.
The argument of setter/getter has to be lvalue and the return of setter/
getter has to be injected to the consumer object. |
|
a***k 发帖数: 1038 | 25 【 以下文字转载自 paladin 讨论区 】
发信人: atack (小军号), 信区: paladin
标 题: 红死病 by 杰克.伦敦
发信站: BBS 未名空间站 (Sat Oct 11 07:40:15 2014, 美东)
I
The way led along upon what had once been the embankment of a railroad. But
no train had run upon it for many years. The forest on either side swelled
up the slopes of the embankment and crested across it in a green wave of
trees and bushes. The trail was as narrow as a man's body, and was no more
than a wild-animal runway.
Occasionally, a piece of rusty iron, showing through ... 阅读全帖 |
|
f*******e 发帖数: 8974 | 26 对自己的木耳很失望,不在前排当笑话了,悄悄得绕到后排来吧
器材:电脑ape,usb转同轴,团购DAC,团购耳放,HD600(650线)
group one:
1957 mullard Ecc82/12au7
小盾标记,long ribbed plate,square getter,made in britain
1960's telefunken Ecc82/12au7
标记蹭没了,long smooth plate,o getter,"diamond" on bottom
Telefunken label Ecc82/12au7 silver plate, siemens oem, late50's/early60's
shiny silver plate, dual support o getter
Tung-sol Black (smoky) glass 12au7, late50's
啥也看不见,因为是black glass,呵呵,不过好像是black long ribbed plate
这四个一组是因为我买的价钱加上运费都在4-50之间。唯一能明确听出区别的就是1957年的 |
|
a***k 发帖数: 1038 | 27 I
The way led along upon what had once been the embankment of a railroad. But
no train had run upon it for many years. The forest on either side swelled
up the slopes of the embankment and crested across it in a green wave of
trees and bushes. The trail was as narrow as a man's body, and was no more
than a wild-animal runway.
Occasionally, a piece of rusty iron, showing through the forest-mold,
advertised that the rail and the ties still remained. In one place, a ten-
inch tree, bursting through... 阅读全帖 |
|
s*y 发帖数: 472 | 28 比如说有一个getter for a Hashset.
用户call getSet(),拿到这个Hashset的reference,但是他直接可以往set里加减东西
请问如何防止别人通过setter进行这种操作?
另外相对这个set进行多线程操作,怎么用synchronized实现mutual exclusion?synch
ronized getter method理论上应该不管用吧?一旦pass给reference以后,getter的程
序就跑完了,mutual exclusion也消失了。
还请大虾指教
多谢! |
|
z*******3 发帖数: 13709 | 29 之前说过我对abstract class的看法,倒是引来不少非议
尤其是有些人居然举出了例子,好,我们就从这个例子开始
有人说在这种情况下要使用abstract class
比如一个animal,有walk和sing方法
那么代码就是
public abstract class Animal{
public void walk(){System.out.println("walk")};
public abstract void sing();
}
然后对于具体的实现类,比如Cat,有如下实现
public class Cat extends Animal{
public void sing(){
System.out.println("cat sing");
}
}
这样一个类,好处就是“便于扩展”等等
OK,那么我们就从这个例子出发,说说为什么在j2ee环境中,我们不这么做
然后说说会怎么做
首先,在j2ee的环境中,关于animal这种实体
我们会在各个层面建立entity
比如在db层面建立一个表,叫做animal,然后有一个cat记录
然后通过orm,建立起一个dto之类的玩... 阅读全帖 |
|
z*******3 发帖数: 13709 | 30 之前说过我对abstract class的看法,倒是引来不少非议
尤其是有些人居然举出了例子,好,我们就从这个例子开始
有人说在这种情况下要使用abstract class
比如一个animal,有walk和sing方法
那么代码就是
public abstract class Animal{
public void walk(){System.out.println("walk")};
public abstract void sing();
}
然后对于具体的实现类,比如Cat,有如下实现
public class Cat extends Animal{
public void sing(){
System.out.println("cat sing");
}
}
这样一个类,好处就是“便于扩展”等等
OK,那么我们就从这个例子出发,说说为什么在j2ee环境中,我们不这么做
然后说说会怎么做
首先,在j2ee的环境中,关于animal这种实体
我们会在各个层面建立entity
比如在db层面建立一个表,叫做animal,然后有一个cat记录
然后通过orm,建立起一个dto之类的玩... 阅读全帖 |
|
p*u 发帖数: 2454 | 31
anywhere by
setter/
you are right, but we can always solve this with another level of
indirection:
"
#define GETTER( a ) Intruder::get( *this, a )
#define SETTER( a, i ) Intruder::set( *this, a, i )
class A
{
private:
friend struct Intruder;
int _i;
};
struct Intruder
{
template
static int get( const T& ref, const A& a );
template
static void set( const T& ref, A& a, int i );
};
template
int Intruder::get( const T& ref, const A& a )... 阅读全帖 |
|
l*******z 发帖数: 4276 | 32 Each of the state's 10 congressional districts is allocated 3 delegates.
If a candidate receives a majority of the vote or only 1 candidate receives
20% of the vote, that candidate receives all 3 delegates.
If there are 2 candidates who receive at least 20% of the primary vote, then
the top vote getter will be allocated 2 delegates and the other candidate
will be allocated 1 delegate.
If no candidate receives at least 20% of the vote or more than 2 candidates
receive at least 20% of the vote, th... 阅读全帖 |
|
q*********u 发帖数: 280 | 33 这个是原来楼主的代码,大致对的,仔细看看他应该是在写方法2,没有final, 这个
写不写,的确区分层次了,另外他有专门一个synchronized block在getter里面,所以
我觉得他是在写2
但是有可能interviewer会看到这个getter又没有专门的工厂, 会不会然后联想方法三
了,这样需要final, 然后就跟楼主起了争执,
其实就面一个初级的sde, 唉,只能说是水涨船高了。
这个是goodbug的代码,再贴一下
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static getInstance() { return INSTANCE; }
}
我写的最后一道题的code,欢迎批评指正
public final class SpecialSingleton{
private Integer i;
private static Map |
|
d**********x 发帖数: 4083 | 34 1.
Piece is a general interface, which can be implemented as concrete types,
interface may include possible moves given the settings on board (arguable);
getter for name; getter for display configuration (arguable); color...
Board will store and manage positions of all Pieces. Sierialization may be
required since users could save and resume games. Board provides methods to
move, change, remove, add (for undo) pieces by name/reference/position/
enumeration.
Use patterns like builder pattern to ge... 阅读全帖 |
|
a****n 发帖数: 1887 | 35 这个不是语法的问题,是OOP概念上的问题, class 本身应该有高内聚/低耦合,
简单的例子, 比如Rectangle的面积, 一般create一个Rectangle的object,
1. setWidth, setHeight, 然后 double area = object.getArea()。
2. setWidth, setHeight, 然后 double area = object.getWidth() * object.
getHeight();
第二种方法内聚比第一种低很多. 一般在设计class 的时候更多的考虑他的behavior,
设计class 有个基本原则tell, don't ask. 也就是说告诉object去做什么, 而不是问
他detail的information.
所以一般来说一个type 同时有很多 getter/setter, 基本上不应该给他其他的
behavior, 而他仅仅充当一个 data 容器, 也就是struct, 反过来真正的class 一般
应该避免同时又setter/getter
而class可以有get, 而这个get 一般... 阅读全帖 |
|
P***0 发帖数: 368 | 36 1. Structure:
QUALIFICATIONS, EXPERIENCE, EDUCATION, ACHIEVEMENTS, (optional for Phd)
PUBLICATIONS.
2. Why "qualifications" first?
The only objective for your resume is to land you an interview. Your resume
will need to pass HR and then HM. "Qualifications" is exactly designed to
pass HR. Here is how.
3. How to write "Qualifications"
HR has almost NO knowledge about technical jargon, but the only thing s/he
knows is the job description. So for any resume submitted, the "
Qualifications" need... 阅读全帖 |
|
s********e 发帖数: 340 | 37 Question:
A J2SE 5.0 class ThirdPartyObject, that is not thread-safe, is to be used
in some new java code. Which of the following design decision can be made to
ensure that no race condition will occour?
A. Store instance of ThirdPartyObject in a ThreadLocal
B. Provide a static getter for a ThirdPartyObject instance
C. Ensure that an instance of ThirdPartyObject is private and can only be
accessed using a public getter method
D Make any instance of ThirdParyObject a local(method) variable and e... 阅读全帖 |
|
b*****y 发帖数: 196 | 38 感觉这一段描述很像站上一些人。
One of my co-workers is a successful “go-getter” who has an aggressive
problem-solving style. Another team member approaches problems more slowly
and quietly. My go-getter co-worker has been very vocal about how the other
person “irritates her” and says she cannot work with him. Could these
comments be considered discriminatory behaviour?
That is correct.
Your response was A. Yes, making comments about a co-worker’s approach to
problem solving is discrimination and harassment.
Yo... 阅读全帖 |
|
P*******e 发帖数: 39399 | 39 还是都贴的吧 这个是Dec.8的 所有可能有点出入
NFL ALL-STAR TOP-TEN VOTE-GETTERS
POS. NAME, TEAM VOTES
QB Peyton Manning, Denver 926432
QB Drew Brees, New Orleans 793685
RB Marshawn Lynch, Seattle 643363
RB Jamaal Charles, Kansas City 636575
WR Calvin Johnson, Detroit 634819
RB Adrian Peterson, Minnesota 596231
TE Jimmy Graham, New Orleans 534867
RB LeSean McCoy, Philadelphia 513961
WR A.J. Green, Cincinnati 504142
QB Russell Wilso... 阅读全帖 |
|
p***n 发帖数: 635 | 40 可以用来实现比较严密的封装,控制外界与类的FIELD的接触.
实际上,不管是在C++还是在JAVA(e.g.,Bean)里头,用getter/setter 函数
(accessor,mutator)来控制外界读写的方式一经很常用了,C#只不过是在语
言里直接把这个常用的模式正式吸纳而已.
譬如,如果你想让一个属性只读, 就只定义一个GET好了. 很方便. 而且如果
你想改变属性的名称, 只用在一个地方改就行了.(呵呵, 如果在JAVA里摊上
个getter/setter 离好几百行的时候, 够费眼的.) |
|
z*******3 发帖数: 13709 | 41 抛砖引玉
吃饱了看文茜世界财经周报,看得昏昏的想睡,睡觉前赶紧写,写完睡觉去了
这样,先不从dto说起了,说tiers
一个j2ee经典的tiers最早提出来的时候,是三层,所谓的三层说的是sever side三层
不包括client side和database
三层里面分别有一层专门跟以上两个东西打交道
一个是presentation tier,这个跟client side打交道
一个是persistent tier,这个专门跟database打交道
中间还剩下一个叫做business tier,这么三层,这都很熟悉了
那么当初提出这个构想的时候
是基于以下一个方式
client side是applet+browser
presentation tier是servlet+jsp,servlet是controller,jsp是viewer
model需要你自己去提取,去包装
business tier则是ejb,尤其是session bean,stateful和stateless
persistent tier也是ejb,是entity bean
database用jdbc连接
这五个... 阅读全帖 |
|
g*****g 发帖数: 34805 | 42 写个getter就完了,一个程序性能的问题在于瓶颈上,
等你确信这个getter是瓶颈的时候再来考虑优化不迟。 |
|
p*****u 发帖数: 711 | 43 如何保证这些getter只可以被B调用? 把这些getter设为B的私有成员函数,并且
declare为A的
friend可行么? |
|
p***r 发帖数: 1098 | 44 Int 和 float的数要convert成NSNumber, and then add to NSMutableArray
@synthesize用来告诉编译器generated getter/setter code
(最新的xcode里,@synthesize这一行可以不写了)
你直接这样写:
@interface MyClass: NSObject
@property (nonatomic, strong) NSMutableArray* operandStack;
@end
自动生成_operandStack的instance variable和self.operandStack的setter和getter |
|
p***r 发帖数: 1098 | 45 Int 和 float的数要convert成NSNumber, and then add to NSMutableArray
@synthesize用来告诉编译器generated getter/setter code
(最新的xcode里,@synthesize这一行可以不写了)
你直接这样写:
@interface MyClass: NSObject
@property (nonatomic, strong) NSMutableArray* operandStack;
@end
自动生成_operandStack的instance variable和self.operandStack的setter和getter |
|
b**********h 发帖数: 419 | 46 我公司里用这个。
有几个annotation很方便,加个@Data可以省去getter/setter/hash/equal
也可以单独挑出某个getter/setter来定制 |
|
o****p 发帖数: 25 | 47 We are lucky to have Tanja Getter in this meeting. She will give a talk on
interview process and contract negotiation.
Hope you will benefit from this.
Tanja Getter is the director of residency programs from CHS.
Community Health Systems, Inc. is one of the nation's leading operators of
general acute care hospitals. In 2014, the organization's size once again
increased significantly with the acquisition of HMA. The organization's
affiliates own, operate or lease 206 hospitals in 29 states with
a... 阅读全帖 |
|
|
s**********y 发帖数: 353 | 49 How about 0.01% people with 67% wealth paying all the taxes? Do you like that
kind of society? What's the fair share for the rich in such a case? 67%?
I don't know what should be the fair share for the rich, but I am thinking if the wealth gap between the rich
and the rest is getter wider, more people may suffer during recessions and a big chunk of capitals just lies in
the banks doing nothing.
fair |
|
d**z 发帖数: 3577 | 50
道理很简单,人家不看重面子,但看重里子。
不像老中很在乎发音准不准,但不在乎说傻话。
像有些国家用军人做外交官,后清用外文系。
在米国,三哥靠谋略和团结窃企,跟英语好坏无关。
米疣何尝不是如此,只有老中猥琐男还在为发音纠结。
英文发音不准,却不影响忽悠的积极,证明很自信。
洋人宁可用自信的三哥做经理,不用自卑奴性的老中。
西方文化喜欢“Go Getter”。认为他们可以成大事。 |
|