Simple setter function or set with a property? - oop

Just curious to know what difference does it make if one uses a setter function or a property to set a value? Which of the above two should be preferred?
column.setWidth(10);
column.width = 10;

Well, that largely depends on what programming language you are using, or, in other words, whether it supports the concept of properties or not. However, lets look at the problem from a general perspective.
The very basic point of view is properties are just plain syntactic sugar, making reading and writing values to some assumed backing field easier and, which is the important point, defining a clear contract for your code's user. Assumed because there needs not be any backing field at all or they can be many.
The high-level semantic difference between a setter function and a native property setter can be thought as follows:
A setter function is primarily still a function, hence the reader assumes it executes certain action using its arguments; being actually a setter is then just a convention.
A native property setter is primarily a way to write a value into some assumed backing storage / into the backing object; there's no implied notion of executing an action even though the hidden implementation details of the setter may work like that.
Many practicle ramifications of using property accessors (getters and setter) were discussed in this question and its answers.

Prefer properties. Actually it depends on your language. If you develop Python that all attributes are public in Python.

Related

Kotlin automatically generates Getters and Setters, but WHY?

I'm new to learning Kotlin, and have just covered the fact that Getters and Setters for every object property are automatically generated behind the scenes, like Lombok is built directly into the language (great as far as I'm concerned!), but now I'm left with the question of why does it even bother?
I know you can override the defaults to change how they act, but why is this not just that case of them being created when you need to do something more complex that just getting or setting the value, but just accessing the property normally otherwise?
Having used Java a lot previously, I understand there are arguments for and against the use of Getters and Setters. Many say they're actually pointless and a bad approach to OOP, others would say they're best practice and should be used everywhere. The way many modern frameworks and libraries are written makes them necessary in lots of cases. This argument spans many different languages, but this question isn't really about the theoretical reasons for them in OOP as a whole, I'm looking for insight specifically into why they're used in Kotlin by default, when to my (perhaps naive) eyes it looks like they needn't be.
What would be the practical difference if Kotlin didn't generate standard Getters and Setters and dot notation simply accessed the property directly? Syntactically, as far as I can see, it produces the same result, just with extra steps.
What would be the practical difference if Kotlin didn't generate standard Getters and Setters and dot notation simply accessed the property directly?
So what you are suggesting is, for properties without custom getters/setters,
// Accessing x would access the field backing the property directly
// no getter or setter
var x: Int = 1
And for properties with custom getters/setters,
// both a field and a setter is generated for y
var y: Int = 1
set(newValue) {
field = newValue.also { println("y is being set!") }
}
// only a getter is generated for z, no field
val z get() = 1
The appropriated getter or setter or both will be generated depending on which ones you wrote.
Well, this would be problematic in a few ways. Here's what I could think of.
Firstly, all of this "when (not) to generate a getter/setter" logic is going to make the compiler more complicated. Why do that, when you can just simply generate a getter and setter, unconditionally, for every property?
Secondly, for Java code interacting with the Kotlin code, they would only have a field to work with, in the case of x, and public fields in Java doesn't look idiomatic at all... Let's say at some point you add a getter to x so that it's computed from something else, rather than backed by a field, then all the Java code would break, because there is no longer a field. I'm not sure whether this is also true on Kotlin/JS.
Thirdly, accessing the values of properties through reflection would be more annoying. You would need to check if it has a getter. If it does, call it. Otherwise, access the backing field instead. They could provide you with a helper property on KProperty that does on this for you, but still, that's a lot more complicated than simply calling the getter and be done with it.
Do note that just for JVM, there is the annotation #JvmField that you can use to make a property not have getters and setters, as far as the JVM is concerned. Kotlin's reflection API will still find a getter and setter though.
The two main arguments against getters and setters:
Verbose. But they aren't verbose in Kotlin.
Performance overhead. But it's not a concern with modern JVM's.
It's much safer for future-proofing to use getters and setters from the original design of a class, even if they are just passing through reads and writes to a field. It leaves open the possibility of adding side effects if you need to later. Forcing the use of properties prevents the possibility of you designing yourself into a corner.
Also, a language is easier to read and write when there are fewer ways of doing the same task. You never have to remember if the property you want to access on a class uses a getter function syntax versus standard property syntax.

