Archive for the ‘ How I write code ’ Category

Write Tests Part 2.1 – How to Write Tests in Java

hey there,
last month I wrote about UnitTests and this time I would like to show you how such tests can be written in Java and in two weeks I’ll show you how it’s done in Pharo. Isn’t this cool? Two column articles in one month! Although the new semester has started a few weeks ago I’m more into writing articles then ever.

How to Write Tests

First of all like I mentioned last month there are a few different methods for testing. The most important in Java is assertEquals as it gives more helpful output if the test fails. There are other assertion methods and if you want, have a look at the Assert-JavaDoc.

I showed you how to create test cases and the important testing methods so let’s start writing tests. Since JUnit 4 it’s much easier to write tests because you don’t have to care about testsuites and tests don’t need the word “test” in their method name to be recognized as a test. To go on with there are only a few things you have to do to write tests.

Firstly if you want to test complex classes and programs you have to initialize the required objects and their states. To do so the first method in our test case is named setUp and in front of this method you have to write @Before and import the necessary package. This setUp method will be called before each test you execute.

The next step is to write the actual test methods. You create a new test method by simply writing @Test in front of the method, isn’t it easy? Note that it’s considered good style to use method names starting with should or shouldNot and then write what you want to test so that it is clear, what is asserted. Have a look at the following test skeleton to see how this all would look like:

	@Test
	public void shouldBeEmpty(){
		...
	}

Sometimes you like to test if an error is thrown, probably see if the check for meaningless input works. For example if you pop an empty stack there should be an error – and it’s a failure, if there is not! To test this you have to write the expected error right after @Test. It should look like this:

	@Test (expected=AssertionError.class)

Now if and only if this error is raised the test will pass.

Last but not least I’m going to show you an example with a few tests. It’s a very simple and trivial one and it’s not a thing you should write tests for, especially not chained ones, but you should see how it’s supposed to work. In this example I’m only going to test the basic calculation functions with Integers. Therefore I’ll test addition, subtraction, multiplication and division should work correct and the result should always be an Integer.

Example:

public class CalculaterTest {

	public int testValue;

	@Before
	public void setUp(){
		testValue = 0;
		assertEquals(testValue, 0);
	}

	@Test
	public void shouldAddFive(){
		testValue = testValue + 5;
		assertEquals(testValue, 5);
	}

	@Test
	public void shouldSubTwo(){
		testValue = testValue + 5;
		testValue = testValue - 2;
		assertEquals(testValue, 3);
	}

	@Test
	public void shouldMultWithFour(){
		testValue = testValue + 5;
		testValue = testValue - 2;
		testValue = testValue * 4;
		assertEquals(testValue, 12);
	}

	@Test
	public void shouldDivWithTwo(){
		testValue = testValue + 5;
		testValue = testValue - 2;
		testValue = testValue * 4;
		testValue = testValue / 2;
		assertEquals(testValue, 6);
	}

	@Test (expected=AssertionError.class)
	public void shouldRaiseError(){
		testValue = testValue + 5;
		testValue = testValue - 2;
		testValue = testValue * 4;
		testValue = testValue / 2;
		testValue = testValue / 4 * 3;
		assertEquals(testValue, 4.5, 0.00000001);
	}
}

As you can see a lot of the code has to be copied every time which leads to long and hard to maintain tests but next month I’ll write about a cool Framework to improve this tests and to write even better tests.

That’s it for almost this month, “How to Write Test in Pharo” will be online 31th of October.
Stay tuned and leave comments below.
cheers d3orn

Write Tests Part 1 – UnitTests

hey there,

this month topic is tests, there are many different kinds of tests and because I like to have more but smaller articles I’m going to split this article up into more then one article. As a result you will probably see my first ScreenCast I ever made, I like to make a Screencast in the last article about this topic because I want to show you a good example.

I’m going to split this articles up into:

  • UnitTests
  • How to write Tests in Java and Pharo
  • JExample
  • Write Tests First

As you can see I’m going to start with UnitTests today.

UnitTests

What are UnitTests?

A unit is the smallest piece of source code you can test and therefore a UnitTest is a method to determine if such an Unit works as intended.

In most programming languages there are tools to write tests. For example in Java you can use assertTrue, assertFalse and assertEquals to create tests or to check conditions in you’re methods (more about this later) and in Smalltalk (Pharo) you do have self assert. To go on with there are test frameworks like JUnit and SUnit which helps you organize and running you’re tests.

