Browsing Tag

object oriented programming

Programming Languages, Python

A Lesson about History, Objects, Classes, Time and Python

December 3, 2014

Object Oriented Programming (OOP) became very popular in the last couple of decades. I do find that a lot of people can tell me what an Object is, but few know what is the difference between a class and Object. In fact, many use them interchangeably. So let us clear the air a bit. Here is a short nice story about the evolution of programming. Sort of.

In the dawn of programming we had variables. For a time it was good. Char, Int, Sting, Float all run along nicely. For us programmers that was not enough. We like to make life more complex than that. So we start writing code. A lot of code. Code that uses a lot of variables. As programmers, we love looking for patterns. Slowly we found one. We are writing the same code, over and over. Now, we the coders are a lazy bunch. We like to be challenged, not to write the same lines of code again and agin. So, we came up with the notion of functions. Function are in fact awesome!. for a long time, one could do anything with a few variables and functions. Not to long after, we found ourself copying entire library of functions and files were getting really big. then we came up with the idea of modules, or libraries if you will. How awesome is it to import a whole battery of functions at your finger tips? Most programmers thought this was the best thing since slice bread. Not the we were around back then. After a while, we thought, you know what, how about we put the data (variables) and the methods (functions) together (encapsulation) and use it as one thing, lets call it an object. Yay! Objects.

This of course is a very short description of what actually happy. Hopefully you go the point. So what are objects? They are instantiation (from the word instants) of Classes with particular attributes and behaviors. Attributes refer to the object variables, behaviors to it’s functions. In most cases, but not all, the behaviors involve the attributes. Classes are the code, the recipe for an Object. 1 Class can produces as many Objects as you computer memory can hold. Having the attributes and behaviors together gives a sense of encapsulation. In OOP, the Object attributes are accessed using getters and setters (Access Modifiers). Getters retrieve a copy of the attribute. Setter overwrite the attributes. Setters and Getters are behaviors that help keep the information help by the Object correct. That means that if there is and attribute of a class that has to be a number between 0 and 10. The setter will not allow any other value to be stored. OOP gives us a sense of abstraction since we normally can’t see the code, but we don’t need to. There are a couple of more terms you should hear for now, inheritance and polymorphism. Inheritance means a class can be extended by another class to enhance functionality. Polymorphism means “of many forms”. This applies to OOP since we can have man ors of a single class.

Wow that was a lot to take in all at once. It is time for an example. What better language to use then our favorite, Python. Yay.

We are going to work on a time module that could be helpful for future programs. we are going to start from our basic class, an instant. For our purposes, an instant of time is date and time up to minute accuracy. That means that we are going to write a class, in Python, for an instant. We will have a date (year, month, day) and hour (hour, minute) as our class attributes. To set this up will have to use some special syntax. It will look like this:


class Instant:

	def __init__(self,year,month,day,hour,minute):
		self.year = year
		self.month = month
		self.day = day
		self.hour = hour
		self.minute = minute

Ok. We start with the keyword class, followed by the class name. then we define a function named __init__. This is a special function called a constructor. This function has to be in every class in order to create an object. It is only called once to set the Object up. As the function arguments we pass in self and the reminder of the variables we want to pass in to set the Object up. Some leagues allow multiple constructors. Python does not. We will pass self from this point to every function in the class, so that they can have access to the Objects attributes. Note that self.year is not the same as year. Self.year is the class variable, while year is a function variable.

To use this class, or to get an object, we can use the following code:


def main():

	i = Instant(2014,12,3,2,11)
	print i

if __name__== "__main__":
	main()

If you run it, you will get something that looks like this:

wpid-instantclasspython-2014-12-3-01-39.png

That number is a memory location where our object is stored. If we crated more Object they all will have different hex memory addresses. This is useful to know but not ver particle. If we want to debug or do anything we will need to print out the individual attributes within the class. Thankfully, there is a special function we can write called a to-string. It is noted in Python __str__ and will be called when asked to print the object. For our example the code will look like this:


def __str__(self):
	return  "Year: " + str(self.year) + " " + \
	   	   "Month: " + str(self.month) + " " + \
		   "Day: " + str(self.day) + " " + \
		   "Hour: " + str(self.hour) + " " + \
		   "Minute: " + str(self.minute)