setting/getting object's property value directly or by method?

This is more general question to any OOP, please before answer consider readability and efficiency.
Here is example in Javascript:
function fnc () {
this.var = "abc";
this.setVar = function (val) {
this.var = val;
}
this.getVar = function () {
return this.var;
}
}
Now, i can set value of var via method:
fnc.setvar("abc");
or
fnc.var = "abc";
I can also get it directly:
console.log(fnc.var)
or via get method:
console.log(fnc.getVar())
Here comes the question:
If the result is the same which option is better? what are the pros and cons for direct or method way?
This highly depends on the features and patterns used in a given language.
Behaviour driven languages
In Java or C++ classes are defined by their behaviour, read "methods". The interfaces and the whole inheritance are based on methods. Fields are 2nd class citizens. Therefore you use methods to get and set attributes. This is the only way of overriding the access and ensuring the integration is correct after you change something later on. Having all fields hidden behind methods also enables you finer grained control (for example getter without a corresponding setter, or a setter that does a calculation instead of simply setting an attribute), but you need a lot of boilerplate, so you write lots of code that does not really add to your business logic and makes the code harder to read from within the class. What makes the code harder to read, however, makes it easier to understand from the client-side through interfaces, as they fully define a class. This concept of methods over attributes usually comes along with visibility settings for methods and attributes. This way you define what is meant for outside world and what is meant for this class or package only. Attributes are almost always private (read "for this class only").
Property driven languages
In languages like JavaScript or Python classes/objects are defined by their fields, read "attributes". Even methods are nothing more than attributes and so both methods and attributes can be overriden (or hidden), switched at runtime etc. Given that you gain nothing but false security using getters and setters, and given that every function call less means better performance and shorter stacktrace, using fields directly is the preferred usage in scripting languages. Regarding readability: the code itself is much easier to read and to understand, but interfaces as known from behaviour based languages don't exist here except in form of documentation (if the code author writes one). Visibility of methods and attributes is usually always public, but some languages offer special annotations or naming schemas to show which methods or fields are meant to be private. There is no strong or no enforcement at all though.
BTW-JFYI: Python has a special solution for the extendability of fields: properties. This is a special thing which enables you using getter and setter with proper logic inside the class but present the field as plain attribute to the outside world. See Python #property versus getters and setters for further reading.
Don't consider the immediate result only. Most software is going to be modified at some point. Considering that, you are more flexible when using getter and setter methods as opposed to direct attribute access.
However the best option - if applicable - is to not use setters at all but create immutable objects.

OOP: Should setters be private?

