Java set properties by string key [duplicate] - java

I have a class that has many settable/gettable attributes. I'd like to use reflection to set these attributes, but I have 2 questions about my implementation
Here is some stripped down code from my class
class Q {
public String question_1;
public String question_2;
public String question_3;
public String answer_1;
public String answer_2;
public String answer_3;
//etc. etc. Many String attributes
// … constructor and other stuff are omitted
// here is my method for "dynamically" setting each attribute
public void set_attribute(String a_raw_string, String my_field) {
try {
Class cls = Class.forName("com.xyz.models.Q");
Field fld = cls.getField(my_field);
fld.set(this, a_raw_string);
}
catch (Throwable e) {
System.err.println(e);
}
}
I then set various fields like this:
Q q = new Q();
q.set_attribute("abcde", "question_1");
q.set_attribute("defgh", "question_2");
// etc.
This works (i.e., the instance variables are set when I call set_attribute.
However, they only work when the instance variables are declared public. When they are declared private I get a NoSuchFieldException
QUESTION 1: Why do I get that error when the fields are private? My naive assumption is that since the set_attribute function is part of the class, it should have unfettered access to the instance variables.
QUESTION 2: I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way). Is there a more recommended approach?
The reason that I want to use reflection is because it's a pain in the ass to declare a ton of setter methods…so I'm wondering if someone has solved this annoyance in a better way.
Thanks!

I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way)
Yep. Reflection is fairly slow and should only be used as a last resort. If this is simply to avoid having so much redundant code, consider using automatic code generation. For pure data objects, I would strongly recommend using protocol buffers; it will generate the getters / setters (you only need to declare the fields). Plus it allows for easy communication of the data between C++, Java, and Python.
If you have a class that has a lot of fields but isn't a pure data object... well
You should consider whether all the fields should be mutable. (Do you really need setters?)
Whether the fields should even be visible. (Do you need any accessors at all?)
It is often a good idea to make fields "final", initialize them in the constructor(s), and provide no access or provide limited access through an implemented interface.

Using setter methods is the accepted way to set values for class member variables, reflection should definitely not be used for that as the code will be harder to understand and run much more slowly.
Most IDEs (eg Eclipse or NetBeans) include tools for automatically creating getter and setter methods for a class's fields.

When they are private you need to call fld.setAccessible(true);
Yes, why don't you just set the fields directly and avoid reflection? It doesn't look like you're doing anything dynamic. It's just that they are private -- why? Perhaps you mean to expose getters/setters and make the fields private? If so, then you should just invoke the public setters.

Related

Will it cause real issue if I use public field instead of getter/setter in Java? [duplicate]