With the help of these methods you can start to write tests, in Java you have to create a JUnit Test Case in Eclipse and import the java.util.assert.* lib. Please notice that I’m using JUnit 4 and not JUnit 3, you should always check the used version before running a Test Case. To check this in Eclipse you right-click on the Test Case -> Run As -> Run Configurations… and in this window you can select the test runner you like.

To go on with there are only a few rules for writing UnitTests:

  • KISS (keep it short and simple)
  • At least one test per method
  • test coverage of approximately 60% or higher (more about test coverage later)
  • tests shouldn’t be longer than ten lines
  • tests should represent a scenario how the unit is used

Tests should be written during the development phase or the debugging phase. During Development you should create tests whenever you encounter one of the following problems:

  1. You need to add new functionality
  2. You need to redesign your software to add new features or adapt to new requirements

In the first case it’s very helpful to write the tests for this new functionality first and then implement the functionality, I’ll cover this in the third article. In the second case you already have a working program and you want to add new features, you therefore should refactor the old version in small, very small steps and after each of these steps you should run the tests you have again. You then have to fix everything that’s broken and when all test pass you can proceed with refactoring. As you can see tests will help you a lot during the development phase of a project but you can also use them during the debugging phase.

During Debbuging whenever you encounter a bug or a defect in your code you should write a test to demonstate that bug and as soon as this test passes you’re bug is fixed!

That’s it for this month and I hope you enjoyed the reading ^^

It’s a big goal of mine to show all of you that tests are good, a lot people I know think that tests are only a waste of time and not worth to be written. I think UnitTest will help you a lot in the future to maintain or refactor a program and you definitly get your invested time back. The best part of UnitTests is, once written, you can run them as many times as you want whitout using much time.

Please leave comments below and stay tuned for the next months article about JExample .

cheers d3orn

UML-Diagram

Hey there,
this months article’s topic is UML-Diagram and how they could  help improving our programs. Sadly I didn’t wrote an article last month and I’m very sorry about this fact, but I promise to try everything to publish every month and I’m going even further I’m trying to post up to four articles a month. Only one about my column but the others will be about different topics!
Good news, this article will be longer and it will cover all things I like to write about UML. This would be a two-month article I’ll cover here!
Now let’s get started.

What’s UML

UML stands for Unified Modeling Language and it’s a collection of different modeling techniques. It can be used for almost every type of program whether they have databases, server&client or other things and UML is totally language independent. There are a lot of different diagram typs like class, component, object, sequence or communication diagram. In this article I focus on the use of class-diagram helping to improve our programming experience!

Why UML?

Why should we use a UML-Diagram to write code?
First of all class diagrams help us visualize the structure of a project in a much better way since it’s something we draw or create with an editor and we can hand out later.
Secondly, these diagrams do not only help the designer, they also help to explain the behavior of the classes or the project to outstanding people. As a result it’s much easier for us (yeah I think sometimes we talk in a unknown language to other people^^) to talk about the features and the design of a project.
Finally, with the help of a class diagram it’s much easier to see if our project has some big problems like wrong class behavior, God-classes & data-classes and so on. If we can see such problems in the beginning of a project it’s much easier to find another solution rather then invest a week programming to find out it doesn’t work. It’s essential that we don’t use to much time to draw such diagrams because it’s not actual code and you can’t see big process, therefore you should either just make a quick draft or use an editor.
Class diagrams don’t take much time to make and help improving our projects a lot because we can find design, behavior or structural problems at the start. As a result this amount of time used to draw and think about such diagrams is well used for the future.
On the other hand you shouldn’t use UML-Diagrams blindly for everything, sometimes you’re better off using an improvised diagram, pseudo-code or just your imagination. I don’t find anything helpful in UML to come up with algorithms for example. There are still some hints, why you would use UML.

Take this checklist:

  • You are working with loads of other people. If so, others can see the big picture in the diagram, even though not everyone was there when the idea was formed.
  • You will have many classes. It is difficult to keep track of all the interactions and code doesn’t often cut it to explain things. UML can help you by giving you a visual help for your project. Also many UML editors let you export the diagram as a code skeleton in the language of your choice.
  • You will be working on the project for a long time. Or even worse: work on it again after some time. The big picture is the argument again.
  • You have no clue what else to do. One could argue that you should not work on that project, but maybe you don’t have a choice. UML diagrams can help you to come up with the responsibilities (if you use Responsibility Driven Design). Or they at least look as if you did a lot of work if you can pass them around.