When writing getter/setters in classes, should the setters be private methods?
It might seem a bit redundant to have to write another method to set a variable but it seems like that might allow for a more maintainable code structure.
Setter is a method that is suppose to allow modifying internal state of an object without exposing that object directly. We can later include validation or other logic inside setter.
If your setter is private, you are missing the point. It's like having a door in your house that is always closed and doesn't even allow opening. Also inside the class you can simply access the field directly, why would you use a setter there?
Of course the real question is: should we have setters at all? The typical class these days holds a bunch of fields, auto-generated getters/setters and no logic. This is hardly a class. It's just a structure with awkward way of accessing elements. But that's not what you are asking for.
In General, I don't recommend "private" access for any member, maybe "protected". Usually, you or other programmer may require it in a descendant class.
Long Boring Descriptive Answer
Now, for accessors ("getters & setters"), its also depends on the syntax and implementation of properties on the programming language.
For Example, C++, or Java, I consider not have "real properties", and accesors, maybe required to have the same scope as the properties. (Unless using a template for properties).
C# & Delphi (Lazarus) have properties implemented, but, I don't like the way C# declare the accesors.
There are cases, where you may want a property not to be public, maybe "protected" or "package protected", and its accesors, the same access than the property.
I just work in some code in Object Pascal. Most properties where "public", and its accesors "protected", but, want to migrate that code to c++ or Java, so, I make the accesors "public", as well.
Quick Short Answer
Same access as the property, but, depends on the syntax of properties.
They should be public, if the intent is to allow them to be manipulated from an external object. That is the point of POJO implementation. (http://en.wikipedia.org/wiki/Plain_Old_Java_Object)
If you're looking to implement some other pattern, perhaps looking at the docs on Java Access Modifiers should be your first stop (http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
However there might be some cases where you want to restrict access to your data just to instances of the same class, but you still want to retain some control over the access to the data for whatever reason (bookkeeping, locking etc.) - in that case having private (or protected) setters/getters makes sense (from both code reuse and safety POV). However, you can't rely on the compiler to catch you doing something wrong then.

In what cases should public fields be used instead of properties? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Public Data members vs Getters, Setters
In what cases should public fields be used, instead of properties or getter and setter methods (where there is no support for properties)? Where exactly is their use recommended, and why, or, if it is not, why are they still allowed as a language feature? After all, they break the Object-Oriented principle of encapsulation where getters and setters are allowed and encouraged.
If you have a constant that needs to be public, you might as well make it a public field instead of creating a getter property for it.
Apart from that, I don't see a need, as far as good OOP principles are concerned.
They are there and allowed because sometimes you need the flexibility.
That's hard to tell, but in my opinion public fields are only valid when using structs.
struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
};
But different people have different thoughts about:
http://kristofverbiest.blogspot.com/2007/02/public-fields-and-properties-are-not.html
http://blogs.msdn.com/b/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx
http://www.markhneedham.com/blog/2009/02/04/c-public-fields-vs-automatic-properties/
If your compiler does not optimize getter and setter invocations, the access to your properties might be more expensive than reading and writing fields (call stack). That might be relevant if you perform many, many invocations.
But, to be honest, I know no language where this is true. At least in both .NET and Java this is optimized well.
From a design point of view I know no case where using fields is recommended...
Cheers
Matthias
Let's first look at the question why we need accessors (getters/setters)? You need them to be able to override the behaviour when assigning a new value/reading a value. You might want to add caching or return a calculated value instead of a property.
Your question can now be formed as do I always want this behaviour? I can think of cases where this is not useful at all: structures (what were structs in C). Passing a parameter object or a class wrapping multiple values to be inserted into a Collection are cases where one actually does not need accessors: The object is merely a container for variables.
There is one single reason(*) why to use get instead of public field: lazy evaluation. I.e. the value you want may be stored in a database, or may be long to compute, and don't want your program to initialize it at startup, but only when needed.
There is one single reason(*) why to use set instead of public field: other fields modifications. I.e. you change the value of other fields when you the value of the target field changes.
Forcing to use get and set on every field is in contradiction with the YAGNI principle.
If you want to expose the value of a field from an object, then expose it! It is completely pointless to create an object with four independent fields and mandating that all of them uses get/set or properties access.
*: Other reasons such as possible data type change are pointless. In fact, wherever you use a = o.get_value() instead of a = o.value, if you change the type returned by get_value() you have to change at every use, just as if you would have changed the type of value.
The main reason is nothing to do with OOP encapsulation (though people often say it is), and everything to do with versioning.
Indeed from the OOP position one could argue that fields are better than "blind" properties, as a lack of encapsulation is clearer than something that pretends to encapsulation and then blows it away. If encapsulation is important, then it should be good to see when it isn't there.
A property called Foo will not be treated the same from the outside as a public field called Foo. In some languages this is explicit (the language doesn't directly support properties, so you've got a getFoo and a setFoo) and in some it is implicit (C# and VB.NET directly support properties, but they are not binary-compatible with fields and code compiled to use a field will break if it's changed to a property, and vice-versa).
If your Foo just does a "blind" set and write of an underlying field, then there is currently no encapsulation advantage to this over exposing the field.
However, if there is a later requirement to take advantage of encapsulation to prevent invalid values (you should always prevent invalid values, but maybe you didn't realise some where invalid when you first wrote the class, or maybe "valid" has changed with a scope change), to wrap memoised evaluation, to trigger other changes in the object, to trigger an on-change event, to prevent expensive needless equivalent sets, and so on, then you can't make that change without breaking running code.
If the class is internal to the component in question, this isn't a concern, and I'd say use fields if fields read sensibly under the general YAGNI principle. However, YAGNI doesn't play quite so well across component boundaries (if I did need my component to work today, I certainly am probably going to need that it works tomorrow after you've changed your component that mine depends on), so it can make sense to pre-emptively use properties.

Can I say a Constructor is a Method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I wonder if can I say that a constructor is a special case of a method?
You can say anything. Whether anyone will disagree with you depends on the context. Some language communities and standards define things that way.
More elaborately, it depends on what you mean by a 'method.' In C++, for example, one way to analyze the creation process is to say that it consists of a call to an operator new (perhaps just placement) followed by a call to a constructor method. From an implementation standpoint, a constructor looks, walks, and quacks like a method. In some compilers, you can even invoke one explicitly.
From a more theoretical viewpoint, someone might claim that constructors are some distinctive species. However, there is no single, true, privileged conceptual model of methods, constructors, or purple unicorns.
Gosh this is all subjective.
You could say so, just as you can say that a human is a special case of animal, however in most contexts mentioning animals implies non-human animals and mentioning methods implies non-constructor methods.
Technically, a constructor usually is a method. Whether it really is or is not depends largely on the particular environment. For example, in .NET constructors are methods called actually after an object is created. However, it's also possible to create an object without having a constructor called right after.
Update: Regarding .NET, or the Common Language Infrastructure to be more precise, ECMA 335, section 8.9.6.6 Constructors states:
New values of an object type are created via constructors. Constructors shall be instance methods, defined via a special form of method contract, which defines the method contract as a constructor for a particular object type.
I think a constructor is too special to be called a method
It doesn't return anything
It modifies the object before the object is initialized
It cannot call itself (imagine that)
blah blah blah
There might be difference between languages, but I don't think I'm going as far as calling a constructor "special method".
In languages that have constructors, you can usually think of a constructor as a special case of a factory method. (Note: I don't mean the GoF Factory Method Software Design Pattern, I'm just talking about any class method that creates new instances.) Usually, this "special casing" generally takes the form of annoying restrictions (e.g. in Java, you can only call the parent constructor at the beginning of the constructor), which is why even in languages that do have constructors, you often end up using or writing factory methods anyway.
So, if constructors are basically factory methods with restrictions, there is really no need to have them both, and thus many languages simply get rid of constructors. Examples include Objective-C, Ruby, Smalltalk, Self, Newspeak, ECMAScript/JavaScript, Io, Ioke, Seph and many others.
In Ruby, the closest thing to a constructor is the method Class#allocate, which simply allocates an empty object and sets that object's class pointer. Nothing more. Since such an empty object is obviously unusable, it needs to initialized. Per convention, this initialization is performed by #initialize. As a convenience, because it is cumbersome to always have to remember to both allocate and initialize (as any Objective-C developer can probably attest), there is a helper method called Class#new, which looks something like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
return obj
end
end
This allows you to replace this:
foo = Foo.allocate
foo.initialize(bar)
With this:
foo = Foo.new(bar)
It is important to note that there is nothing special about any of these methods. Well, with one exception: Class#allocate obviously has to be able to set the class pointer and to allocate memory, which is something that is not possible in Ruby. So, this method has to somehow come from outside the system, which e.g. in MRI means that it is written in C, not Ruby. But that only concerns the implementation. There are no special dispatch rules, no special override rules. It's just a method like any other that can e.g. call super whereever, whenever and how often it wants and can return what it wants.
"Special" is the magic word here. There's absolutely nothing wrong with calling a constructor a special method, but what "special" implies can vary depending on the language.
In most cases, "special" means they can't return values or be called as a method without creating a new object. But there are always exceptions: a prime example is JavaScript, where a constructor is no different from a normal function, it can return its own values and it can be called either as a constructor or as a simple function.
At least in vb.net, constructors can have a non-standard control flow. If the first statement of a constructor is a call to New (of either the same type or a base type), the sequence of events will be: (1) perform the call; (2) initialize all the fields associated with the type; (3) finish handling the rest of the constructor. No normal method has that sort of control flow. This control flow makes it possible to do things like pass constructor parameters to field initializers of a derived type, if the base type is written to allow such.
#Tom Brito, personally I would agree with you that a constructor is a special case of method.
Also, see below:
A constructor in a class is a special type of subroutine called at the creation of an object.
... A constructor resembles an instance method, but it differs from a method in that it never has an explicit return-type...
Source:
Wikipedia
Also, you may read my comments on others' comment (woot4moo, phunehehe).