This question already has answers here:
Are getters and setters poor design? Contradictory advice seen [duplicate]
(16 answers)
Closed 9 years ago.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior. In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public? Or just treat the class as a data structure?
I don't think so. It depends of the lifetime of your Object and its "exposure" (external modification).
If you're only using it as a data structure, exposing fields in secure way (final) sounds enough:
public class Person {
public final String firstName;
public final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
The term POJO was intended to distinguish classes from JavaBeans or any other convention. As such a POJO is by definition NOT required to do anything.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior.
This is called encapsulation and a good principle.
In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public?
That is an alternative approach. Some projects may forbid this approach while others may encourage it. Personally, I would favour this approach for classes which are encapsulated in some way already e.g. they are package local.
There is a view that some day in some way your class might have additional requirements and changing the "API" will be impossible. This goes against the YAGNI principle and very rarely proves to be the case and when it does has a much lower cost than adding lots of methods which don't do anything.
However, this is not always the case and if you don't use accessor methods you should consider what the impact will be on the project if you have to change it later. Using accessor methods every where means you never need to worry about this.
In summary, if you are pretty sure accessor methods are pointless and it won't be a problem to add them later, I would say you should use your judgement. However if you are not sure if it could be a problem in the future or you don't want to have to worry about it, use accessor methods.
The definition of POJO doesn't mandate getter/setter.
Experimentally, I am not using getter and setter in my current project.
The approach I am taking is this one:
unless necessary, don't provide getter/setter.
So far, I didn't find a case where I really needed get/set.
Some friend told me: "having get/set is helpful if in the future you need xyz"; my reply has been: when -in the future- I need to do so, I will provide the getter and setter; I don't want to anticipate anything.
The objection about incapsulation, that some may raise, is not really a valid one: providing getter and setter breaks incapsulation in the same manner, plus you have additional lines of (useless) code. Bugs may also lay in getter and setters.
This is an example of one of a non-trivial domain class:
public class SSHKey implements IsSerializable {
public Long id;
public Long userId;
public String type;
public String bits;
public String fingerprint;
public String comment;
#SuppressWarnings("unused")
private SSHKey() { // required by gwt-rpc
}
public SSHKey(String text) throws InvalidSSHKeyException {
Ensure.that(text != null, new InvalidSSHKeyException("Invalid Key"));
text = text.trim();
String[] parts = text.split(" ", 3);
Ensure.that(parts.length >= 2,
new InvalidSSHKeyException("Invalid Key"));
type = getType(parts);
Ensure.that(type.equals("ssh-rsa") || type.equals("ssh-dss"),
new InvalidSSHKeyException(
"Key must start with 'ssh-rsa' or 'ssh-dss'"));
bits = getBits(parts);
comment = getComment(parts);
}
private String getBits(String[] parts) {
return parts[1];
}
private String getComment(String[] parts) {
if (parts.length == 3)
return parts[2];
return type + " " + bits.substring(0, min(15, bits.length())) + "...";
}
private String getType(String[] parts) {
return parts[0];
}
}
The constructor takes the responsibility to validate and prepare the data to be manageable. Thus this logic doesn't need to be in a setter/getter.
If I was shown object with public members some years ago, I would probably not like them; maybe I am doing something wrong now, but I am experimenting and so far it is ok.
Also, you need to consider if your class is designed to be extended or not (so, foresee the future is part of the requirements), and if you want your object to be immutable. Those things you can only do with get/set.
If your object must be immutable, and you can avoid the empty constructor, you can just add 'final' to the member instances, btw.
Unfortunately I had to add IsSerializable (similar to java.io.Serializable) and an empty constructor since this is required by gwt. So, you could tell me then "you see? you need the getter an setter"; well not so sure.
There are some jdbc frameworks which promote the use of public fields btw, like http://iciql.com
This doesn't imply that this project is correct, but that some people are thinking about it.
I suppose that the need of getter/setter is mostly cultural.
The issue with making the members accessible is that you no longer control them from inside the class.
Let's say that you make Car.speed accessible. Now, everywhere in you program there can be some reference to it. Now, if you want to make sure that speed is never set a negative value (or to make the change synchronized because you need to make it thread safe), you have to either:
in all the points where speed is accessible, rewrite the program to add the control. And hope that everybody that changes the program in the future remembers to do so.
make the member private again, create the getter and setter methods, and rewrite the program to use them.
Better get used to write getter and setter from the beginning. Nowadays, most IDEs do it automatically for you, anyway.
The canonical answer to this is: You don't know whether your simple data structure will stay so simple in the future. It might evolve more than you expect now. It might be also possible, that anytime soon you want some "value changed" observer in that bean. With getter and setter methods you can do this very simply later without changing you existing codebase.
Another pro point for getter/setter is: If in Rome, do like the Romans... Which means in this case: Many generic frameworks expect getter/setter. If you don't want to rule all these usefulls frameworks out right from the start then do you and your colleagues a favour and simply implement standard getter/and setters.
Only if you expose a class in a library that's used beyond your control.
If you do release such a library, the Uniform Access Principle dictates that you should use getters and setters in order to be able to change the underlying implementation later without requiring clients to change their code. Java doesn't give you other mechanisms to do this.
If you use this class in your own system, there's no need: your IDE can easily encapsulate a public field and update all its usages in one safe step. In this case, brevity wins, and you lose nothing for the time where you need encapsulation.
I think it's a good idea to use getters and setters, unless you have very specific speed/memory/efficiency requirements or very simple objects.
A good example is a Point, where it is probably both nicer and more efficient to expose it's .x and .y variables.
That said, it will actually not be a big effort to change the visibility of a few member variables and introduce getters and setters even for a large codebase, if you suddenly require some logic in a setter.
JavaBeans require getters and setters. POJOs do not, anyway this has its benefits
The objetive of the getters and setters is to achieve encapsulation, which manages the internal state of object. This allows you to add or change business rules in your application after the application has been implemented only change the getter or setter code, example, if you have a text field that only allows for more than 3 characters can check before assigning it to an attribute and throw an exception, other reason for not doing this is if it's possible you'll want to change the implementation or change variable names or something like. This cannot be enforced if the field is publicly accessible and modifyable
anyway you can use your IDE to generate setters and getters.
If you are developing a simple application can be recommended, if your application is complex and must give maintenance is not recommend.
for the data-type objects, like POJO / PODS / JavaBean, at python you have only public members
you can set those and get those easily, without generating boilerplate setter and getter code(in java these boilerplate code usually(98%) exposes the inner private tag as noted in the question)
and at python in the case you would need to interact with a getter, then you just define extra code only for that purpose
clean and effective at the language level
at java they chose the IDE development instead of changing base java, see JavaBean e.g. how old that is and java 1.0.2 is how old...
JDK 1.0 (January 23, 1996)
The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999
so just live with it, use the setter getter because those are enforced by java surroundings
That's the true what #Peter Lawrey explains about encapsulation.
Only one note: it's more important, when you are working with complex objects (for example in the domain model in a ORM project), when you have attributes that aren't simple Java types. For example:
public class Father {
private List childs = new ArrayList();
public Father() {
// ...
}
private List getChilds() {
return this.childs;
}
public void setChilds(List newChilds) {
this.childs = newChilds;
}
}
public class Child {
private String name;
// ...
private String getName() {
return this.name;
}
public void setName(String newName) {
this.name = newName;
}
}
If you expose one attribute (like the childs attribute in the Father class) as a public, you won't be able to identify what part of your code are setting or changing one property of your exposed attribute (in the case, for example, adding new Child to a Father or even changing the name of a existing Child). In the example, only a Father object can retrieve the childs content and all the rest of the classes can change it, using its setter.

confusion on Get and set methods in java

I am learning get and set methods, I was just wondering if these can only be public, and do they need to be written for every instance variable in a class?
No.
Many internal variables should never be edited, such as states of computations.
If a field is private and has no getter/setter, it is that way for a reason and is acceptable as long as you don't need to access it outside the class.
If it is public, there's no point, and if protected, it's per-package or subclasses not necessarily in the same package.
Without a modifier, it's package-private.
If you want to make a field private and the getter/setter controlled you can use access levels as well.
On that note, if you want, you can perform validation inside a setter to ensure only acceptable values are set. Then, you can either silently reject, return false if the setter is a boolean, or throw an exception in severe circumstances.
I am assuming you are talking about encapsulation.
The whole point of these methods is for them to be public so that they can pass the value of your variable somewhere else in the application.
For achieving this with many variables, you may consider using 'listeners' (Observer Pattern Theory) which are basically custom interfaces that work with a custom class that contains many of these get and set methods.
More on encapsulation:
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
More on Observer Pattern Theory
http://www.youtube.com/watch?v=UEtyGP994X0
You need to have public getters and setters for your object to function as a JavaBean.
If you don't have a JavaBean requirement for your objects, then you don't need/have to provide public getters ( and especially setters ) in your classes.
Get and set methods in Java are just normal methods. They don't have to be public, but they wouldn't be very useful if they weren't public.
They don't need to be written for every instance variable in a class. If there are instance variables whose values depend on other values, then it may not make sense for them to have setters, e.g. a totalPrice instance variable that depends on a quantity instance variable.
If you want instance variables that shouldn't change, i.e they are immutable, then don't provide any set methods at all.
These methods provide your interface to the caller. They provide the operations on your object that you allow, so that the caller can't set your values to an invalid state, e.g. a count of -1 or a latitude of 91 degrees. This is "encapsulation", or hiding your object's implementation from your caller.
There is no java rule for making getters and setters public but these are made public for a reason.The point of getters and setters is that only they are meant to be used to access the private varialble, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing. It is good practice to make member variables private so they cannot be modified directly by programs using them.
A good article on the usage of getters and setters:
http://java.dzone.com/articles/getter-setter-use-or-not-use-0
Basically Yes, and No.
Yes, Get and Set methods (also called "getters" and "setters" or accessor methods) should almost always be public (although they can be otherwise -- there's a difference between can and should). The point of getters and setters is usually so other classes can access the encapsulated instance variables.
Exeptions:
You might make an accessor method to be protected if you only want child
classes or other classes in the same package to have access to those
methods.
You might use a private (or protected) setter if you want to
use special logic to set a variable (like concatenating it)
and you don't want other classes to be able to set the
variable.
No, they shouldn't always have accessors. Sometimes a variable should only have a getter (for instance, if that variable is final), and sometimes a variable shouldn't be accessed at all, and therefore you would not give it any accessor methods.
Get and set methods were designed originally for JavaBeans, classes stylized so IDEs and application programs can detect what properties the classes have and what event listeners they support. Through a limited version of reflection called introspection, tools can analyze the classes, and even if the programmer did not want to use is/get/set methods he could write BeanInfo classes that tell what methods be used instead.
Look at the Javadoc for java.beans.Introspector. and java.beans.BeanInfo. This provides ways to document additional information, including methods exposed to other tools and metadata about properties. For example, a TemperatureGauge class could expose the minimum and maximum temperature so a Swing program can set the limits of a slider without the programmer looking the information up.
Still, one should not expose more than one has to expose. You may need to limit access to getters and setters. You may need them for database tools, but you may not want ordinary programming to touch properties. This leads to ideas like OSGI or proxies where methods are limited to specific packages.
For example, one common tactic is to have getters only, to mark variables final, and build objects in the constructor. For example,
public final class Complex {
private final double re;
private final double im;
public Complex(double re, double I'm) {
this.re = re;
this.im = im;
}
public double getReal() {
return re;
}
// more getters, arithmetic, etc.
}
Note that I named the method slightly differently than the variable; that's okay.
On the other hand, there is a style of programming where one eschews getters and writes methods that tell the object what to do. Consider a Name class with givenName and surname instance variables. Then, add this method:
public void writeFormally(Appendable app) {
app.append(surname)
.append(", ")
.append(givenName);
}
You see this sometimes in Model-View-Presenter systems, like GWT and its HasText interface.
Unless you are writing code that deals with dependency injection systems or that use reflection to have your objects communicate with database, don't worry about the specifics of getters and setters. Just do what comes naturally and limit your objects' exposures. Also, every time you are tempted to write:
x.getA().getB().getC().setZ(42);
Rewrite the code to get rid of the chain of gets and sets. Look up the Law of Demeter in The Pragmatic Programmer.
Use protected if you want only child classes to access the field. However, if you want other classes to access the field, public is the way to go. Your decision should be based on the scope of access.

force private member access from same class only through method in java

I want to force future users of a class to access a private member also from future code written in that class only through an accessor method (even through junit or anything like that).
is there a way to do it in java? can someone show an example if possible?
You cannot force to do that, but you can create a method and document that enforcement in the javadoc.
private int myMember;
/**
* ATTENTION: use this method instead of setting the member directly.
*/
public void setMyMember(int value) {
this.myMember = value;
}
Also, there is an alternative solution which might work. Use ThreadLocal, like this:
private final ThreadLocal<String> member = new ThreadLocal<String>();
public void setMember(final String value) {
member.set(value);
}
The member field is final and cannot be changed. Therefore, clients will be forced to call the setter directly.
As long as the field is part of the class, anyone can access it directly. This can be a problem when we try to force all (co-)authors to go through the getters/setters because those method do some conversion, checking or bookkeeping stuff. Like incrementing internal counters.
A general solution, that comes to mind: it could be possible by using annotations. You'd have to create an annotation (and the annotation processor code) to ensure, that it is a compile time error if the field is used outside of it's getter/setter method:
#GetterSetterAccessOnly
private int value;
If you want to prevent reflection you can use a SecurityManager. If this is not an option you can get the call stack with Thread.currentThread().getStackTrace() and check the caller is from your class.
Two problems with this are; the performance won't be great. Anything you can do in the method you can do externally so the simplest work around is to copy its contents without the check. ;)
I suggest you document your reason for not allowing access this way.
Make use of inheritance to hide the field:
Do your class with all the fields and getter/setters that you need. (You may make it abstract)
Do a child class, that inherits from the previews one, and since the field isn't accessible, you force the use of the getter/setter pair.
As you are talking about the accessing in the same class, they have all the freedom to access the private member directly as well as through accessor method if that member has. So basically you cannot prevent them using the member directly in the same class.
I am afraid there is no standard way to do that. If a user has access to a class instance, although a private member is declared private, permissions can be changed at runtime and accessed anyway.
You need a classloader that enforces permissions. You can make an OSGi Bundle and enforce a control policy over the instance of your objects exported as services through interfaces. However this will tie you to an OSGi container to run your application.
Well, if they have access to your code, they can do anything they want. In the worst case, they remove your getters and setters and just put in a public field instead ;)
But of course you can motivate them to not access the variable directly with an according design:
you should check whether the others should rather implement subclasses instead of changing the class itself. Then private fields are, of course, only accessed via setters and getters.
you could move the data into a different class, and use your getters and setters to access the data in the other class. Doing this just for the sake of not having the data directly in your class is maybe a bit counter-intuitive, but since you probably have a good reason why they shouldn't access that very data, it indicates a different responsibility. So refactoring to meet the SRP is a good idea anyways.

Java Reflection to set attributes

I have a class that has many settable/gettable attributes. I'd like to use reflection to set these attributes, but I have 2 questions about my implementation
Here is some stripped down code from my class
class Q {
public String question_1;
public String question_2;
public String question_3;
public String answer_1;
public String answer_2;
public String answer_3;
//etc. etc. Many String attributes
// … constructor and other stuff are omitted
// here is my method for "dynamically" setting each attribute
public void set_attribute(String a_raw_string, String my_field) {
try {
Class cls = Class.forName("com.xyz.models.Q");
Field fld = cls.getField(my_field);
fld.set(this, a_raw_string);
}
catch (Throwable e) {
System.err.println(e);
}
}
I then set various fields like this:
Q q = new Q();
q.set_attribute("abcde", "question_1");
q.set_attribute("defgh", "question_2");
// etc.
This works (i.e., the instance variables are set when I call set_attribute.
However, they only work when the instance variables are declared public. When they are declared private I get a NoSuchFieldException
QUESTION 1: Why do I get that error when the fields are private? My naive assumption is that since the set_attribute function is part of the class, it should have unfettered access to the instance variables.
QUESTION 2: I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way). Is there a more recommended approach?
The reason that I want to use reflection is because it's a pain in the ass to declare a ton of setter methods…so I'm wondering if someone has solved this annoyance in a better way.
Thanks!
I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way)
Yep. Reflection is fairly slow and should only be used as a last resort. If this is simply to avoid having so much redundant code, consider using automatic code generation. For pure data objects, I would strongly recommend using protocol buffers; it will generate the getters / setters (you only need to declare the fields). Plus it allows for easy communication of the data between C++, Java, and Python.
If you have a class that has a lot of fields but isn't a pure data object... well
You should consider whether all the fields should be mutable. (Do you really need setters?)
Whether the fields should even be visible. (Do you need any accessors at all?)
It is often a good idea to make fields "final", initialize them in the constructor(s), and provide no access or provide limited access through an implemented interface.
Using setter methods is the accepted way to set values for class member variables, reflection should definitely not be used for that as the code will be harder to understand and run much more slowly.
Most IDEs (eg Eclipse or NetBeans) include tools for automatically creating getter and setter methods for a class's fields.
When they are private you need to call fld.setAccessible(true);
Yes, why don't you just set the fields directly and avoid reflection? It doesn't look like you're doing anything dynamic. It's just that they are private -- why? Perhaps you mean to expose getters/setters and make the fields private? If so, then you should just invoke the public setters.

When to use get/set Methods in java [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = "" instead а = classVariable.getName()
Here is example of class using set and get methods
public class ClassExampe {
String name;
String course;
public String getName ( )
{
return name;
}
public void setName (String studentName)
{
name = studentName;
}
public String getCourse ( )
{
return course;
}
public void setCourse (String studentCourse)
{
course = studentCourse;
}
}
Thanks
Using Getters / Setters vs using Fields
As a rule of thumb:
use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.
The simple rule is: never use direct access (except, of course, when referring to them from inside the class).
field access can't be proxied
you may want to have some event notification
you may want to guard against race conditions
expression languages support setters and getters
theoretically this breaks encapsulation. (If we are pedantic, setter and getter for all fields also breaks encapsulation though)
you may want to perform some extra logic inside the setter or getter, but that is rarely advisable, since consumers expect this to follow the convention - i.e. being a simple getter/setter.
you can specify only a setter or only a getter, thus achieving read-only, or write-only access.
Even if this does not happen that you need any of these, it is not unlikely. And if you start with field access, it will be harder to change.
In Java, using a getter and setter is usually considered best practice.
This is because if you ever need to change your code to do something else when a property is accessed or modified, you can just change it in the existing getter or setter.
I tend to think it causes a bit of clutter for simple objects, but if you have ever had to refactor a public property to a getter and setter to add additional functionality you will see that it can be a pain.
I suspect most will say to always use getters/setters to access private members. It's not necessary, but is considered a "best practice".
One advantage is that you can have more than just simple assignment and returning. Example:
public void setLevel(int lvl)
{
if (lvl<0)
{
this.level=1;
}
else
this.level = lvl;
}
public int getLevel()
{
if (this.someIndicator==4)
return this.level*7.1;
else
return level;
}
Getters and Setters allow you to change the implementation later (e.g. do something more complex), allow you to implement validation rules (e.g. setName throws an exception if the name is not more than 5 characters, whatever.)
You could also choose to add a getter but not a setter so that the variable is like 'read-only'.
That's the theory, however in many cases (e.g. Hibernate using setters) you cannot throw exceptions in setters so you can't do any validation. Normally the value will just be assigned/returned. In some companies I've worked at, it's been mandatory to write getters and setters for all attributes.
In that case, if you want to access an attribute from outside an object, and you want it to be readable/writable, I just use a public attribute. It's less code, and it means you can write things like obj.var += 5 which is easier to read than obj.setVar(obj.getVar() + 5).
If you mean: when to use public accessor methods instead of making the internal, private variable public my answer is "always" unless there is a severe performance reason.
If you mean, call your own get and set methods vs direct access to the vars w/in your class I still say call your own access methods. This way, any conversion, edits or rules you implement as part of get/set get invoked automatically by your own internal calls as well as external callers.
In pure OO languages (for example, Smalltalk) there is no concept of public - all internal vars are private and so you must use accessors. In less pure OO languages, you can make things public - however exposing the internals of your data structures and implementation is an exceptionally bad idea for stability and maintenance in the long run. Look up "tight coupling" for more on this.
Simply put, if you expose internal vars publicly, people can access them directly and if you ever change name or type everything down the line breaks. This is called side effects.
Its a matter of taste, but generally speaking you always should use get/set methods for all properties that are public. But for things like Value Objects (VOs) that you probably are not going to be bothered with for some time you can use public variables without getting too much criticism I think.
In general, you'd want to use setters and getters to give the opportunity to developers reusing your code by modifying it or extending it to add layers of processing and control when accessing and modifying your internal data. This wouldn't be possible in Java when using direct accesses.
Parenthesis: However, it's perfectly possible in other languages, for instance in Scala, when the line between properties and methods can become quite fine. And it's great, as then it doesn't become a coding-problem that gets in the way and it makes usage more transparent.
You can also often consider that in your class you can feel free to access your internal (private or protected) members directly, as you're supposed to know what you're doing, and you don't need to incur the overhead of yet another method call.
In practice, multiple people working on a class might not know what everyone's doing and those lines of integrity checking in your getters and setters might be useful in most cases, while the micro-optimization may not.
Moreover, there's only one way for you to access a variable directly, whereas you can define as many accessors as you want.
Encapsulate the private fields of a class and expose them with getter/setter classes the way you want to.

Categories

Resources