Terence hacks

Life as a wannabe programmer

Monthly Archives: December 2010

Code Refactoring

In the real world, you’re not a one-man team like you once were during college (because apparently, it’s cheating in your professor’s eyes). You will work with other people when developing software. If that’s the case, it’s inevitable that those other people you’re working with will also be looking at your code. Not only that, they’ll also be working with the code that you will write.

One of the things a developer must strive for is better code. What do I mean by better code? Take a look at the code you’re working on right now. If you show it to other programmers, will they be able to figure out how your code works immediately without having to look at it extensively?

Does your code have too much comments? Do most of the comments just explain the “what” and not the “why” of the code? It’s not that I have anything against using comments. I simply believe that comments should only be used to indicate why you did the following approach in writing the code to which to comment points to instead of what the code does.

Do you find yourself repeating a lot of code in your software?

Take a look at some of the codes that you made in the past. Do you still understand how everything works?

If you answered No to the first and last question and Yes to the rest of the questions, then you, dude, have bad code. It’s time to give your code a makeover a.k.a. code refactoring.

Code Refactoring, by definition of Wikipedia, is the process of changing a program’s source code without affecting its external functional behavior to improve some of the non-functional aspects of the program. You usually change it for the better.

Code Refactoring has the following benefits:

  1. You make your code more readable to yourself and others as well.
  2. Since it makes your code more readable, it makes your software easier to maintain and extend.
  3. More often than not, refactoring results to lesser lines of code, so it actually saves you some bytes of memory when refactoring
  4. It results to lesser comments in your code since the code is pretty much self-explanatory already.
  5. It saves you from being screamed at by your fellow programmers for showing them bad code.

To further my discussion on the concept of code refactoring, let me show you a basic example of how refactoring works.

We’ll use the code that we made in my last entry. Here are both the source files we made:

Car.java

public class Car {
	private String brand;
	private String color;
	private String name;
	private int speed = 0;
	private int gear = 1;