UML-Basics

I’m only going to write about class diagrams in this article but you can find more informations here: UML Tutorial
Every class in a class-diagram gets a rectangle with three cells, the first cell contains the name, the second is used for member variables and the third cell is used for all the different methods of this class. In the following picture you can see the basic structure of an entry.

First of all there are a few different signs to indicate the scope of a variable or a method, these are the following.

+ = public
# = protected
~ = default
- = private (minus)
capital letters = final
underlined = static

I’m now going to explain each of this indicators with an example of a class.

public class Cell {
	public static final int MAXAGE = 10;
	public String name;
	protected String cellType;
	private int birthday;

	public void giveFood(Food food){
		...
	}

	private void mitosis(){
		...
	}
}

The first variable in the class is public (+), static (underlined), final (capital letters) and an int with the value 10. To continue the second is a public (+) String and the third is protected (#) String. The last variable is a private (-) int. To go on with the methods there are only two, the first is a public (+) method with a parameter. You have to pay attention to the parameters because the order is changed, the name is in front of the typ! The second method is private (-) but does not have any parameters. I don’t write the type of a parameter or method if it’s void.
In addition in Java or other programming languages there are abstract classes and they could look like that:

public class PrimalCell {
	protected String cellType;
	private abstract void mitosis();
}

An abstract class has {abstract} or {a} after his name and after each abstract method, have a look at the following picture to get the idea of an abstract class:

Last but not least Java as example has interface classes, interfaces do have a «Interface» or «I» in front of the class name. I think it’s clear how this would look like in a class-diagram.
On the other hand there are also dependencies we can add to our UML-class-diagram. I like to explain dependencies with one big example and  two smaller examples.

public class A implements C extends D {
	String name;

	public B doSomething{
		B temp = new B();
		...
	}
}

As you can see there are four types of arrows.

  • full line and closed arrowhead represents a specialization therefore A is-a subclass of D and in fact A is-a D. Mind that the arrow points at the more general type.
  • dull line with a diamond represents an aggregation or a composition therefore A has-a String (the diamond points at the class which has. Think of the diamond as a cell with contains the thing on the other end)
  • dashed line and closed arrowhead represents an implementation. A implements C (the arrowhead points at the implemented class/interface!)
  • dashed line and open arrowhead represents an usage therefore A uses-a B (the arrowhead points at the class which uses). It is not as clear as with the other arrows, what that means. A somehow needs B to fulfill its responsibilities.

To continue, sometimes we have to use an inner class, for example you can use an inner class to implement a queue, the inner class would be an object with a previous and next parameter and the stored data.

Such an inner class would look like this:

The class A would have a inner class called B. Finally I like to mention one last thing, it’s called cardinality. Often it is very useful to point out for example how many Strings the class A has. As a result there are different types of cardinalities.

  • 1..* = one to many
  • m..n = between m and n (for example 1 to 5 would be 1..5 )
  • 0..1 = zero or one
  • n = exactly n Elements
  • * = any number, including 0.

How to draw class diagrams?

You came to the conclusion, that a class diagram would be helpful for your work.
Maybe you already have some code which you want to extend. In that case you should first translate that into UML. Some tools can do that for you, otherwise keep it simple. Not every method needs to be in there.
If you start with a blank sheet, there are other problems of course. I often find it hard to know where to start. While I’m a big fan of drawing things on paper to come up with ideas, there is a simple fact, that makes me use UML editors instead of it: You can edit. Of course you can kinda edit things on paper too, but it gets messy. So in using an editor like Dia , I can just put some class names in the diagram, that I think I will end up needing. No attributes, no methods, no connections yet. Then I start wondering, what they should perform and give them some methods to do that. Now I start to see, how the classes might interact and what other classes might be useful. As a result I connect the classes the way I think they interact but I don’t need to add every Getter&Setter because they are such basic methods. To go on with I rethink my current diagram and change what I think should be changed. It’s very important at this point of developing that I don’t overload my diagram, an overloaded diagram won’t help anybody and could only lead to a big mess. So delete methods with trivial use and refactor abstract or interface classes out of existing classes or even put some of the details in a diagram on its own. At the current point I often safe my diagram and start over to have a second version with probably new ideas. If you like to do this start over and if you are done with the second diagram try to compare the two files. Like I already mentioned in a previous article my second thoughts are almost the better once xD.
Now you should have a proper class-diagram for your project. At this point you should start writing code and because you can see the important connections of the different classes you should definitive start with writing tests! More about writing test in the next article “Write tests first” next month.

That’s it for this month and I hope you enjoyed the reading ^^
Please leave comments below and stay tuned for the next months article.

cheers d3orn

What’s important

In the second part of my column I’d like to talk about important things before you actually start coding and designing. This things are necessary for planning and for a good start.

Firstly, I think it’s good to have a deadline when you should handout your project. If this deadline exists I’d prefer to make a little timetable with the major TODO’s. On this first list I think of possible small goals and this list is growing iteratively during the whole process. Keep in mind that you shouldn’t have to much TODO’s at the start, just KISS (keep it short, stupid!)

To go on with it’s very important to share this timetable with all your group members if it’s a groupproject (which is often the case^^). You and your groupmembers should compare and share all lists. I personally like Google Wave and therefore I’d like to create a Wave which contains the merged timetable. The big pro of a wave is that all members can edit the table and add new TODO’s/goals. As a result you are up to date all the time.
I think Google Wave could really help improving project management and design and therefore I recommend it to anyone! see www.wave.google.com and sign in!

Secondly like I already wrote it is very important to have small goals since this type of goals really help keeping the motivation up! Personally I make my goals as small as possible but this could lead to a bunch of small goals. I’m always trying to avoid too much goals, remember coding is a iteratively process, the goals too. Due to the fact that my goal are so small and therefore reachable, every time I reach such a goal my motivation rises and I keep up my good work! Another thing I do is increasing the size of my goals every time I fullfill one, as a result the goals aren’t too big at the start and motivation could rise. As time goes on the goals are getting bigger and bigger which will increase motivation also if such a goal is reached!

Finally all planning is worth nothing if your group members and you doesn’t try to be in plan as much as possible. This may bring a little pressure to the project but it may also help to deliver the finished product at the right time! And a lot of people are working way better with pressure, like me^^

That’s it for this month and I hope you like this article. I’m looking forward to read a lot of comments^^
My blog domain is moving but I don’t know how much time it takes but if I know some thing new it I’ll tweet it!
And I’m looking for a new Word-Press theme too, I’ll hope you will like it^^
The next topic for this little column is about “UML-Diagram” and this will be one of my favourites!

Cheers d3orn

Think about the task

Whenever I get a new task or a new program to improve, the very first thing I do is to think about the task. I read the existing program to understand what the creator did or I simply read the task 2 times.
I’m going to split this article in two parts, one part about a new program and the second about a given program task.
After reading and understanding the task I try to come up with a first concrete idea about what my program should do and how It could look like. To go on with personally I like to reflect about the task a second time since my second thoughts often improve or change my first idea in a good way!

If on the other hand I have to improve a given program I come up with an idea how I could solve the task too but then I highly recommend to start searching for the place you can/should implement your idea. There is nothing worse than being lost in the code of someone else! IDEs often have good ways to search for call hierarchy and other things. Use them!

I’ll hope I could show you how I start to solve a programming task! Next article is about “What’s important” and it should be out June 14th
Cheers d3orn

How I write code

Todays article is about the way I create my programs.
First of all I have to say, I’m not a pro in writing code but on the other hand I’m learning a lot about Java, C++, C and programming-concepts in the university and as a result my skills improve. My aim is to write good, readable, tested and simple structured code, since this sort of code is the one you can depend on and improve later. This because you simply understand what it does by rereading the code and the tests^^.
So how do I start when I get a new programing task? I made a list to show you all the steps I need to make a program.

  • Think about the task.
  • What’s important (Deadlines, personal features etc.)
  • UML-Diagram
  • Write Tests
  • First class!
  • Expand class(es) iteratively (with the help of IDE and tests)
  • repeat 4-5 with new classes till your program works and does what it should
  • Write more test and get a coverage of over 60%
  • Reread the whole code, think about improvements in understanding and simplicity
  • If it’s possible refactor Interfaces and/or abstract-classes => Dependency Injection
  • Optional: Improve the speed of your program

So, that’s it for today, in the next weeks and months I’m going to write about each of this steps separately and if I’m done I’ll post a PDF with all the informations collected. I hope this will help you improving your code writing and I’m glad for comments or mails!
Cheers d3orn