Not necessarily necessary

When I started learning java, I was coming from a world of pascal, delphi and vb, so I believed there are a lot of things in java that are not necessary. As my experience with the language grows, I started seeing things in a different light. I will name some of the things I thought were not neccesary then, and then I will try and explain why I now think they are.

getters and setters. Why use getters and setters. I could make all my members public and just read them like that instead of using getters and setters. And for as long as I can remember this is how I do my things. Then one day, as part of a bigger API, I needed to write a user class. The illumination started when I found out that the requirements are these: The user of the API will supply the password in string and we will store the hash value. Also when he requests the password, we should reset the one in the db, generate a new one, store the hash and return the string to him.

As usual I wrote a helper class that does that. The problem is when you want to create a new user, you give the String password and call a save method. Then in the save method I convert the string to md5 and store it (and that works fine), but when you say user.getPassword(), it should return a new password hash and all that. I was momentarily trapped. That was when I remembered getters and setters. The final user class looks like this

public class User {

String password;

String username;

public User(String username, String password) {

this.setUsername(username);

this.setPassword(password);

}

.

.

public void setPassword(String password) {

this.password = md5hash(password);

}

public String getPassword() {

return newPasswordMd5Hashed();

}

}

Getters and Setters were introduced so as to overcome this kind of problem I believe. When you want to do something special at the point of accessing a variable. It is like overloading the = operator in c++.

Access Modifiers: Some days ago, I posted a joke on my facebook page. This is it.

A php programmer walked up to a java programmer and said “java is full of crap. The chief of these being what u guys call access modifiers…public, private, protected..etc. why have all that crap”. The java programmer looked up and said “lets assume for a second that I am God, and I make your wife public” End of Discussion.

The joke however is on java programmers. Thats talk for another day. I used to be like that php guy. Why all these access modifiers. All my members and methods are public, so I really dont need them(This is where I prefer scala, the default is public, unlike java where the default is private). But my User class above also taught me the need for access modifiers. The user class is actually a base class for some other classes, We have the ManagedUser, TimedUser etc. If I make the password field public, then the programmer that is using the API can as well just use the = to assign value to it. This will have very un-desirable effects. If I make it private the programmer wont, but neither will ManagedUser and TiimedUser. I need them to also be able to modify this field because we store the passwords differently for a managedUser and timedUser. I need to make the field protected.

When developing API’s that will be used by other people, access modifiers are your friend my friend.

Wrapper classes: why have int and Integer, boolean and Boolean, double and Double. Who needs wrapper classes anyway. But that is a lie, sometimes you will need them. One day you will need to write a method that takes an object as an arguement or that returns an object. primitives like int,boolean,double are not objects. You will need to have wrapper classes. What I wanted to do when this dawned on me was simple. Pass an Object to a method. This Object could either be an Object or a primitive. What do I do? Simple, use wrapper classes.

public void done(Object i) {

if(i instanceof Integer) {

.

.

.

} else if(i instance of Double) {

.

.

.

} else {

.

.

.

}

}

Abstract Classes: Now this one I didn’t get until very later in my java journey. Abstract classes, Interfaces etc. But let me explain it to you in simple terms. You will need these features if you want classes to fufil a particular contract. For example, I was writing a class Store as part of a J2ME Database Management API. Now any POJO that must be persisted must have two methods toByteArray() and fromByteArray(). If I were doing J2Se, I could have used reflections, I didnt have this luck with J2ME CLDC. So I rememebered Abstract classes and interfaces. So I make sure every persistable class must extend and abstract class I called StoreBase. The class itself contains methods toByArray() and fromByteArray() without any body definition. Any class that extends StoreBase can be persisted, but it must have definition for those methods, else your code wont even compile. EOD.

EDIT: The default access modifier for java is packaged and not private as erroneously stated above.  Thanks to Jose Ayerdis

public class User {
String password;
String username;
public User(String username, String password) {
this.setUsername(username);
this.setPassword(password);
}
.
.
.
.
public void setPassword(String password) {
this.password = md5hash(password);
}
public String getPassword() {
return newPasswordMd5Hashed();
}
}
Advertisements

4 Comments »

  1. Thomas Bakketun said

    Getter and setters are very useful for hiding implementation details that the user of an API does not have to be bothered with. However in your example the fact that the current password of a user can not be read is clearly part of the public API. Hiding the operation of generating a new password and returning it’s hash violate the getter/setter idiom. Getters should always be idempotent, ie. calling the getter twice, with any other code in between, should always return the same value. Violating this idiom will sooner or later confuse some user of the API.

    An example of proper use of a getter would be lazy loading in a database persistense system. A query might return “hollow” objects containg just the primary key. Whenever a property getter is accessed the data is automatically loaded from the database, and possibly cached in a hidden field of the object.

    Please note that when an object is shared between different threads or processes, calling the same getter twice is not garanteed to return the same value. However it is still idempotent since it’s not the act of calling the getter that is changing the property’s value.

    I would caution against the use of access modifiers as a means of keeping information secret. This will only work when the untrusted code is 100% garanteed to run in a sandbox. If it’s not there are many ways of getting access to a private field, eg. by using the debugging functionality of the JVM.

    As you correcly state, wrapper classes are need because the primitive types in Java are not objects. But why are they not? In programming languages such as Smalltalk and Lisp everything is an object. As far as I know effecieny problems related to this had been solved long before Java was created.

  2. “This is where I prefer scala, the default is public, unlike java where the default is private”

    What do you mean the default access modifier is private?? the default access modifier in java is called packaged-modifier and it work under the package level access.

    PD. nice post.

    • @ Jose Ayerdis That statement is not correct, Thanks for the correction. I would have edited the post, but then your comment would make no sense anymore, so I will leave it like that.

  3. You can always edit it at the end, a correction from the statement. Remember not every one read the Comments. Rule 90-9-1. http://www.90-9-1.com

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: