JavaScript: Is it worth making variables private and defining getters/setters? - javascript

I'd like to start by saying that I understand that JavaScript is a Classless language. My background is in Java, C++, and Objective-C which are all classic OOP languages that support Classes.
I'm expanding into Web Development and have been experimenting with JavaScript and learning its Patterns. Right now I'm working with the Constructor Pattern that simulates Classes with in JavaScript.
So this is my "practice" class:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
var privateVarTest = 10;
this.getPrivateVarTest = function() {
return privateVarTest;
}
this.setPrivateVarTest = function( value ) {
privateVarTest = value;
}
}
Car.prototype.toString = function() {
return this.model + " is a " + this.year + " model and has " +
this.miles + " miles.";
}
var myCar = new Car( "Ford Focus", "2006", "65,000" );
document.getElementById('notepad').innerHTML += '</br> Testing </br>';
document.getElementById('notepad').innerHTML += myCar.toString() + '</br>';
document.getElementById('notepad').innerHTML += myCar.model + '</br>';
document.getElementById('notepad').innerHTML += myCar.getPrivateVarTest() + '</br>';
myCar.setPrivateVarTest( 20 );
document.getElementById('notepad').innerHTML += myCar.getPrivateVarTest() + '</br>';
Now I like using the prototype way of defining functions, as it doesn't instantiate a new version of the function for each Car Object created. However, in classic OOP languages we make our variables private and create public functions/methods to set and get these variables as needed.
JavaScript being Classless there is no private or public key word for this use, so I thought I'd experiment with a method of "faking" a private variable, and that's when found that using var instead of this essential makes it unaccessible out side of the constructor, but I was able to define getters and setters that would allow me to.
Now finaly to my question, sorry about the long wind up. For Best Practices from experinced JavaScript programmers, would you make all variables private to follow the standards of other OOP languages, and set getters and setter (which can not be prototyped forcing a creation for each Object), or avoid them as much as possible since the this keyword basicly lets you get and set all you want, and ONLY use private for hard coding some internal data needed for the class?
Thank you for taking the time to read this and providing to the discussion, I'm really just trying to get a feel for the standards that are used as Best Practices by experinced Web Developers.

General OOP
I'm in the camp that getters and setters are largely completely pointless and silly regardless of what language you're writing code in.
For the most part, exposed properties should be rare since any property of an object should typically be within the object's domain so only the object should actually change its own internals as a side-effect of other actions, not because some other object directly told it to change something. There are exceptions I'm sure (there always are) but I can't remember the last time I needed to make one.
Furthermore, when properties are exposed, the only reason to expose with a method is because you either can't just expose the property due to language constraints (Java) or because some validation or notification has to happen when you change that property. Just tacking on methods Java-bean-style that do nothing more than actually alter or return properties does nothing to preserve encapsulation. You might as well just make the property public if you can.
But the real problem with wanting to get/set everything willy-nilly from all over the place is that you've basically just written chained procedural code and called it OOP. You still have a long winding series of things that can only be reasoned about in terms of one happening after the other. With OOP, the idea is to avoid that long winding spaghetti chain so you can view your architecture more from the perspective of larger constructs that own specific domains interacting with each other at key points. Without that, you're perhaps reducing the spaghetti a touch by at least categorizing your functions under namespaces so it's easier to know where to look for stuff but you're not really leveraging the key wins that OOP can provide your architecture.
The real value of private or in JS's case local constructor/factory-closur vars is signalling intent. If it's exposed, something external really should be changing it. If it isn't, then you've made it clear that the var is only the object's business.
JS OOP
My advice is to forget class-emulation in JS. It's completely unnecessary. Prototypes are elegant and easy once you understand them. Think of a constructor's prototype property as a kind of a backup object. If you call a method on an instance that it doesn't have, the next step is to check the instance's constructor's prototype object property. If that object doesn't have it, then its constructor's prototype object gets checked and so on until you finally reach the core Object constructor's prototype.
It's because of that lookup process that you can add new methods to a constructor on the fly and have all instances "inherit" it after they've been built but it's not really inheritance so much as a fallback process.
Inheritance in JS is stupid-easy. That doesn't mean you should do a ton of it though. Long chains of cascading inheritance is regarded as an anti-pattern in any language for good reason and due to the way the callback process works, it can also really kill perf if you're hammering on the call object through like 18 levels of prototypes for every little thing in JS. I would say prefer composite objects to inheritance and when inheritances seems like a wiser option, check yourself any time you're tempted to inherit through more than 2-3 prototype links in the chain.
Oh, and one JS gotcha to look out for on local instance vars in the constructors as private properties: that's just JS's closure rules within a function scope context in action really. Methods declared in the prototype or outside of the constructor function can't access those internal vars. Constructor functions invoked with the new keyword change the rules of what 'this' accesses and they leave an instance behind but are otherwise executed JS functions in every other way.
Other flavors of crazy but also crazy-powerful worth understanding in JS OOP are the apply, call, and now bind methods. I tend to see these more as things you'd want in a factory but they are very powerful.
Once you've mastered JS OOP, start understanding JS from a functional perspective and you'll discover it has a really powerful 1-2 punch combo going on. We can do just about anything very easily and with a minimum of code in JS. The design tradeoff is performance (which modern JIT compilers are handling surprisingly well) and that it gives you plenty of rope to hang yourself with. I prefer the rope. The self-lynching is no fun but that's part of the learning/developing better instincts process which happens much faster as a result and leads to more maintainable code in the long haul. Whereas Java basically forces OOP implementation but due to being overly protectionist in regards to devs doing dumb things to themselves, results in community wide adoption of practices that run completely counter to the whole point of OOP.
The short version:
Stop getting/setting a lot if you do, regardless of language. It drastically reduces the win factor of implementing OOP in the first place.
Prototypes are really simple, elegant, and powerful. Tinker with them. Learn them. But be warned. Classes might start to feel archaic, clumsy, and overwrought in comparison (although to be fair, completely necessary in non-interpreted languages).
To make JS work well for you, self-learn the crap out of whatever aspect of it you happen to be dealing with. The rewards in terms of raw elegant linguistic power are more than worth the time spent. JS is closer to Scheme than the languages you listed being familiar with so it's weird but it's not being weird arbitrarily or without design principles in mind and JS's dominating success in web UI is no accident, regardless of what people telling everybody we're "stuck with it" would have you believe.
Full disclosure: I don't love Java.
Update:
The es6 class keyword changes virtually nothing about OOP in JS. It's 100% syntax-sugar. IMO, the use of the word "class" isn't doing newcomers any favors but there are advantages/disadvantages to all three styles of object constructor/creation and object instantiation in JS and they're all worth knowing/understanding. Those three approaches are functions as constructors, Object.create, and now the class keyword.

We need to be aware of our tendency to want every new language we learn to behave identically to the last language we learned. Or the first. And so forth. Douglas Crockford has a great (albeit a bit dated) google talk, in which he muses, "Javascript is the only language I know of that people feel they don't need to learn before using it". That talk will answer a lot of questions you never knew you had, including the one you've asked here.
There's nothing wrong with writing setters and getters. There's rarely harm in doing work to keep one's own sanity. You will happen to have a 'C accent' when speaking JS, but at least you'll be clear in your intent to anyone reading your code.
My sanity saving tip for managing 'this' across scopes, always remember that you can save your current 'this' before entering a new context:
var self = this;
I avoid using prototype except in special cases by including my object methods within the scope of the declaration.
function MyClass(_arg){
var self = this;
this.arg = _arg;
this.returnArg = function(){
return self.arg;
}
}
var foo = new MyClass("bar");
foo.returnArg(); //"bar"

in case of OOP I have to say infact javascript provide some level of oop.
by that I mean 4 main concepts of OOP design could be implemented in javascript although it is not strong and very well defined as in Java or C++. lets check those concepts and I will try to provide an example for each of them.
1- Abstraction : here as I said before we can understand why OOP is not very well defined as in Java, in Java we implement Abstraction concept using Classes, Variables, interfaced,... but in javascript Abstraction is rather implicitly defined in contrast to other OOP languages such as Java.
2- Encapsulation : I guess an example will suffice here
function Student (stdName, stdEmail, stdAvg) {
this.name = theName;
this.email = theEmail;
this.avg = stdAvg;
}
here also as you see we define a "class" like concept using functions in fact if get type Student you'll see it is a function.
3,4 - Inheritance and Polymorphism :
the way that JavaScript achieves Inheritance and Polymorphism is different than Java or C++ because of its prototypial (to be honest I have no idea any other way to say that) approach.
const Gun = function(soundEffect){
this.soundEffect = soundEffect;
};
Gun.prototype.fire = function(){
console.log(this.soundEffect);
};
const DesertEagle = function(color,clipSize){
this.color = color;
this.clipSize = clipSize;
};
DesertEagle.prototype = new Gun("pew pew peeeew");
const myWeapon = new DesertEagle("black",15);
myWeapon.fire();
now in order to cover the public/private access for variables and functions we have to use some kind of technique to implement such concept. check the code below:
const Student = function(name, stdNumber, avg){
this.name = name;
this.stdNumber = stdNumber;
this.avg = avg;
var that = this; //NOTE : we need to store a reference to "this" in order for further calls to private members
this.publicAccess = { // a set of functions and variables that we want as public
describe: function () {
console.log(that.name + " : " + that.stdNumber);
},
avg: this.avg,
};
return this.publicAccess; // return set of public access members
};
const newStd = new Student("john", "123", "3.4");
newStd.describe();
// output: john : 123
console.log(newStd.avg)
// output: 3.4
in ES6 defining a class is mush easier but it is just syntax sugar it is still the same thing at the heart of it.
I hope it will help .
I also recommend you this article (Javascript design patterns) it will provide some helpful information about avascript capabilities and design patterns.
please accept my apology for my poor English.

Related

javascript real prototype object oriented programming

