Getters and setters for all the private variables of a class? - class

Is it really necessary or a good practice in general to add getters and setters on all the private variables of a class?
I am not asking about the read-only variables. What I am really asking is the general case, where most of the time we just add getters and setters in case they'll be needed and don't really know whether they will be used or not.

There are different explanations by different people regarding the use of 'getters' and 'setters'. The purest OO people says, they are evil.
But actually there are situations where we have to go with them at least in non-direct way.
But I believe that, it is not a good practice to add them seamlessly as you suggest.

As private properties are the internal state of the defining class there is no need to write accessors.
The benefits are:
faster code execution (less function calls),
higher readability and maintainability (lower LOC),
accessibility to private properties only for the defining class.

It is not necessary to write getter or setter for all private variables.
It is just a good practice.
But without any public function you can not access the private data(variable) of the class.

Related

Why use accessors and mutators with simple classes?

For simple classes (and I mean really simple ones), why do we use accessor and mutator methods? Why do not we just make the data members public?
For example, the following class header (in C++) and could have been implemented with much less effort; as it is actually a couple of data members with accessors and mutators that do nothing but access/modify those data members.
I appreciate the advantage of the use of accessors and mutators in more complex classes.
template<class T>
class Node
{
private:
T item; // A data item
Node<T>* next; // Pointer to next node
public:
Node();
Node(const T& anItem);
Node(const T& anItem, Node<T>* nextNodePtr);
void setItem(const T& anItem);
void setNext(Node<T>* nextNodePtr);
T getItem() const;
Node<T>* getNext() const;
}; // end Node
This is a very fundamental, basic, and well-defined design principle in OOP - why to use accessors and mutators, in spite of whether a class is big or small.
I would still say, that implementation-usage of this principle still varies from language to language, but the core principle of Object Oriented Design - Encapsulation - remains always same and mandates, that you should always hide everything that is possible to hidden.
This is kind of duplicate of your question, and it refers to why getters and setters are in the play; however, I'll try to bring some other points as well.
Encapsulation, aspect of which is the topic in questions (mutators/accessors), is a fundamental and probably the most important principle of Object Oriented Programming.
First and foremost:
The main point of the Encapsulation is not(!) to restrict/block the access to the member variable, but rather to constrain the access policy and mandate the reasonable access, and therefore avoid any unintended interference, implicit misuse, or accidental accesses.
Think about it: if the user invokes .setUserName("MyUser") the one really intends to write the data into the member field, and that's explicitly clear! otherwise, it would mean that the client has (1) accidentally provided the "MyUser" data as an argument into setter method, and they (2) accidentally invoked the .setUserName method, which is way less likely to happen accidentally both together, then just publicly accessing that field, which takes only one move to do.
That being said, using the principle of encapsulation and advocating it as a core OOP feature, software developers, a lot of frameworks and libraries very often conventionally agree and make use of data classes, ordinary classes, business classes, service, or any other types, relying on the widespread Conventional Design and best practice of how to use member variables - using mutators to mutate and accessors to access the fields.
Many frameworks explicitly invoke setters and getters when they implement IoC or DI.
So, it's the best practice, conventionally agreed, non-smelling code style, and the most safe design of the class members, to use encapsulation and interact with them through mutators and accessors.

Swift: Constant's internal implementation

In swift, how is constants implemented?
I read this article, which says
In Swift, constants are generally implemented as (inlined) function calls.
I am not clear of this statement.
Does Swift use a special approach to make constants?
Could anyone explain?
Are you familiar with "getter" and "setter" methods from other languages, such as Java? If a variable is made public in a language like Java, it's exposed to other classes to access directly. In the future, if this variable has to be changed, there's no way to do so without changing all of the other classes dependent upon. With getter/setter methods, dummy implementations can be made that don't do anything besides read/write the value. In the case that a change needs to be made, the implementation of these methods can be changed without effecting the public API of the class.
Swift implements variables with "properties", which are like a backing private variable with public getter/setter methods that are automatically generated. In the future, you can replace a property with a computer property with a special getter/setter implementation, without effecting the public API of the class, just like before. The difference here is that you don't need to write all of the default getters/setters yourself.

What is the philosophy behind making instance variables public by default in Scala?