And the output (for the same main() function from before):

wpid-instantstrpython-2014-12-3-01-39.png

You could be fancy and change the function to return something else like:

wpid-instantstrpython2-2014-12-3-01-39.png

if you really want you could play around with colors and strings in Python all that you want, but that is not the point. Now we are going to add some getters and setters. Getters are easy, the just retrieve information, so a getter for year looks like this:


def getYear(self):
	return self.year

We define getters to avoid direct access to class attributes. However, if we go back to out main we can issue a command ‘print i.year’ without an error. In order to avoid that we will add 2 underscores to the attribute name in the constructor. That will make the attribute private so only within the class using self.year we can access thee variable. So our new constructor will look like this:


def __init__(self,year,month,day,hour,minute):
	self.__year = year
	self.__month = month
	self.__day = day
	self.__hour = hour
	self.__minute = minute

And our getter will look like this:


def getYear(self):
	return self.__year

And if we wanted to print just the year, we would use it like this:


i.getYear()

Ideally, we would have a getter for every attribute in the class. That is not a must, just a friendly suggestion. Now we can move to the setters. In a setter, we will put a new value in the Object attribute. We could start with a simple method like this:


def setYear(self,year):
	self.__year = year 

This would work. However, normally it is a good idea to check what the user is putting as a year. In Python, variables do not have a declared type. That means that a user can end up passing in something like a String, Boolean or another Object for all we now. In addition, even if the user entered a number, what if it is a negative number? for our purposes, we are going to say that a year must be between 1900 and 2100. So our new setter will look like this:


def setYear(self,year):
	if not ((type(year) != type(2000)) or (year < 1900) or (year > 2100)):
		self.__year = year 

If you were following along you would notice a problem. When we first set self.year we never checked that the value of year upholds the setter standards. In order to correct this we would need to modify our constructor to do the same check. This does get tricky, but it is necessary to maintain the integrity f the Object data. We will modify our constructor set year line to look now like this:


if not ((type(year) != type(2000)) or (year < 1900) or (year > 2100)): self.__year = year
else: raise Exception('Year is not in correct format or out of range')

This means that for each variable we will need to similar work an add a getter and setter. Assuming we got all this done we could move forward. There are 3 more function we will want to added to our instant class:

  1. beforeMe
  2. afterMe
  3. addToMe

The first 2 functions are booleans that take another instant and compare the 2 to see if the other instant is before the current one. Similar idea with afterMe. The method add to me, will take a quantity and add it to instant. Lets take a look at the functions beforeMe and afterMe:

def beforeMe(self,other):
	if self.__year > other.getYear():
		return False
	elif self.__year == other.getYear():
		if self.__month > other.getMonth():
			return False
		elif self.__month == other.getMonth():
			if self.__day > other.getDay():
				return False
			elif self.__day == other.getDay():
				if self.__hour > other.getHour():
					return False
				elif self.__hour == other.getHour():
					if self.__minute > other.getMinute():
						return False
	return True

def afterMe(self,other):
	return not self.beforeMe(other)

I did get a little laze. I could have re-wrttien afterMe as a reverse to beforeMe, this seemed smoother to me. This function really should be straight forward. Lets move on to the next one. In the next one, we can add X minutes to an instant. That is cool and useful because it does require a little math. Let us first take a look at how this is done:


def add(self,min):
	if type(min) != type(1): raise Exception("Invalid minutes to add")
		self.__minute += min
		if self.__minute > 60:
			self.__hour += self.__minute / 60
			self.__minute = self.__minute % 60
			if self.__hour > 24:
				self.__day += self.__hour / 24
				self.__hour = self.__hour % 24
				if self.__day > 30:
					self.__month += self.__day / 30
					self.__day = self.__day % 30
					if self.__month > 12:
						self.__year += self.__month / 12
						self.__month = self.__month % 12

Do note that at this point I am making a lot of assumptions. I did not account for leap years and odd months. This function should be re-wrriten better, but for our sake right now it serves it’s purpose. So after all this is said and done, we should end up with a very interesting class that represents and instant, or a moment if you will in time. That class could be used to create many Objects. Even objects that interact with each other since we can compare 2 instants using the beofreMe and afterMe functions. Maybe next time we can extend this class to be used for a TimePeriod and maybe even a meeting in a schedule book.