I have always been fascinated by the notion of "prototype" in javascript, and I have used that to model business domains. But I have not used javascript for actual programming until quite recently. So now I am wondering how to really make use thinking in prototypes rather than classes. Recently javascript gained syntactic sugar with class ... extends { constructor() { ... } ... } and all that stuff that makes javascript appear more like Java. But it detracts away from the prototype orientation.
My question is, if my following intuitions jive and what I should read on if I am not interested in just reproducing Java in the browser (got decades of Java under my belt) but rather, how to really use the prototype paradigm.
First thing that I have always admired but never understood is why a class in javascript is implemented as a function?
> new (function(x) { this.foo = x; })(99)
< { foo: 99 }
It is so cool, but why is that? What's the deep philosophy behind calling new on a function, and effectively saying "a class is nothing but a constructor function". What if I call this function without new? Then this is whatever global object and it really doesn't make sense to add foo onto this, or does it? I bet it makes profound sense, but I just don't understand it.
Next there is the question whether I can build a system without ever calling constructors. This is where the prototype oriented programming comes along, which I apply to real business object modeling.
For example, I have a plan for a car,
car = {
type: "sedan",
material: "aluminum"
}
which essentially is a model of the car, that is, there is some mapping between the model and a real car. Let's say my plan says it has an aluminum body, then any real world instance of this car also has an aluminum body.
myCar = { plate: "FR-AS-2345" }
myCar.__proto__ = car
so now I can query:
> myCar.plate
< 'FR-AS-2345'
> myCar.type
< 'sedan'
Philosophically, what is a "real car" with respect to an information system anyway? Whether we describe the class of aluminum sedans or my car that's parked just outside, there is always a mapping of real world to information structure. And so, the structure of these car models are no different whether I define a universal aluminum sedan or my particular car.
Where this is really neat is in specification refinement. For example, I can say:
redCar = { color: "red" }
redCar.__proto__ = car
And if my car is actually red:
myCar.__proto__ = redCar
But I could also do something even cooler:
carsLikeMine = { plate = undefined }
carsLikeMine.__proto__ = myCar
so I was able to create a "class" from an instance, saying "just like mine but (of course) with an undefined license plate.
You get the gist. I could use
myCar.__proto__ = redCar
but I could also say
Object.setPrototypeOf(myCar, redCar)
which should I use?
And isn't there some easier way to do that? I was hoping I could somehow use the new operator:
yourCar = new carsLikeMine
but of course that doesn't work. However, I am sitting here pondering why not? I know formally the object is not a "constructor" function which new expects (what makes functions a "constructor" anyway, as I can apply the new operator on any function?) But why should there not be a simple operator some notation where I could say:
yourCar = new extend(carsLikeMine, { plate: "TÜ-PS-1234" })
Oh, so I can make my own prototype inheritance function:
function extend(prototype, object) {
// perhaps better also clone object first to prevent side-effect
const newObject = {}
Object.assign(newObject);
newObject.__proto__ = prototype;
return newObject;
}
Why am I the only one making such an extend function? Someone else must have long done this? This whole world of prototype oriented programming must have been explored and charted with all the "no entry" signs posted long ago. What should I read to get on top of that?
And finally, notice that in this prototype approach we do not call "constructors", so any programming that relies on constructors to create valid initialized objects is gone. Should I be concerned about this, or should one just learn to program without relying on constructors? (They are anyway unreliable, because javascript inherently does not protect its objects from change (and neither does Java once you learn to use reflection, I have set private variables on Java objects before).

Are getter/setters really useful? [duplicate]

What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?
If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:
public String foo;
is any worse than:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Whereas the former takes a lot less boilerplate code.
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
Here are the some of the reasons I am aware of:
Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
Hiding the internal representation of the property while exposing a property using an alternative representation.
Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
Allowing the getter/setter to be passed around as lambda expressions rather than values.
Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.
Because 2 weeks (months, years) from now when you realize that your setter needs to do more than just set the value, you'll also realize that the property has been used directly in 238 other classes :-)
A public field is not worse than a getter/setter pair that does nothing except returning the field and assigning to it. First, it's clear that (in most languages) there is no functional difference. Any difference must be in other factors, like maintainability or readability.
An oft-mentioned advantage of getter/setter pairs, isn't. There's this claim that you can change the implementation and your clients don't have to be recompiled. Supposedly, setters let you add functionality like validation later on and your clients don't even need to know about it. However, adding validation to a setter is a change to its preconditions, a violation of the previous contract, which was, quite simply, "you can put anything in here, and you can get that same thing later from the getter".
So, now that you broke the contract, changing every file in the codebase is something you should want to do, not avoid. If you avoid it you're making the assumption that all the code assumed the contract for those methods was different.
If that should not have been the contract, then the interface was allowing clients to put the object in invalid states. That's the exact opposite of encapsulation If that field could not really be set to anything from the start, why wasn't the validation there from the start?
This same argument applies to other supposed advantages of these pass-through getter/setter pairs: if you later decide to change the value being set, you're breaking the contract. If you override the default functionality in a derived class, in a way beyond a few harmless modifications (like logging or other non-observable behaviour), you're breaking the contract of the base class. That is a violation of the Liskov Substitutability Principle, which is seen as one of the tenets of OO.
If a class has these dumb getters and setters for every field, then it is a class that has no invariants whatsoever, no contract. Is that really object-oriented design? If all the class has is those getters and setters, it's just a dumb data holder, and dumb data holders should look like dumb data holders:
class Foo {
public:
int DaysLeft;
int ContestantNumber;
};
Adding pass-through getter/setter pairs to such a class adds no value. Other classes should provide meaningful operations, not just operations that fields already provide. That's how you can define and maintain useful invariants.
Client: "What can I do with an object of this class?"
Designer: "You can read and write several variables."
Client: "Oh... cool, I guess?"
There are reasons to use getters and setters, but if those reasons don't exist, making getter/setter pairs in the name of false encapsulation gods is not a good thing. Valid reasons to make getters or setters include the things often mentioned as the potential changes you can make later, like validation or different internal representations. Or maybe the value should be readable by clients but not writable (for example, reading the size of a dictionary), so a simple getter is a nice choice. But those reasons should be there when you make the choice, and not just as a potential thing you may want later. This is an instance of YAGNI (You Ain't Gonna Need It).
Lots of people talk about the advantages of getters and setters but I want to play devil's advocate. Right now I'm debugging a very large program where the programmers decided to make everything getters and setters. That might seem nice, but its a reverse-engineering nightmare.
Say you're looking through hundreds of lines of code and you come across this:
person.name = "Joe";
It's a beautifully simply piece of code until you realize its a setter. Now, you follow that setter and find that it also sets person.firstName, person.lastName, person.isHuman, person.hasReallyCommonFirstName, and calls person.update(), which sends a query out to the database, etc. Oh, that's where your memory leak was occurring.
Understanding a local piece of code at first glance is an important property of good readability that getters and setters tend to break. That is why I try to avoid them when I can, and minimize what they do when I use them.
In a pure object-oriented world getters and setters is a terrible anti-pattern. Read this article: Getters/Setters. Evil. Period. In a nutshell, they encourage programmers to think about objects as of data structures, and this type of thinking is pure procedural (like in COBOL or C). In an object-oriented language there are no data structures, but only objects that expose behavior (not attributes/properties!)
You may find more about them in Section 3.5 of Elegant Objects (my book about object-oriented programming).
There are many reasons. My favorite one is when you need to change the behavior or regulate what you can set on a variable. For instance, lets say you had a setSpeed(int speed) method. But you want that you can only set a maximum speed of 100. You would do something like:
public void setSpeed(int speed) {
if ( speed > 100 ) {
this.speed = 100;
} else {
this.speed = speed;
}
}
Now what if EVERYWHERE in your code you were using the public field and then you realized you need the above requirement? Have fun hunting down every usage of the public field instead of just modifying your setter.
My 2 cents :)
One advantage of accessors and mutators is that you can perform validation.
For example, if foo was public, I could easily set it to null and then someone else could try to call a method on the object. But it's not there anymore! With a setFoo method, I could ensure that foo was never set to null.
Accessors and mutators also allow for encapsulation - if you aren't supposed to see the value once its set (perhaps it's set in the constructor and then used by methods, but never supposed to be changed), it will never been seen by anyone. But if you can allow other classes to see or change it, you can provide the proper accessor and/or mutator.
Thanks, that really clarified my thinking. Now here is (almost) 10 (almost) good reasons NOT to use getters and setters:
When you realize you need to do more than just set and get the value, you can just make the field private, which will instantly tell you where you've directly accessed it.
Any validation you perform in there can only be context free, which validation rarely is in practice.
You can change the value being set - this is an absolute nightmare when the caller passes you a value that they [shock horror] want you to store AS IS.
You can hide the internal representation - fantastic, so you're making sure that all these operations are symmetrical right?
You've insulated your public interface from changes under the sheets - if you were designing an interface and weren't sure whether direct access to something was OK, then you should have kept designing.
Some libraries expect this, but not many - reflection, serialization, mock objects all work just fine with public fields.
Inheriting this class, you can override default functionality - in other words you can REALLY confuse callers by not only hiding the implementation but making it inconsistent.
The last three I'm just leaving (N/A or D/C)...
Depends on your language. You've tagged this "object-oriented" rather than "Java", so I'd like to point out that ChssPly76's answer is language-dependent. In Python, for instance, there is no reason to use getters and setters. If you need to change the behavior, you can use a property, which wraps a getter and setter around basic attribute access. Something like this:
class Simple(object):
def _get_value(self):
return self._value -1
def _set_value(self, new_value):
self._value = new_value + 1
def _del_value(self):
self.old_values.append(self._value)
del self._value
value = property(_get_value, _set_value, _del_value)
Well i just want to add that even if sometimes they are necessary for the encapsulation and security of your variables/objects, if we want to code a real Object Oriented Program, then we need to STOP OVERUSING THE ACCESSORS, cause sometimes we depend a lot on them when is not really necessary and that makes almost the same as if we put the variables public.
EDIT: I answered this question because there are a bunch of people learning programming asking this, and most of the answers are very technically competent, but they're not as easy to understand if you're a newbie. We were all newbies, so I thought I'd try my hand at a more newbie friendly answer.
The two main ones are polymorphism, and validation. Even if it's just a stupid data structure.
Let's say we have this simple class:
public class Bottle {
public int amountOfWaterMl;
public int capacityMl;
}
A very simple class that holds how much liquid is in it, and what its capacity is (in milliliters).
What happens when I do:
Bottle bot = new Bottle();
bot.amountOfWaterMl = 1500;
bot.capacityMl = 1000;
Well, you wouldn't expect that to work, right?
You want there to be some kind of sanity check. And worse, what if I never specified the maximum capacity? Oh dear, we have a problem.
But there's another problem too. What if bottles were just one type of container? What if we had several containers, all with capacities and amounts of liquid filled? If we could just make an interface, we could let the rest of our program accept that interface, and bottles, jerrycans and all sorts of stuff would just work interchangably. Wouldn't that be better? Since interfaces demand methods, this is also a good thing.
We'd end up with something like:
public interface LiquidContainer {
public int getAmountMl();
public void setAmountMl(int amountMl);
public int getCapacityMl();
}
Great! And now we just change Bottle to this:
public class Bottle implements LiquidContainer {
private int capacityMl;
private int amountFilledMl;
public Bottle(int capacityMl, int amountFilledMl) {
this.capacityMl = capacityMl;
this.amountFilledMl = amountFilledMl;
checkNotOverFlow();
}
public int getAmountMl() {
return amountFilledMl;
}
public void setAmountMl(int amountMl) {
this.amountFilled = amountMl;
checkNotOverFlow();
}
public int getCapacityMl() {
return capacityMl;
}
private void checkNotOverFlow() {
if(amountOfWaterMl > capacityMl) {
throw new BottleOverflowException();
}
}
I'll leave the definition of the BottleOverflowException as an exercise to the reader.
Now notice how much more robust this is. We can deal with any type of container in our code now by accepting LiquidContainer instead of Bottle. And how these bottles deal with this sort of stuff can all differ. You can have bottles that write their state to disk when it changes, or bottles that save on SQL databases or GNU knows what else.
And all these can have different ways to handle various whoopsies. The Bottle just checks and if it's overflowing it throws a RuntimeException. But that might be the wrong thing to do.
(There is a useful discussion to be had about error handling, but I'm keeping it very simple here on purpose. People in comments will likely point out the flaws of this simplistic approach. ;) )
And yes, it seems like we go from a very simple idea to getting much better answers quickly.
Please note also that you can't change the capacity of a bottle. It's now set in stone. You could do this with an int by declaring it final. But if this was a list, you could empty it, add new things to it, and so on. You can't limit the access to touching the innards.
There's also the third thing that not everyone has addressed: getters and setters use method calls. That means that they look like normal methods everywhere else does. Instead of having weird specific syntax for DTOs and stuff, you have the same thing everywhere.
I know it's a bit late, but I think there are some people who are interested in performance.
I've done a little performance test. I wrote a class "NumberHolder" which, well, holds an Integer. You can either read that Integer by using the getter method
anInstance.getNumber() or by directly accessing the number by using anInstance.number. My programm reads the number 1,000,000,000 times, via both ways. That process is repeated five times and the time is printed. I've got the following result:
Time 1: 953ms, Time 2: 741ms
Time 1: 655ms, Time 2: 743ms
Time 1: 656ms, Time 2: 634ms
Time 1: 637ms, Time 2: 629ms
Time 1: 633ms, Time 2: 625ms
(Time 1 is the direct way, Time 2 is the getter)
You see, the getter is (almost) always a bit faster. Then I tried with different numbers of cycles. Instead of 1 million, I used 10 million and 0.1 million.
The results:
10 million cycles:
Time 1: 6382ms, Time 2: 6351ms
Time 1: 6363ms, Time 2: 6351ms
Time 1: 6350ms, Time 2: 6363ms
Time 1: 6353ms, Time 2: 6357ms
Time 1: 6348ms, Time 2: 6354ms
With 10 million cycles, the times are almost the same.
Here are 100 thousand (0.1 million) cycles:
Time 1: 77ms, Time 2: 73ms
Time 1: 94ms, Time 2: 65ms
Time 1: 67ms, Time 2: 63ms
Time 1: 65ms, Time 2: 65ms
Time 1: 66ms, Time 2: 63ms
Also with different amounts of cycles, the getter is a little bit faster than the regular way. I hope this helped you.
Don't use getters setters unless needed for your current delivery I.e. Don't think too much about what would happen in the future, if any thing to be changed its a change request in most of the production applications, systems.
Think simple, easy, add complexity when needed.
I would not take advantage of ignorance of business owners of deep technical know how just because I think it's correct or I like the approach.
I have massive system written without getters setters only with access modifiers and some methods to validate n perform biz logic. If you absolutely needed the. Use anything.
We use getters and setters:
for reusability
to perform validation in later stages of programming
Getter and setter methods are public interfaces to access private class members.
Encapsulation mantra
The encapsulation mantra is to make fields private and methods public.
Getter Methods: We can get access to private variables.
Setter Methods: We can modify private fields.
Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that method
better;
safer; and
faster.
Anywhere a value can be used, a method that returns that value can be added. Instead of:
int x = 1000 - 500
use
int x = 1000 - class_name.getValue();
In layman's terms
Suppose we need to store the details of this Person. This Person has the fields name, age and sex. Doing this involves creating methods for name, age and sex. Now if we need create another person, it becomes necessary to create the methods for name, age, sex all over again.
Instead of doing this, we can create a bean class(Person) with getter and setter methods. So tomorrow we can just create objects of this Bean class(Person class) whenever we need to add a new person (see the figure). Thus we are reusing the fields and methods of bean class, which is much better.
I spent quite a while thinking this over for the Java case, and I believe the real reasons are:
Code to the interface, not the implementation
Interfaces only specify methods, not fields
In other words, the only way you can specify a field in an interface is by providing a method for writing a new value and a method for reading the current value.
Those methods are the infamous getter and setter....
It can be useful for lazy-loading. Say the object in question is stored in a database, and you don't want to go get it unless you need it. If the object is retrieved by a getter, then the internal object can be null until somebody asks for it, then you can go get it on the first call to the getter.
I had a base page class in a project that was handed to me that was loading some data from a couple different web service calls, but the data in those web service calls wasn't always used in all child pages. Web services, for all of the benefits, pioneer new definitions of "slow", so you don't want to make a web service call if you don't have to.
I moved from public fields to getters, and now the getters check the cache, and if it's not there call the web service. So with a little wrapping, a lot of web service calls were prevented.
So the getter saves me from trying to figure out, on each child page, what I will need. If I need it, I call the getter, and it goes to find it for me if I don't already have it.
protected YourType _yourName = null;
public YourType YourName{
get
{
if (_yourName == null)
{
_yourName = new YourType();
return _yourName;
}
}
}
One aspect I missed in the answers so far, the access specification:
for members you have only one access specification for both setting and getting
for setters and getters you can fine tune it and define it separately
In languages which don't support "properties" (C++, Java) or require recompilation of clients when changing fields to properties (C#), using get/set methods is easier to modify. For example, adding validation logic to a setFoo method will not require changing the public interface of a class.
In languages which support "real" properties (Python, Ruby, maybe Smalltalk?) there is no point to get/set methods.
One of the basic principals of OO design: Encapsulation!
It gives you many benefits, one of which being that you can change the implementation of the getter/setter behind the scenes but any consumer of that value will continue to work as long as the data type remains the same.
You should use getters and setters when:
You're dealing with something that is conceptually an attribute, but:
Your language doesn't have properties (or some similar mechanism, like Tcl's variable traces), or
Your language's property support isn't sufficient for this use case, or
Your language's (or sometimes your framework's) idiomatic conventions encourage getters or setters for this use case.
So this is very rarely a general OO question; it's a language-specific question, with different answers for different languages (and different use cases).
From an OO theory point of view, getters and setters are useless. The interface of your class is what it does, not what its state is. (If not, you've written the wrong class.) In very simple cases, where what a class does is just, e.g., represent a point in rectangular coordinates,* the attributes are part of the interface; getters and setters just cloud that. But in anything but very simple cases, neither the attributes nor getters and setters are part of the interface.
Put another way: If you believe that consumers of your class shouldn't even know that you have a spam attribute, much less be able to change it willy-nilly, then giving them a set_spam method is the last thing you want to do.
* Even for that simple class, you may not necessarily want to allow setting the x and y values. If this is really a class, shouldn't it have methods like translate, rotate, etc.? If it's only a class because your language doesn't have records/structs/named tuples, then this isn't really a question of OO…
But nobody is ever doing general OO design. They're doing design, and implementation, in a specific language. And in some languages, getters and setters are far from useless.
If your language doesn't have properties, then the only way to represent something that's conceptually an attribute, but is actually computed, or validated, etc., is through getters and setters.
Even if your language does have properties, there may be cases where they're insufficient or inappropriate. For example, if you want to allow subclasses to control the semantics of an attribute, in languages without dynamic access, a subclass can't substitute a computed property for an attribute.
As for the "what if I want to change my implementation later?" question (which is repeated multiple times in different wording in both the OP's question and the accepted answer): If it really is a pure implementation change, and you started with an attribute, you can change it to a property without affecting the interface. Unless, of course, your language doesn't support that. So this is really just the same case again.
Also, it's important to follow the idioms of the language (or framework) you're using. If you write beautiful Ruby-style code in C#, any experienced C# developer other than you is going to have trouble reading it, and that's bad. Some languages have stronger cultures around their conventions than others.—and it may not be a coincidence that Java and Python, which are on opposite ends of the spectrum for how idiomatic getters are, happen to have two of the strongest cultures.
Beyond human readers, there will be libraries and tools that expect you to follow the conventions, and make your life harder if you don't. Hooking Interface Builder widgets to anything but ObjC properties, or using certain Java mocking libraries without getters, is just making your life more difficult. If the tools are important to you, don't fight them.
From a object orientation design standpoint both alternatives can be damaging to the maintenance of the code by weakening the encapsulation of the classes. For a discussion you can look into this excellent article: http://typicalprogrammer.com/?p=23
Code evolves. private is great for when you need data member protection. Eventually all classes should be sort of "miniprograms" that have a well-defined interface that you can't just screw with the internals of.
That said, software development isn't about setting down that final version of the class as if you're pressing some cast iron statue on the first try. While you're working with it, code is more like clay. It evolves as you develop it and learn more about the problem domain you are solving. During development classes may interact with each other than they should (dependency you plan to factor out), merge together, or split apart. So I think the debate boils down to people not wanting to religiously write
int getVar() const { return var ; }
So you have:
doSomething( obj->getVar() ) ;
Instead of
doSomething( obj->var ) ;
Not only is getVar() visually noisy, it gives this illusion that gettingVar() is somehow a more complex process than it really is. How you (as the class writer) regard the sanctity of var is particularly confusing to a user of your class if it has a passthru setter -- then it looks like you're putting up these gates to "protect" something you insist is valuable, (the sanctity of var) but yet even you concede var's protection isn't worth much by the ability for anyone to just come in and set var to whatever value they want, without you even peeking at what they are doing.
So I program as follows (assuming an "agile" type approach -- ie when I write code not knowing exactly what it will be doing/don't have time or experience to plan an elaborate waterfall style interface set):
1) Start with all public members for basic objects with data and behavior. This is why in all my C++ "example" code you'll notice me using struct instead of class everywhere.
2) When an object's internal behavior for a data member becomes complex enough, (for example, it likes to keep an internal std::list in some kind of order), accessor type functions are written. Because I'm programming by myself, I don't always set the member private right away, but somewhere down the evolution of the class the member will be "promoted" to either protected or private.
3) Classes that are fully fleshed out and have strict rules about their internals (ie they know exactly what they are doing, and you are not to "fuck" (technical term) with its internals) are given the class designation, default private members, and only a select few members are allowed to be public.
I find this approach allows me to avoid sitting there and religiously writing getter/setters when a lot of data members get migrated out, shifted around, etc. during the early stages of a class's evolution.
There is a good reason to consider using accessors is there is no property inheritance. See next example:
public class TestPropertyOverride {
public static class A {
public int i = 0;
public void add() {
i++;
}
public int getI() {
return i;
}
}
public static class B extends A {
public int i = 2;
#Override
public void add() {
i = i + 2;
}
#Override
public int getI() {
return i;
}
}
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
a.add();
System.out.println(a.i);
System.out.println(a.getI());
}
}
Output:
0
0
4
Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are:
Abstraction
Encapsulation
Suppose we have an Employee class:
package com.highmark.productConfig.types;
public class Employee {
private String firstName;
private String middleName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
}
Here the implementation details of Full Name is hidden from the user and is not accessible directly to the user, unlike a public attribute.
There is a difference between DataStructure and Object.
Datastructure should expose its innards and not behavior.
An Object should not expose its innards but it should expose its behavior, which is also known as the Law of Demeter
Mostly DTOs are considered more of a datastructure and not Object. They should only expose their data and not behavior. Having Setter/Getter in DataStructure will expose behavior instead of data inside it. This further increases the chance of violation of Law of Demeter.
Uncle Bob in his book Clean code explained the Law of Demeter.
There is a well-known heuristic called the Law of Demeter that says a
module should not know about the innards of the objects it
manipulates. As we saw in the last section, objects hide their data
and expose operations. This means that an object should not expose its
internal structure through accessors because to do so is to expose,
rather than to hide, its internal structure.
More precisely, the Law of Demeter says that a method f of a class C
should only call the methods of these:
C
An object created by f
An object passed as an argument to f
An object held in an instance variable of C
The method should not invoke methods on objects that are returned by any of the allowed functions.
In other words, talk to friends, not to strangers.
So according this, example of LoD violation is:
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
Here, the function should call the method of its immediate friend which is ctxt here, It should not call the method of its immediate friend's friend. but this rule doesn't apply to data structure. so here if ctxt, option, scratchDir are datastructure then why to wrap their internal data with some behavior and doing a violation of LoD.
Instead, we can do something like this.
final String outputDir = ctxt.options.scratchDir.absolutePath;
This fulfills our needs and doesn't even violate LoD.
Inspired by Clean Code by Robert C. Martin(Uncle Bob)
If you don't require any validations and not even need to maintain state i.e. one property depends on another so we need to maintain the state when one is change. You can keep it simple by making field public and not using getter and setters.
I think OOPs complicates things as the program grows it becomes nightmare for developer to scale.
A simple example; we generate c++ headers from xml. The header contains simple field which does not require any validations. But still as in OOPS accessor are fashion we generates them as following.
const Filed& getfield() const
Field& getField()
void setfield(const Field& field){...}
which is very verbose and is not required. a simple
struct
{
Field field;
};
is enough and readable.
Functional programming don't have the concept of data hiding they even don't require it as they do not mutate the data.
Additionally, this is to "future-proof" your class. In particular, changing from a field to a property is an ABI break, so if you do later decide that you need more logic than just "set/get the field", then you need to break ABI, which of course creates problems for anything else already compiled against your class.
One other use (in languages that support properties) is that setters and getters can imply that an operation is non-trivial. Typically, you want to avoid doing anything that's computationally expensive in a property.
One relatively modern advantage of getters/setters is that is makes it easier to browse code in tagged (indexed) code editors. E.g. If you want to see who sets a member, you can open the call hierarchy of the setter.
On the other hand, if the member is public, the tools don't make it possible to filter read/write access to the member. So you have to trudge though all uses of the member.
Getters and setters coming from data hiding. Data Hiding means We
are hiding data from outsiders or outside person/thing cannot access
our data.This is a useful feature in OOP.
As a example:
If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.
public and private are access modifiers.
So how can we access that variable outside:
This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.
Example(Java):
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name= name;
}
Advantage:
When anyone want to access or change/set value to balance variable, he/she must have permision.
//assume we have person1 object
//to give permission to check balance
person1.getName()
//to give permission to set balance
person1.setName()
You can set value in constructor also but when later on when you want
to update/change value, you have to implement setter method.