What is the philosophy behind making the instance variables public by default in Scala. Shouldn't making them private by default made developers make less mistakes and encourage composition?
First, you should know that when you write:
class Person( val name: String, val age: Int ) {
...
}
name and age aren't instance variables but accessors methods (getters), which are public by default.
If you write instead:
class Person( name: String, age: Int ) {
...
}
name and age are only instance variables, which are private as you can expect.
The philosophy of Scala is to prefer immutable instance variables, then having public accessors methods is no more a problem.
Private encourages monoliths. As soon as it's easier to put unrelated functionality into a class just because it needs to read some variables that happen to be private, classes start to grow.
It's just a bad default and one of the big reasons for classes with more than 1000 lines in Java.
Scala defaults to immutable, which removes a massive class of errors that people often use private to restrict (but not remove, as the class' own methods can still mutate the variables) in Java.
with immutables which are preferred in many places, public isn't so much of an problem
you can replace a public val with getters and setters without changing the client code, therefore you don't need the extra layer of getters and setters just in case you need it. (Actually you do get that layer but you don't notice it most of the time.)
the java anti pattern of private field + public setters and getters doesn't encapsulate much anyway
(An additional view supplementing the other answers:)
One major driver behind Java's encapsulation of fields was the uniform access policy, i.e. you didn't have to know or care whether something was implemented simply as a field, or calculated by a method on the fly. The big upside of this being that the maintainer of the class in question could switch between the two as required, without needing other classes to be modified.
In Java, this required that everything was accessed via a method, in order to provide the syntactic flexibility to calculate a value if needed.
In Scala, methods and fields can be accessed via equivalent syntax - so if you have a simple property now, there's no loss in encapsulation to expose it directly, since you can choose to expose it as a no-arg method later without your callers needing to know anything about the change.

#properties question on iPhone development

From what I've read, #properties and #synthesize are used to tell the compiler to to generate getters and setters for various properties of our class.
So I am confused when I see the source code of an Apple example, the GKTank, that uses only one class for the whole game (apart from the app delegate) and still most of the attributes of that class are defined in #property() and are synthesized, even if no other class will try to get/set them. What am I misunderstanding here?
Thanks
Using properties is generally good practice as the synthesized setters will do the right thing when it comes to memory management (retain, or simply assign, depending on how you've configured your property).
They are also a means of providing a clean separation between the public interface of your class and it's internal implementation.
This article offers some good advice on when and why to use properties and dot-notation.
It also allows you to use the dot syntax:
self.myProperty = something;
I don't know that particular example. However, it is considered good style to access members of the same class through accessors rather than referencing the members directly. By encapsulating the members as a property with getters and setters, the implementation details of the field may change while those details are abstracted by the getter/setter.
Furthermore, the declaration of properties on the class allows you to use the .-notation to access the properties so it might lead to more consistent code if you want to use that notation.

When the use of an extension method is a good practice? [duplicate]

This question already has answers here:
Closed 13 years ago.
Extension methods are really interesting for what they do, but I don't feel 100% confortable with the idea of creating a "class member" outside the class.
I prefer to avoid this practice as much as I can, but sometimes it looks better to use extension methods.
Which situations you think are good practices of usage for this feature?
I think that best place for extension methods is "helper" methods or "shortcuts" that make existing API easier and cleanier by providing default values to arguments of existing methods or hiding repeating chains of method calls.
Contrary to the common beliefs that you can "extend" classes for which you do not have access to the source code, you cannot. You have no access to private methods and objects, all you can do is to polish public API and bend it to your likings (not recommended).
They're great for interfaces (where you can add "composite" behaviour which only uses existing methods on the interface) - LINQ to Objects is the prime example of this.
They're also useful for creating fluent interfaces without impacting on the types that are being used. My favourite example is probably inappropriate for production code, but handy for unit tests:
DateTime birthday = 19.June(1976) + 8.Hours();
Basically anywhere that you don't want to or can't add behaviour to the type itself, but you want to make it easier to use the type, extension methods are worth considering. If you find yourself writing a bunch of static methods to do with a particular type, think about whether extension methods wouldn't make the calls to those methods look nicer.
When the class is not extensible and you don't have control over the source code. Or if it is extensible, but you prefere to be able to use the existing type instead of your own type. I would only do the latter if the extension doesn't change the character of the class, but merely supplies (IMO) missing functionality.
In my opinion, extension methods are useful to enhance the readability and thus maintainability of code. They seem to be be best on entities where either you have no access to the original class, or where the method breaks "Single Responsibility Principle" of the original class. An example of the latter we have here is DSLs. The DSL models are extended with extension methods are used to make T4 templating easier but no methods are added the model unless they are specifically related to the model.
The ideal use for them is when you have an interface that will be implemented in many places, so you don't want to put a huge burden on implementors, but you want the interface to be convenient to use from the caller's perspective as well.
So you put the "helpers" into a set of extension methods, leaving the interface itself nice and lean.
interface IZoomable
{
double ZoomLevel { get; set; }
}
public static void SetDefaultZoom(this IZoomable z)
{
z.ZoomLevel = 100;
}
Extension methods are a great way to add functionality to classes that you don't own (no source), are in the framework or that you don't want to inherit for whatever reason.
I like them, but you are right. They should be used judiciously.