Here is a link to the complete instant class in Python in case you want to play around with it.

Problems, Programming Languages

The Basics Of Classes in Java

October 17, 2013

It has been a little while since I had a chance to write an article, so I figured I am way past due for one. Let us get started.

What are Classes? Classes are essentially blueprints. Much like a blue print for a coffee mug, house or a car. Classes contain a framework on which we can build an Object. Classes are the technical generic framework of an Object. So what are Objects? Well, the text book definition I tend to like is that Objects are instantiation of Classes. They are the “bringing to life” (if I may) of a Class. Let me try to put this into an example. A table in the most generic form would be a flat service supported by legs. This will be the Class. An Object of the table might be a kitchen table of hight h, width w, length l and has 4 rounded edges with round legs. The particulars of the Object are called attributes. We will get back to that in a little bit.

So what can Objects do for us? Well, the must be somehow useful, after all Java is an Object Oriented Programming Language and is by far the most in demand. Objects are useful because we can interact with them. We can use what we call behaviors, to make use of them. Going back to our example, what can we do with a table? We can put something on it and remove something form it. Maybe we can change it’s height by putting it on 4 bricks? I will admit when you think about it a table is a pretty simple Object, but when we see more examples we will see many more attributes and behaviors.

wpid-java-logo-2013-10-18-00-49.jpg

Before we get in to gory detail let us see more ways objects are useful. This following paragraph is mostly to convince you that Objects are indeed useful in any language. First, Objects allow us to create a hierarchy of an Objects that inherit information from their parents. What does that mean? It means that if for example we create a parent Object, call it Shape, we can create a child Object named Rectangle. The Object Shape might only have 1 attribute Name, but the Object Rectangle will have it’s parents attribute Name, and maybe some more information such as it’s sides lengths. Second, Objects allow us to encapsulate data. This means we can keep the internal of the Object hidden and keep the implementation as well as attributes hidden from another user. So in a nut shell I can write a program that uses an Object that I have no direct way to interact with it, aside from public methods. Third, because of encapsulation I can ensure the integrity of the attributes of an Object. For example, I can prevent anyone from leaving the Name of Shape empty. I know this is a little out there for someone that is just starting off, but like I said it is something you are going to have to learn and we will have to visit that later.

All this theory makes me want to code something up. How about that Rectangle class? Here is a problem formal definition:

Create a class Rectangle. The class has attributes length and width, each of which defaults to 1.0. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 1.0 and less than 10.0. Write a program to test class Rectangle.

This is a classic beginner problem and a good review/quiz problem. It shouldn’t take you longer than 10-15 min to figure something like this out. Lets try to work this out together. Like every other Computer Science problem, start by reading the problem at least twice and then start to figure out what is requested from you. Here is my list of requirements:

  1. Create a Rectangle class
  2. Rectangle has 2 attributes (or variables) length and width that are floating point numbers
  3. The attributes of Rectangle are initially set to 1.0.
  4. We need a getter and setter for each attribute
  5. The setter must validate that the number assigned to length or width is no less than 1.0 and no more than 10.0.
  6. Rectangle has to have a method to calculate perimeter and area.
  7. Write a main method that utilize Rectangle class and tests it’s functions.

Great. Now let us start with Java.

Number 1 is ease, create a Rectangle class. To do this we need the following code stored in a .java file with the same name as the class. In this case Rectangle.java.


public class Rectangle{

}

Well that was super easy. Now let us add the 2 attributes:


public class Rectangle{

	private double length;
	private double width;

}

Ok. That is still easy, but why is there the word “private” there? That is a variable modifier that tells Java what is the working scope of a variable or a method. There are 3 modifiers, private protected and public. Usually attributes of classes are private, at least in the beginning of programming. This is a whole other discussion by itself.

The next thing we need is called a constructor. A constructor is a method that is invoked when to Object is created. This is normally where the attributes are setup. The constructor has to have the same name as the class and does not have a return type like a normal function would have. Here is what our default constructor will look like for Rectangle.