No ways to have class-based objects in javascript?

The javascript prototype-based object-oriented programming style is interesting, but there are a lot of situations where you need the ability to create objects from a class.
For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.
I've read a lot of tutorials and the book "Javascript : the good parts", but yet it seems to me that there is no way to define classes that respect 1) encapsulation and 2) efficient member methods declaration (I mean : member methods that are being defined once, and shared among every class instances).
To define private variables, closures are being used :
function ClassA()
{
var value = 1;
this.getValue = function()
{
return value;
}
}
The problem here is that every instance of "ClassA" will have its own copy of the member function "getValue", which is not efficient.
To define member functions efficiently, prototype is being used :
function ClassB()
{
this.value = 1;
}
ClassB.prototype.getValue = function()
{
return this.value;
}
The problem here is that the member variable "value" is public.
I don't think that this issue can be solved easily, since "private" variables need to be defined DURING object creation (so that the object can have access to its context of creation, without exposing thoses values) whereas prototype-based member functions definition has to be done AFTER object creation, so that prototype makes sense ("this.prototype" does not exists, I've checked).
Or am I missing something ?
EDIT :
First of all, thank you for your interesting answers.
I just wanted to add a little precision to my initial message :
What I really want to do is to have 1) private variables (encapsulation is good, because people only have access to what they need) and 2) efficient member methods declaration (avoid copies).
It seems that simple private variables declaration can really only be achieved via closure in javascript, that's essentially why I focused on the class based approach. If there is a way to achieve simple private variables declaration with a prototype based approach, that's okay for me, I'm not a fierce class-based approach proponnent.
After reading the answers, it seems like the simple solution is to forget about privates, and use a special coding conventions to detter other programmers from accessing "private" variables directly...
And I agree, my title / first sentence was misleading regarding the issue I wanted to discuss here.
Shh, come here! Wanna hear a secret?
Classical inheritance is a tested and tried approach.
It is useful to implement it in JavaScript often. Classes are a nice concept to have and having templates for modeling our world after objects is awesome.
Classical inheritance is just a pattern. It's perfectly OK to implement classical inheritance in JavaScript if it's the pattern you need for your use case.
Prototypical inheritance focuses on sharing functionality and that's awesome (dinasaur drumstick awesome), but in some cases you want to share a data-scheme and not functionality. That's a problem prototypical inheritance does not address at all.
So, you're telling me classes are not evil like everyone keeps telling me?
No, they are not. What the JS community frowns upon is not the concept of classes, it's limiting yourself to just classes for code reuse. Just like the language does not enforce strong or static typing, it doesn't enforce schemes on object structure.
In fact, behind the scene clever implementations of the language can turn your normal objects to something resembling classical inheritance classes.
So, how do classes work in JavaScript
Well, you really only need a constructor:
function getVehicle(engine){
return { engine : engine };
}
var v = getVehicle("V6");
v.engine;//v6
We now have a vehicle class. We didn't need to define a Vehicle class explicitly using a special keyword. Now, some people don't like to do things this way and are used to the more classical way. For this JS provides (silly imho) syntactic sugar by doing:
function Vehicle(engine){
this.engine = engine;
}
var v = new Vehicle("V6");
v.engine;//v6
That's the same thing as the example above for the most part.
So, what are we still missing?
Inheritance and private members.
What if I told you basic subtyping is very simple in JavaScript?
JavaScript's notion of typing is different than what we're used to in other languages. What does it mean to be a sub-type of some type in JS?
var a = {x:5};
var b = {x:3,y:3};
Is the type of b a sub type of the type of a? Let's say if it is according to (strong) behavioral subtyping (the LSP):
<<<< Begin technical part
Contravariance of method arguments in the subtype - Is fully preserved in this sort of inheritance.
Covariance of return types in the subtype - Is fully preserved in this sort of inheritance.
No new exceptions should be thrown by methods of the subtype, except where those exceptions are themselves subtypes of exceptions thrown by the methods of the supertype. - Is fully preserved in this sort of inheritance.
Also,
Preconditions cannot be strengthened in a subtype.
Postconditions cannot be weakened in a subtype.
Invariants of the supertype must be preserved in a subtype.
The history rule
All of these are again, are up to us to keep. We can keep them as tightly or loosly as we want, we don't have to, but we surely can.
So matter of fact, as long as we abide to these rules above when implementing our inheritance, we're fully implementing strong behavioral subtyping, which is a very powerful form of subtyping (see note*).
>>>>> End technical part
Trivially, one can also see that structural subtyping holds.
How would this apply to our Car example?
function getCar(typeOfCar){
var v = getVehicle("CarEngine");
v.typeOfCar = typeOfCar;
return v;
}
v = getCar("Honda");
v.typeOfCar;//Honda;
v.engine;//CarEngine
Not too hard, was it? What about private members?
function getVehicle(engine){
var secret = "Hello"
return {
engine : engine,
getSecret : function() {
return secret;
}
};
}
See, secret is a closure variable. It's perfectly "private", it works differently than privates in languages like Java, but it's impossible to access from the outside.
What about having privates in functions?
Ah! That's a great question.
If we want to use a private variable in a function we share on the prototype we need to firrst understand how JS closures and functions work.
In JavaScript functions are first class. This means you can pass functions around.
function getPerson(name){
var greeting = "Hello " + name;
return {
greet : function() {
return greeting;
}
};
}
var a = getPerson("thomasc");
a.greet(); //Hello thomasc
So far so good, but we can pass that function bounded to a around to other objects! This lets you do very loose decoupling which is awesome.
var b = a.greet;
b(); //Hello thomasc
Wait! How did b know the person's name is thomasc? That's just the magic of closures. Pretty awesome huh?
You might be worried about performance. Let me tell you how I learned to stop worrying and started to love the optimizing JIT.
In practice, having copies of functions like that is not a big issue. Functions in javascript are all about well, functionality! Closures are an awesome concept, once you grasp and master them you see it's well worth it, and the performance hit really isn't that meaningful. JS is getting faster every day, don't worry about these sort of performance issues.
If you think it's complicated, the following is also very legitimate. A common contract with other developers simply says "If my variable starts with _ don't touch it, we are both consenting adults". This would look something like:
function getPerson(name){
var greeter = {
greet : function() {
return "Hello" +greeter._name;
}
};
greeter._name = name;
return greeter;
}
Or in classical style
function Person(name){
this._name = name;
this.greet = function(){
return "Hello "+this._name;
}
}
Or if you'd like to cache the function on the prototype instead of instantiate copies:
function Person(name){
this._name = name;
}
Person.prototype.greet = function(){
return "Hello "+this._name;
}
So, to sum it up:
You can use classical inheritance patterns, they are useful for sharing types of data
You should also use prototypical inheritance, it is just as potent, and much more in cases you want to share functionality.
TheifMaster pretty much nailed it. Having privates private is really not a big deal as one might think in JavaScript, as long as your code defines a clear interface this should not be problematic at all. We're all concenting adults here :)
*The clever reader might think: Huh? Weren't you tricking me there with the history rule? I mean, property access isn't encapsulated.
I say no, I was not. Even if you don't explicitly encapsulate the fields as private, you can simply define your contract in a way that does not access them. Often like TheifMaster suggested with _. Also, I think the history rule is not that big of a deal in a lot of such scenarios as long as we're not changing the way property access treats properties of the parent object. Again, it's up to us.
I don't want to be discouraging since you seem to be a fairly new member of StackOverflow, however I'm going to have to be a little in your face and say that it's a really bad idea to try to implement classical inheritance in JavaScript.
Note: When I say that it's a bad idea to implement classical inheritance in JavaScript I mean that trying to simulate actual classes, interfaces, access modifiers, etc. in JavaScript is a bad idea. Nevertheless, classical inheritance as a design pattern in JavaScript is useful as it's just syntactic sugar for prototypal inheritance (e.g. maximally minimal classes). I use this design pattern in my code all the time (a la augment).
JavaScript is a prototypal object-oriented programming language. Not a classical object-oriented programming language. Sure, you can implement classical inheritance on top of JavaScript but before you do keep the following things in mind:
You're going against the spirit of the language, which means that you'll be faced with problems. Lots of problems - performance, readability, maintainability, etc.
You don't need classes. Thomas, I know that you truly believe that you need classes but trust me on this. You don't.
For your sake I'll provide two answers to this question. The first one will show you how to do classical inheritance in JavaScript. The second one (which I recommend) will teach you to embrace prototypal inheritance.
Classical Inheritance in JavaScript
Most programmers start with trying to implement classical inheritance in JavaScript. Even JavaScript Gurus like Douglas Crockford tried to implement classical inheritance in JavaScript. I too tried to implement classical inheritance in JavaScript.
First I created a library called Clockwork and then augment. However I wouldn't recommend you to use either of these libraries because they go against the spirit of JavaScript. The truth is that I was still an amateur JavaScript programmer when I wrote these classical inheritance libraries.
The only reason I mention this is because everyone is an amateur at some point of time, and although I would prefer that you didn't use classical inheritance patterns in JavaScript, I can't expect you to understand why prototypal inheritance matters just yet.
You can't learn how to cycle without falling down a few times. I believe you're still in the learning phase with respect to prototypal inheritance. Your need for classical inheritance is like the training wheels on cycles.
Nevertheless, training wheels are important. If you want there are some classical inheritance libraries out there which should make you more comfortable writing code in JavaScript. One such library is jTypes. Just remember to take off the training wheels when you are confident of your skills as a JavaScript programmer.
Note: Personally I don't like jTypes one bit.
Prototypal Inheritance in JavaScript
I'm writing this section as a milestone for you so that you can come back later and know what to do next when you are ready to learn about true prototypal inheritance.
First of all the following line is wrong:
The javascript prototype-based object-oriented programming style is interesting, but there are a lot of situations where you need the ability to create objects from a class.
This is wrong because:
You will never need to create objects from a class in JavaScript.
There is no way to create a class in JavaScript.
Yes it's possible to simulate classical inheritance in JavaScript. However you're still inheriting properties from objects and not classes. For example, ECMAScript Harmony classes are just syntactic sugar for the classical pattern of prototypal inheritance.
In the same context the example you gave is also wrong:
For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.
Yes you can create a new line from an existing one even though the workspace is empty in the beginning. What you need to understand is that the line is not actually drawn though.
var line = {
x1: 0,
y1: 0,
x2: 0,
y2: 0,
draw: function () {
// drawing logic
},
create: function (x1, y1, x2, y2) {
var line = Object.create(this);
line.x1 = x1;
line.y1 = y1;
line.x2 = x2;
line.y2 = y2;
return line;
}
};
Now you can draw your the above line by simply calling line.draw or else you could create a new line from it:
var line2 = line.create(0, 0, 0, 100);
var line3 = line.create(0, 100, 100, 100);
var line4 = line.create(100, 100, 100, 0);
var line5 = line.create(100, 0, 0, 0);
line2.draw();
line3.draw();
line4.draw();
line5.draw();
The lines line2, line3, line4 and line5 form a 100x100 square when drawn.
Conclusion
So you see you really don't need classes in JavaScript. Objects are enough. Encapsulation can be easily achieved using functions.
That being said you can't have public functions of each instance access the private state of the object without each instance having its own set of public functions.
This is not a problem however because:
You don't really need private state. You may think that you do, but you really don't.
If you really want to make a variable private then as ThiefMaster mentioned just prefix the variable name with an underscore and tell your users not to mess with it.
Aight, here's my attempt at solving this particular issue, although I think following conventions it's a better approach, ie. prefix your variables with _. Here I just keep track of the instances in an array, they can then be removed with a _destroy method. I'm sure this can be improved but hopefully it will give you some ideas:
var Class = (function ClassModule() {
var private = []; // array of objects of private variables
function Class(value) {
this._init();
this._set('value', value);
}
Class.prototype = {
// create new instance
_init: function() {
this.instance = private.length;
private.push({ instance: this.instance });
},
// get private variable
_get: function(prop) {
return private[this.instance][prop];
},
// set private variable
_set: function(prop, value) {
return private[this.instance][prop] = value;
},
// remove private variables
_destroy: function() {
delete private[this.instance];
},
getValue: function() {
return this._get('value');
}
};
return Class;
}());
var a = new Class('foo');
var b = new Class('baz');
console.log(a.getValue()); //=> foo
console.log(b.getValue()); //=> baz
a._destroy();
console.log(b.getValue()); //=> baz
You don't need private/public at runtime. These are enforceable statically. Any project complex enough to enforce private properties are not used outside will have a build/pre-process step, which you can use
to verify the fact. Even languages with syntax for private/public have a way to access private at runtime.
As for defining class-based objects, the constructor+prototype you are using is the simplest and most efficient way. Any kind of additional wizardry will
be more complex and less performant.
Although you can cache prototype so you don't have to repeat ClassB.prototype. all the time:
//in node.js you can leave the wrapper function out
var ClassB = (function() {
var method = ClassB.prototype;
function ClassB( value ) {
this._value = value;
}
method.getValue = function() {
return this._value;
};
method.setValue = function( value ) {
this._value = value;
};
return ClassB;
})();
The above does not require any library and you can easily create a macro for it.
Also, in this case even a regex is enough to verify
that "private" properties are used correctly. Run /([a-zA-Z$_-][a-zA-Z0-9$_-]*)\._.+/g through the file and see that the first match
is always this. http://jsfiddle.net/7gumy/
It's impossible as far as I know without other instances influencing the value, so if it's a constant you're still good by wrapping it in a function like this:
(function( context ) {
'use strict';
var SOME_CONSTANT = 'Hello World';
var SomeObject = function() {};
SomeObject.prototype.sayHello = function() {
console.log(SOME_CONSTANT);
};
context.SomeObject = SomeObject;
})( this );
var someInstance = new SomeObject();
someInstance.sayHello();
The best you could do is annotate that a property shouldn't be touched by using an underscore like this._value instead of this.value.
Note that private functions are possible by hiding them in a function:
(function( context ) {
'use strict';
var SomeObject = function() {};
var getMessage = function() {
return 'Hello World';
};
SomeObject.prototype.sayHello = function() {
console.log(getMessage());
};
context.SomeObject = SomeObject;
})( this );
var someInstance = new SomeObject();
someInstance.sayHello();
Here is an example of 2 'Classes' extending and interacting with each other: http://jsfiddle.net/TV3H3/
If you really want private entities on a per instance basis, but still want to inherit your methods, you could use the following set-up:
var Bundle = (function(){
var local = {}, constructor = function(){
if ( this instanceof constructor ) {
local[(this.id = constructor.id++)] = {
data: 123
};
}
};
constructor.id = 0;
constructor.prototype.exampleMethod = function(){
return local[this.id].data;
}
return constructor;
})();
Now if you create a new Bundle, the data value is locked away inside:
var a = new Bundle(); console.log( a.exampleMethod() ); /// 123
However you now get into the debate as to whether you should truly have private values in JavaScript. As far as I've found it's always better for those that may need to extend your code—even yourself—to have open access to everything.
There are also hidden downsides to the above pattern, besides not being so readable, or being clunky to access "private" values. One fact is that every single instance of Bundle will retain a reference to the local object. This could mean—for example—if you created thousands of Bundles, and deleted all but one of them, the data held in local would not be garbage collected for all Bundles ever created. You'd have to include some deconstruction code to fix that... basically making things more complicated.
So I'd recommend dropping the idea of private entities / properties, whichever pattern you decide to go for... object-based or constructor. The benefit of JavaScript is that all these different approaches are possible—it's no-where-near as clear cut as class-based languages—which some could argue makes things confusing, but I like the freedom JavaScript lends towards being quick and expressive.
with regards this statement in your question:
For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.
You seem to be under the misunderstanding that objects in Javascript can only be made by cloning existing objects, which would backtrack to the problem of "okay but what about the very first object? that can't be made by cloning an existing object because there aren't any existing objects."
However you can make objects from scratch, and the syntax for that is as simple as var object = {}
I mean, that's the simplest possible object, an empty object. More useful of course would be an object with stuff in it:
var object = {
name: "Thing",
value: 0,
method: function() {
return true;
}
}
and so on, and now you're off to the races!
There are cleverer people than I answering this question, but I wanted to note one part in particular that you just edited in - the private variable part.
You can simulate this using closures; an awesome construct which allows a function to have it's own environment. You could do this:
var line = (function() {
var length = 0;
return {
setLen : function (newLen) {
length = newLen;
},
getLen : function () {
return length;
}
};
}());
This will set line to be an object with the setLen and getLen methods, but you'll have no way of manually accessing length without using those methods.