	public String getBrand() {
		return this.brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getColor() {
		return this.color;
	}

	public void setColor(String color) {
		color = color.replaceAll("[0-9]", "");
		this.color = color;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getSpeed() {
		return this.speed;
	}

	public void setSpeed(int speed) {
		this.speed = speed;
	}

	public int getGear() {
		return this.gear;
	}

	public void setGear(int gear) {
		this.gear = gear;
	}
}

CarDemo.java

public class CarDemo {
	public static void main(String[]args) {
		Car myCar = new Car();

		myCar.setBrand("Porsche");
		myCar.setColor("White123");
		myCar.setName("911 GT3");
		myCar.setSpeed(120);
		myCar.setGear(2);

		System.out.println("The car is a " + myCar.getColor() + " " + myCar.getBrand() + " " myCar.getName() + ".");
		System.out.println("The car is runs at " + myCar.getSpeed() + " miles per hour on gear " + myCar.getGear());
	}
}

Let’s focus our attention to CarDemo.java. Look at how we invoked the Car class in this example. You first declare and instantiate an object then you have to set values to them one by one. Isn’t it too much of a hassle to create objects with this approach? I’m pretty lazy to have to write all these so it’s only natural to find a way to do them in shorthanded way.

Speaking of laziness, did I tell it’s one of the virtues of a good programmer? No, not that kind of laziness where you bum around and do nothing. Here’s the definition of laziness according to the book, ProgrammingPerl:

Laziness: The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don’t have to answer so many questions about it. Hence, the first great virtue of a programmer. Also hence, this book.

Now that we know how being lazy is a good trait for a programmer, we need to do something about how we create Car objects.

Let’s say one of your co-workers, Bob, who also happens to be your team mate in the program you’re working on, wanted Car objects to have specific default values for their attributes when he creates them so he can mass produce them (Well, mass producing is a bit of an exaggeration but just go with it). He told you that he only wants to specify the brand and name of the car and he wants every car that he makes to have it’s default color set to “White”, its speed set to 0 (obviously) and its gear set to 1. How will you do this?

When we talk about creating objects, we’re talking about the constructor, specifically. Since we didn’t explicitly make a constructor for the Car class in the last entry, let’s make one for Bob:

public Car (String brand, String name) {
	setBrand(brand);
	setColor("White");
	setName(name);
}

What this constructor does is get the values of its brand and name argument and assign them to the object using its setter methods. If you looked at it closely, you’ll notice that we didn’t call the setter for speed and gear. Why? Take a look at Car.java again. We already assigned default values for the attributes, speed and gear.

private int speed = 0;
private int gear = 1;

Every instance of Car will possess these assigned values by default when you create them.

If you still remember Bob’s requirements, you’ll see that it’s exactly what he wanted. If we go to CarDemo.java right now, we can now create objects in this fashion:

Car bobsCar = new Car("Mitsubishi", "Lancer EX");

Isn’t this convenient? We can now create objects and assign values to their attributes in a single line. If we want to change them, we can just invoke the setter methods and be done with it. This will now be our new CarDemo.java:

public class CarDemo {
	public static void main(String[]args) {
		Car bobsCar = new Car("Mitsubishi", "Lancer EX");

		System.out.println("The car is a " + bobsCar.getColor() + " " + bobsCar.getBrand() + " " bobsCar.getName() + ".");
		System.out.println("The car is runs at " + bobsCar.getSpeed() + " miles per hour on gear " + bobsCar.getGear());
	}
}

This will be the output:

The car is a White Mitsubishi Lancer EX.
The car runs at 0 miles per hour on gear 1.

Will you look at that? We shrunk that long 6-liner code into just one line. See how convenient code refactoring is?

We can still shrink the main method of CarDemo.java into just 2 lines. Look at the rest of the code, did you notice how long it is to write the code to print the values of the object to the screen? Well, not really, but what if you made a million objects and you have to print all of their values to the screen? Wouldn’t that be a nightmare?

If you find yourself typing the same code multiple times, you can turn all those repeated code into methods. That way, you only have to type the code once and just call it when you need it.

Let’s cut and paste our printing code to Car.java, put it inside a method, and tweak it a little bit so it would suit our needs:

public void printInformation() {
	System.out.println("The car is a " + getColor() + " " + getBrand() + " " getName() + ".");
	System.out.println("The car is runs at " + getSpeed() + " miles per hour on gear " + getGear());
}

I’m pretty sure you’ll have a good idea of how CarDemo.java would look right now, but I’ll still show it to you:

public class CarDemo {
	public static void main(String[]args) {
		Car bobsCar = new Car("Mitsubishi", "Lancer EX");

		bobsCar.printInformation();
	}
}

We shrunk it into 2 lines (Well, 3, actually, because of the whitespace)! It will still produce the same output as last time, but now it takes less effort to do the same thing. Isn’t code refactoring wonderful? Now you will be saved from getting screamed at by your co-workers.

Access Modifiers in Java

As I’ve said in my previous entry, classes should never be invoked like this:

myCar.brand = "Porsche";
myCar.color = "Black";
myCar.name = "911 GT3";
myCar.speed = 120;
myCar.gear = 2;

System.out.println("myCar is a " + myCar.color + " " + myCar.brand + " " + myCar.name + ".");
System.out.println("myCar is running on " + myCar.speed " miles per hour on just gear " + myCar.gear ".");

The reason behind this is because too much data is exposed to the wild and they’re very prone to errors if you followed this approach.

Let’s say you wanted to change myCar’s color attribute to something different, say, White? Unfortunately, you’re pretty nervous at the moment and you entered “White123″ instead. Your professor/boss saw this little error in the program and he humiliated you in front of everyone over the stupid error. “Colors don’t have numbers on their names!”, he said while laughing. Don’t ask me why someone would laugh over something so trivial.

We could have prevented this tragic incident if we validated the data first before setting it as the attribute’s value. Let’s modify the class that we made in the previous entry and make a method that validates data and removes non-alphabet characters to make up for the mistake that we’ve done in the past.

class Car {
	String brand;
	String color;
	String name;
	int speed = 0;
	int gear = 1;
	
	void setColor(String color) {
		color = color.replaceAll("[0-9]", "");
		this.color = color;
	}
}

Now that we have a method that removes all the non-alphabet characters, you might think that this solution will finally save you from the humiliation that you experienced, right? Not really. Why, you ask? Well, we can still call the attribute directly like this:

myCar.color = "White123";

So you might be thinking, “What the heck did we make that method for if we can still ignore the method and assign a value to the attribute directly like before?”.

In Java, we can limit access to variables and methods through the use of Access Modifiers. There are 4 access modifiers in Java: Public, Private, Protected, and Default (No modifier).

Since I’m too lazy to define everything for you, let me quote this tutorial’s definition on all 4 access modifiers:

Public access modifier

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

Private access modifier

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

Protected access modifier

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

Default access modifier

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Now that we’re familiar with access modifiers, let’s modify the class once again. As a convention, we should declare class attributes as private variables to prevent outside classes from messing with them directly.

class Car {
	private String brand;
	private String color;
	private String name;
	private int speed = 0;
	private int gear = 1;
}

Now that we made the attributes of the Car class private, how are we going to access them from outside the class now? We solve this by creating getter and setter methods inside the class and giving them the public access modifier.

class Car {
	private String brand;
	private String color;
	private String name;
	private int speed = 0;
	private int gear = 1;
	
	public String getBrand() {
		return this.brand;
	}
	
	public void setBrand(String brand) {
		this.brand = brand;
	}
	
	public String getColor() {
		return this.color;
	}
	
	public void setColor(String color) {
		color = color.replaceAll("[0-9]", "");
		this.color = color;
	}
	
	public String getName() {
		return this.name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getSpeed() {
		return this.speed;
	}
	
	public void setSpeed(int speed) {
		this.speed = speed;
	}
	
	public int getGear() {
		return this.gear;
	}
	
	public void setGear(int gear) {
		this.gear = gear;
	}
}

What’s the logic behind this? Remember that method we created to validate the color’s name and remove any non-alphabet characters? We turned that method into a setter for the color attribute. Since we turned the color attribute into a private variable, you and other programmers will be forced to use the setter if you want to change the value of color. When making setter methods, it’s a good practice to put your validation inside of them to make sure that data will be handled accordingly.

Aside from setters, you need to make getter methods as well to retrieve the value of the attributes since there’s no way for you to retrieve them directly because of the private access modifier.

Now that we have a decent Car class, let’s make another class to create Car instances and invoke their attributes and methods:

class CarDemo {
	public static void main(String[]args) {
		Car myCar = new Car();
		
		myCar.setBrand("Porsche");
		myCar.setColor("White123");
		myCar.setName("911 GT3");
		myCar.setSpeed(120);
		myCar.setGear(2);
		
		System.out.println("The car is a " + myCar.getColor() + " " + myCar.getBrand() + " " myCar.getName() + ".");
		System.out.println("The car is runs at " + myCar.getSpeed() + " miles per hour on gear " + myCar.getGear());
	}
}

Notice how I still used “White123″ as the color’s new value? Since we made a validation for that earlier, we don’t have to worry about the numeric characters being included in the string. This will be the output of the program:

The car is a White Porsche 911 GT3.
The car runs at 120 miles per hour on gear 2.

What happens when we try to invoke the class attributes directly? Simple, we’ll get a compile error. That’s the reason why everyone will be forced to use the getter and setter methods. Capiche?

Classes and Objects in Java

DISCLAIMER: Do not use any of the code found in this entry for real life exercises. They do not adhere to the standards of OOP. I intentionally wrote wrong code in this entry for the sake of discussion. I will smack you in the face if you used the following code in real life exercises.

I’ve been trying to teach some of my classmates about the concepts of OOP, so I thought I’d turn them into a series blog posts for future reference. I’m also going through the process of re-learning Java and OOP in my Java class so I’m going to write about them to make sure I leave no holes unplugged.

OBJECTS

First of all, let’s talk about Objects. Objects are the core of OOP. I mean, why the heck would they call it Object-Oriented Programming if it wasn’t about Objects, right?

Objects in OOP are very similar to real-life objects. You could say that they’re based on them. Real-life objects have attributes and behaviors and Objects in OOP are modeled based on them. Let’s take a car for example: a car is an object, it has attributes (brand, color, name, speed, gear) and behaviors (accelerate, decelerate, change gear).

In OOP, we create objects based on what they are in real life. Objects may vary in complexity based on what they are in real life because some objects may have complicated behaviors (may involve complicated math or algorithms) or attributes (having other objects as their attributes). Understanding objects is the key to learning and thinking in OOP.

CLASSES

Let’s say you went outside for a walk and you saw John doing his usual rounds of jogging in the neighborhood. Behind him are Bob and Mary who are running a wee bit slower than John because they’re both still in the process of reducing their weight. You decided to jog with them and you saw that hot girl, Samantha, with her friends, Chloe and Alicia, while jogging. After jogging, you decided to go home and reflect on what happened while you were outside. While reflecting, you realized that you saw a lot of people today. Sure, they all have their differences, but they all have one thing in common: they’re people.

Based on the scenario above, we can safely say that John, Bob, Mary, Samantha, Chloe, and Alicia are objects. One thing they have in common is that they’re all people; human beings. If you haven’t guessed what Classes are yet, they’re basically an abstraction of a set of objects. Based on this definition, we can say that the people mentioned above are objects of the class, People (or Person if we want to be specific).

Another good analogy for Classes are houses. People can build hundreds of houses using just one blue print. Houses are the objects, the blue print is the class.

Now that we understand what Classes are, let’s try to make a class. It should look something like this:

class Car {
	String brand;
	String color;
	String name;
	int speed = 0;
	int gear = 1;
}

This is, technically, a complete class already. If you look at it pretty closely, you’ll notice that it’s a representation of the car example that I used earlier. In Java, instead of attributes, it has fields (brand, color, name, speed, gear). Isn’t that easy to understand?

Right now, we have the blue print for making cars, but just having the blue print isn’t enough. We have to start building them to make cars. Let’s make another class that creates car objects and invokes their fields and manipulates them:

class CarDemo {
	public static void main(String[]args) {
		Car myCar = new Car();
		Car yourCar = new Car();
		
		myCar.brand = "Porsche";
		myCar.color = "Black";
		myCar.name = "911 GT3";
		myCar.speed = 120;
		myCar.gear = 2;
		
		yourCar.brand = "Volkswagen";
		yourCar.color = "Green";
		yourCar.name = "Beetle";
		yourCar.speed = 10;
		yourCar.gear = 5;
		
		System.out.println("myCar is a " + myCar.color + " " + myCar.brand + " " + myCar.name + ".");
		System.out.println("myCar is running on " + myCar.speed " miles per hour on just gear " + myCar.gear ".");
		
		System.out.println("yourCar, however, is a " + yourCar.color + " " + yourCar.brand + " " + yourCar.name + ".");
		System.out.println("yourCar is running on " + yourCar.speed " miles per hour on gear " + yourCar.gear " already. Yuck!");
	}
}

As I’ve said in the disclaimer earlier, this is the wrong way to code. I did this so you can be aware of what is wrong and right in OOP. I’ll show you how to code the right way in my next entry.

The output of this program will look like this:

myCar is a Black Porsche 911 GT3.
myCar is running on 120 miles per hour on just gear 2.
yourCar, however, is a Green Volkswagen Beetle.
yourCar is running 10 miles per hour on gear 5 already. Yuck!

This is me trying to pull off a car joke even though I barely know anything about cars. Kidding aside, let’s go over the code one by one:

Car myCar = new Car();
Car yourCar = new Car();

Here, we create 2 instances/objects of the class, Car. This is the way to create objects in Java:

[classname] [variablename] = new [constructor];

This statement has 2 parts. On the left hand side, we declare an object. Take note that it hasn’t been officially created yet since we only did a declaration. On the right hand side, this is the part where we construct the object and then assign the newly constructed object to the declared object on the left hand side.

I’m a bit skeptical about teaching you the syntax since I wanted to teach you concepts instead of language-specific syntax. Anyway, let’s move on to the next one:

myCar.brand = "Porsche";
myCar.color = "Black";
myCar.name = "911 GT3";
myCar.speed = 120;
myCar.gear = 2;

yourCar.brand = "Volkswagen";
yourCar.color = "Green";
yourCar.name = "Beetle";
yourCar.speed = 10;
yourCar.gear = 5;

In this chunk of code, I’ve manipulated the fields of both myCar and yourCar objects and assigned values to them.

System.out.println("myCar is a " + myCar.color + " " + myCar.brand + " " + myCar.name + ".");
System.out.println("myCar is running on " + myCar.speed " miles per hour on just gear " + myCar.gear ".");
		
System.out.println("yourCar, however, is a " + yourCar.color + " " + yourCar.brand + " " + yourCar.name + ".");
System.out.println("yourCar is running on " + yourCar.speed " miles per hour on gear " + yourCar.gear " already. Yuck!");

Here, we call the value of the fields myCar and yourCar and print them on the screen. In Java, you call them by [objectName].[fieldName or methodName].

In conclusion, Objects are the core of OOP, they are also modeled according to real-life objects, and Classes are the blue prints for making objects. Understanding how objects and classes work are the key to having an OOP state of mind. This is very important when doing OOP.

In my next entry, we’ll go over the right way of coding in OOP. We will also cover the advanced stuff when it comes to classes and objects.

Follow

Get every new post delivered to your Inbox.