public Rectangle(){
	this.length = 1.0;
	this.width = 1.0;
}

Notice that we used the modifier this to denote the class attribute and not a local variable length. This is not a must, but it will make you life easier and in some cases save you a lot of time figuring out why things are not working like you except. The constructor we have is the empty constructor. It is not a must, like I said. If you do not write a constructor, Java will inherit one from the generic Class definition. That means that nothing will happen beside Java giving your variable an address.

Moving forward (or downward) in our list we need a getter and setter for each attribute. Remember a few paragraphs ago I mentioned something about data integrity? This is where the getter and setters com in to play. They act as a buffer between the user and the values of the attributes. In the case of getters they just return the value (normally). In the case of setters we can modify the actual attribute only if it is an acceptable value. In our case we can write our setters such that if the values are less than 1.0 or more than 10.0 the value of the Object is not set. Let’s take a look:

Here are our getters:


public double getLength(){
	return this.length;
}

public double getWidth(){
	return this.width;
}

And here are the setters:


public void setLength(double length){
	if((length >= 1.0) && (length <= 10.0))           	this.length = length; } public void setWidth(double width){ 	if((width >= 1.0) && (width <= 10.0))
          	this.width = width;
}

That was not so bad, was it? Before we move on to testing we have to complete 1 more task, writing a method for computing perimeter and area. That should be really straight forward.


public double perimeter(){
	return 2 * (this.length + this.width);
}

public double area(){
	return this.getLength() * this.getWidth();
}

You will notice that in the perimeter method we used this to access the variables, while in the area method we used the getters. Both styles are ok and will yield the same results. This was done for educational purposes only.

So now we are done with our class and can move on to testing. Wrong! I highly recommend you take the time to write a debug toString() method. Why? you will thank me later. Here is my toString() for Rectangle:


public String toString(){
	return "Length: " + this.length +"\tWidth: " + this.width;
}

It may seem simple, but later when you are dealing with multiple classes, it is nice to just be able to print them. Let us try to actually use our class. We are going to use a Scanner for user input and standard user output (terminal screen). Here is a simple Main I put together. If you find it useful here is a link to Java Rectangle Class.


public static void main (String[] args)
{

	Scanner userInput = new Scanner(System.in);
	Rectangle r = new Rectangle();

	System.out.print("Enter a length >>> ");
	r.setLength(userInput.nextDouble());

	System.out.print("Enter a width >>> ");
	r.setWidth(userInput.nextDouble());

	System.out.println("The Rectangle with the following attributes: \n" + r);
	System.out.println("Has perimeter is:  " + r.perimeter() + " and area is:  " + r.area());

}

And the output:

wpid-java_rectangle_output-2013-10-18-00-49.png

That is all. Easy isn’t it?

Computer Programming I

Computer Programming I

September 4, 2012

After writing about the content of Computer Programming III and writing the assumptions for that, I had a friend take a look. The most obvious problem was that I didn't define part I and II. So the following is what I would use as a syllabus for Computer Programming I.

 

Please NOTE: The associated web pages with Computer Programming I are for absolute beginners. The key audience for these pages are people who want to start programming. Although some of the post may be relevant for non-beginners, please be patient when reading. As always if you find any errors, please do point them out via email or in the comments.

 

Assumptions

Going back to My first assumptions, the following assumptions still hold true.

Assumption #0: You can read and write.

Assumption #3: You have Internet access.

Assumption #4: MATH.

Assumption #5: Hardware & Software.

 

The main purpose of Computer Programming I is to peak your interest. By the end of the first programming class you should be at a point where Assumption #2: You want to know more is a constant. You will learn about what programming can do and what are the limitations. That being said, you will not get to a point where you need a super fast computer, or run out of memory. You might get the computer to freeze, but not because of computation. Before I get to the syllabus and the specific topics, the following are the topics in no particular order.

Topic #0: Basic Building Blocks. This is the most fundamental programming. types, conditionals, program flow, basic proof, etc. This is will give you all the tools to start writting programming.

Topic #1: Functions. I can not explain how important this part is. Ask any programmer in any language. Functions will become the biggest tool in you arsenal.

Topic #2: Object Oriented Programming.  An introduction to OOP concepts and basic maneuvering.