IS OOP possible in Javascript?

I recently found out that Javascript function can have classes, so I was wondering if OOP is also possible through javascript. Is It? If yes, Could you please point out some tutorials or site, where I can start with?
OOP is definitely possible. While Javascript doesn't have "classes" like most OO languages do, what it does have is called "prototypes". Basically, objects are defined in terms of other objects rather than classes. (Objects can also emulate classes to some degree, for those who can't wrap their minds around prototypal inheritance.)
One could argue JS's OO capabilities exceed those of most languages, considering objects play an even more essential role than in languages with classes.
OOP is central to Javascript, but it's not classical OOP. Javascript uses prototypes, not classes.
Douglas Crockford is a Javascript genius, so his Prototypal Inheritance in Javascript is a nice starting point. A Google search for "Javascript OOP" likely will turn up some neat articles to peruse, as well — I like the article by Mike Koss.
Javascript is an intrinsically OOP language. Like others have said, it is classless, but you have a choice of how you want to create objects.
You can create objects that make use of different types of inheritance.
A pseudo-classical inheritance. Here you build constructor functions and use new to create classes. This will look most like the typical class based OOP.
Prototypal inheritance. - This is what many of the other answer referred to.
Functional inheritance. - In this mode you make use of closures, anonymous functions, and strategic returns to create truly private and protected variables.
There's a fair amount of cross over among these types. Suffice it to say that Javascript is a very flexible and powerful language for OOP.
I'm just learning about OOP in JS as well. Here is an example of functional inheritance I put together:
jsFiddle
// Object constructor
var parent = function (initial) {
var that, privateNumber, hiddenVar;
that = {};
// Public variables
that.share = initial - 32;
// Public methods
that.getNumber = function () {
return privateNumber;
};
// Private properties
privateNumber = initial;
hiddenVar = "haha can't get me";
return that;
};
// Second object constructor that inherits from parent
var child = function (initial) {
var that, privateName;
// Inherit from parent
that = parent(initial);
// Public methods
that.getName = function () {
return privateName;
};
// Private poroperties
privateName = "Ludwig the " + initial + "th";
return that;
};
// Create objects
var newPar1 = parent(42);
var newPar2 = parent(10);
var newChild1 = child(0);
var newChild2 = child(100);
// Output on the jsFiddle page refed above: http://jsfiddle.net/ghMA6/
http://msdn.microsoft.com/en-us/magazine/cc163419.aspx
http://www.dustindiaz.com/namespace-your-javascript/
http://vimeo.com/9998565
frameworks for oop js
http://jsclass.jcoglan.com/
http://www.prototypejs.org/
Pluralsight - JavaScript for C# Developers - Shawn Wildermuth - 2h 5m
JavaScript Basics
JavaScript Functions
Object-Oriented JavaScript
Practical Application
and
Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries - 356 pages -2008 -packed publishing
Yes. It is possible. I have ever using the Script# to build javascript application, It allow you writing C# code, and translate to JavaScript.
it is an good experience, especially for large project, it will force your thinking in the OOP way to order your code.
The tool can be found at: (it is open source but write by an Microsoft employee)
http://scriptsharp.com
If you are not familiar with C# you can also find the similar tool for writing javascript in Java.
And if you don't want to using those too, you can investigate how it convert the code to understand how it implement the OOP feature.
Here is an example of accomplishing an OO structure in javascript that is utilizing a library(not required, recommended)
//Create and define Global NameSpace Object
( function(GlobalObject, $, undefined)
{
GlobalObject.PublicMethod = function()
{
///<summary></summary>
}
GlobalObject.Functionality = {}
}) (GlobalObject = GlobalObject || {}, jQuery);
//New object for specific functionality
( function(Events, $, undefined)
{
//Member Variables
var Variable; // (Used for) , (type)
// Initialize
Events.Init = function()
{
///<summary></summary>
}
// public method
Events.PublicMethod = function(oParam)
{
///<summary></summary>
///<param type=""></param>
}
// protected method (typically define in global object, but can be made available from here)
GlobalObject.Functionality.ProtectedMethod = function()
{
///<summary></summary>
}
// internal method (typically define in global object, but can be made available from here)
GlobalObject.InternalMethod = function()
{
///<summary></summary>
}
// private method
var privateMethod = function()
{
///<summary></summary>
}
Events.PublicProperty = "Howdy Universe";
}) (GlobalObject.Functionality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )
// Reusable "class" object
var oMultiInstanceClass = function()
{
// Memeber Variables again
var oMember = null; //
// Public method
this.Init = function(oParam)
{
oMember = oParam;
}
}
The strength to this is that it initializes the Global object automatically, allows you to maintain the integrity of your code, and organizes each piece of functionality into a specific grouping by your definition.
This structure is solid, presenting all of the basic syntactical things you would expect from OOP without the key words.
There are even some ingenious ways to set up interfaces as well. If you choose to go that far, a simple search will give you some good tutorials and tips.
Even setting up intellisense is possible with javascript and visual studio, and then defining each piece and referencing them makes writing javascript cleaner and more manageable.
Using these three methods as needed by your situation helps keep the global namespace clean, keep your code organized and maintains separation of concerns for each object.. if used correctly. Remember, Object Oriented Design is of no use if you don't utilize the logic behind using objects!

How is a functional programming-based JavaScript app laid out?

I've been working with node.js for a while on a chat app (I know, very original, but I figured it'd be a good learning project). Underscore.js provides a lot of functional programming concepts which look interesting, so I'd like to understand how a functional program in JavaScript would be setup.
From my understanding of functional programming (which may be wrong), the whole idea is to avoid side effects, which are basically having a function which updates another variable outside of the function so something like
var external;
function foo() {
external = 'bar';
}
foo();
would be creating a side effect, correct? So as a general rule, you want to avoid disturbing variables in the global scope.
Ok, so how does that work when you're dealing with objects and what not? For example, a lot of times, I'll have a constructor and an init method that initializes the object, like so:
var Foo = function(initVars) {
this.init(initVars);
}
Foo.prototype.init = function(initVars) {
this.bar1 = initVars['bar1'];
this.bar2 = initVars['bar2'];
//....
}
var myFoo = new Foo({'bar1': '1', 'bar2': '2'});
So my init method is intentionally causing side effects, but what would be a functional way to handle the same sort of situation?
Also, if anyone could point me to either a Python or JavaScript source code of a program that tries to be as functional as possible, that would also be much appreciated. I feel like I'm close to "getting it", but I'm just not quite there. Mainly I'm interested in how functional programming works with traditional OOP classes concept (or does away with it for something different if that's the case).
You should read this question:
Javascript as a functional language
There are lots of useful links, including:
Use functional programming techniques to write elegant JavaScript
The Little JavaScripter
Higher-Order JavaScript
Eloquent JavaScript, Chapter 6: Functional Programming
Now, for my opinion. A lot of people misunderstand JavaScript, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml look completely different). JavaScript is not object-oriented, it is actually a prototype-based language. It doesn't have classes or classical inheritance so shouldn't really be compared to Java or C++.
JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as partial application (currying).
Let's take an example (using sys.puts from node.js):
var external;
function foo() {
external = Math.random() * 1000;
}
foo();
sys.puts(external);
To get rid of global side effects, we can wrap it in a closure:
(function() {
var external;
function foo() {
external = Math.random() * 1000;
}
foo();
sys.puts(external);
})();
Notice that we can't actually do anything with external or foo outside of the scope. They're completely wrapped up in their own closure, untouchable.
Now, to get rid of the external side-effect:
(function() {
function foo() {
return Math.random() * 1000;
}
sys.puts(foo());
})();
In the end, the example is not purely-functional because it can't be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.
I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:
var Square = function(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
function getArea(square) {
return square.w * square.h;
}
function sum(values) {
var total = 0;
values.forEach(function(value) {
total += value;
});
return total;
}
sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) {
return getArea(square);
})));
As you can see, using objects in a functional language can be just fine. Some Lisps even have things called property lists which can be thought of as objects.
The real trick to using objects in a functional style is to make sure that you don't rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a new object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).
I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for you.
You have to understand that functional programming and object oriented programming are somewhat antithetical to each other. It's not possible to both be purely functional and purely object oriented.
Functional programming is all about stateless computations. Object oriented programming is all about state transitions. (Paraphasing this. Hopefully not too badly)
JavaScript is more object oriented than it is functional. Which means that if you want to program in a purely functional style, you have to forego large parts of the language. Specifically all the object orient parts.
If you are willing to be more pragmatic about it, there are some inspirations from the purely functional world that you could use.
I try to adhere to the following rules:
Functions that perform computations should not alter state. And functions that alter state should not perform computations. Also, functions that alter state should alter as little state as possible. The goal is to have lots of little functions that only do one thing. Then, if you need to do anything big, you compose a bunch of little functions to do what you need.
There are a number of benefits to be gained from following these rules:
Ease of reuse. The longer and more complex a function is, the more specialized it also is, and therefore the less likely it is that it can be reused. The reverse implication is that shorter functions tend to more generic and therefore easier to reuse.
Reliability of code. It is easier to reason about correctness of the code if it is less complex.
It is easier to test functions when they do only one thing. That way there are fewer special cases to test.
Update:
Incorporated suggestion from comment.
Update 2:
Added some useful links.
I think, http://documentcloud.github.com/underscore/ should be nice fit for what you need - it provides the most important higher-order functions for functional programming and does not has client-side functions for DOM manipulation which you don't need for server side. Though I don't have experience with it.
As a side note: IMHO primary feature of functional programming is Referential transparency of a function - function result depends only on its parameters - function does not depend on changes on other objects and does not introduce any change except its result value. It makes it easy to reason about program's correctness and very valuable for implementing of predictable multi-threading (if relevant). Though JavaScript is not the bet language for FP - I expect immutable data structures to be very expensive performance-wise to use.
So 2 things to point out ,
In your first example your variable would not be leaking into the global area and is the way it should be done , try to never use variables without declaring them i.e. test = 'data' would cause data to leak into the global area.
Your second example is correct as well , bar1 and bar2 would only be declared on the Foo object.
Things to keep in mind try not to overuse prototyping since it applies to every object that you create , this could be extremely memory intensive depending on how complex your objects are.
If you are looking for a app development framework , have a look at ExtJs. Personally I think it would fit perfectly into the model you are trying to develop against. Just keep in mind how their licensing model works before getting heavily invested in it.

Categories