Thursday, August 25, 2016

JAVA 6 - Avoiding tangled code with methods

Last time we were looking at operators.  The program I wrote to support it showcased a whole load of operators, which you can see here.  The problem is that the main() method went on a bit ...

Rapunzel, you don't want your main method to end up like your hair ...

Computer programs aren't one single, long listing ... though they used to be (but then, hey you would be lucky to have 1kB of memory to fill).

Methods (previously known in some languages as functions) are a way of taking a piece of behaviour, breaking it into it's own space where its easier to read, but more importantly where it can be called whenever you need it (and reused).

[You might notice because I learned about methods originally in my days of C programming, I'll revert by accident to using the word "function".  Pretty much function and method can be used interchangeably.]

If you've ever manually test scripted, you might have used a similar concept to methods in your scripts.  You probably have a script somewhere for logging in, and ideally it's fleshed out in just one place,


Do you flesh out your script with such detail EVERY time you login?  Of course not - you tend to define it once like this (if you absolutely have to), then you refer to it time and again to save effort.  It saves you time writing out, and if there's any significant change to the page (for instance "log in" will now consistently be called "log on"), it means you have less changes to make (less maintenance for the win!).



Exploring methods with some examples

I'm going to talk through some of the features of methods, using a few examples, each one building on a previous one, and expanding them.

The way I learn any language (and how I really recommend you do too) is not just to read, and copy examples.  But also to play and experiment with it.  I'll try as always to suggest ways to do this as we go along.

My examples are all in Github, and I'll include references as I go along.


Be aware, this is a pretty big section, and I've broken it down for you.  You might want to work through them all in one go, or pace yourself through them!



A basic method

Okay - so as a minimum viable product for the use of a method "write a hello world program which uses a method you've created to print to screen".

My code for this can be found here.



Here printMe is our method - the following is the header definition for the function, which shares a lot of similarities with the main() method when we previously put that under the microscope,

  • private - this could also be public.  It defines how visible this method is.  The main() function can see this because it's part of the same class definition for basicMethod.  However if you tried to use this outside of the basicMethod class, you'd get an error.
  • static - as we've said, because we have a main() method our methods have to be static within this class.
  • void - means that this method just does it's job, it doesn't return a value.
  • printMe - this is the name of our function.  We can choose it to be whatever we want to be (as long as it's not a reserved word used for something else like "int", "double", "static" etc).
  • () - this helps to define that we've got a function here.  If we were passing values, they'd be inside the brackets, but this is our minimum viable product remember!

After this, the print statement which is bounded by {...}.  Everything within here is part of the

Within the main() function you can see there is the command printMe(); which calls the function.

Try,

  • Changing the visibility of the function from private to public. Anything bad happen?
  • Do I really need that static definition?  Remove it and see what happens.



Method visibility

I've created a project on Github here where my printMe() and main() functions are in separate classes, so that you can see how this works.

So we have a print class here:


And a main class here:


Notice how printClass doesn't have to be static now?  We've also had to do a slightly odd call of the printMe method, which will make more sense when we cover objects.

Notice that both classes are using the package sharedMethods, which they're part of, and hence they can see each other.

Try,

  • What happens when you change printMe to private?


Passing variables

As mentioned before, we can pass data to our methods when we call them - which helps to unlock a lot of behaviour.

We have to defined the parameters we use in the function header, in the () part.  You can have multiple variables defined here, all comma separated.

We use a nomenclature similar to where we define variables in a program so ...

addNum (int num1, int num2);

So you start with the type of parameter/object, then follow with the name,
int is the data type of integer
num1 and num2 are the names of the variables

Variables defined in the header can be used inside the function, so you wouldn't get an error if you had a line like,
num1 + num2;

Because the variables weren't found.


I have in Github an example here,


Here you can see I've redefined printMe to take in a number "num" and a string "str", which it prints to screen.

In the main() method you can see how I declare values that I then pass to my method with the call printMe(printNum, printStr).

Notice how I don't need to match the name of the variable string I use in main() ie printStr to the one I use in printMe ie str.


Passing values

When you send values to a method, you're sending over a copy of your actual variable, not the variable variable.

It's similar to a thriller where the good guy hands over a tape with something incriminating on, only to see the villain destroy it.  Somewhere later on the good guy goes "aha - you thought you'd destroyed it - you only destroyed a copy!!!".

The best way to demonstrate this of course ... is with an example.  Which can be found here,



Here,

  • We create variable "number" within main(), which is set to 1.
  • We then pass "number" to incrementNumber function, which increases it's copy to 2, and prints that it's 2.
  • When the function finishes, it returns to the main() function.  Where the original version of "number" is still set to 1.

This is often called "passing by value".


Returning values

This might have you asking "is calling a method a one-way street?  I can pass information into it, but it's not much use getting information out".

Up until now we've defined void functions.  Ones which don't return any information.  However we can change that to any variable or object type we want.

So we have an example ready to go here,

Here we have a sightly difference version of incrementNumber,


This one increments the number, and then returns it using the return command.  The return command means that the system exits the method on it's execution

Try to,
  • Return a non-int, you should get an error
  • Add a print command after the return command.  You should get an error that the code is non-reachable (as the system will exit on the return command).

This method takes two string, and returns a new string where they've been joined together with a space in-between.


Finally, in our main() method you'll see something interesting,


The main() method is calling the function and using an assignment operator "=" to take the value, and assign it to a local variable.  Hence unlike the previous example, the work of the method is returned and retained.  Essentially you can use this design to "over-write your original".




There are also be some other ways we can manipulate data with methods, but we'll look at them later when we look at objects.



See ... everything so much easier when you keep things short ...


Wednesday, August 24, 2016

JAVA 5 - Manipulating variables through operators

Last time we looked at declaring variables.  But a variable isn't really much use unless we learn to do something with it - for that we need operators.


Operators allow you to manipulate variables in lots of ways.  They're in truth the powerhouse of your programming language.  There are a whole load, but we're going to focus on just a few.  To avoid this series spiralling, you're going to have to research some yourself - which is okay, as most programmers do just that.  Looking for operators as they need them.

Arithmetic operators

You're probably semi-familiar with these already - they're the operators which allow you to do arithmetic!

As a physicist, most of the early software I wrote was about simulating a problem in maths or physics, so using these was a must.

The operators +, -, / are probably familiar as add, minus, divide.  Looking a little different from normal maths, * is used for multiplication.

In code, you can set out such mathematical statements as you need.

Integer maths

Let's start out by declaring two integers,

int num1 = 5;
int num2 = 3;

Once declared, we don't have to continuously use "int" anymore.  So we can use,

num1 + num2;

This will return 8.  They're added.

num1 - num 2;

This will return 2.  They're subtracted.

num1 / num2;

Might surprise you.  Remember these numbers can only have whole number values.  It returns 1, because 3 goes into 5 only once.  There is no decimal, and there is no rounding up.

To counter this, there is the % operator which is the modulus.  This is "the remainder" if you remember back to maths at high school.

num1 % num2;

Returns 2.  Once you divide 5 by 3, you have 2 left over.

num1 * num2;

Returns 15.  Multiplied.

num1 / 2;

Returns 4.  This is a reminder that you don't always have to use variables - whether using int, double or String.  You can use fixed values (sometimes called literals) if you want.

Double maths

This is the maths of decimal numbers.

double num3 = 5;
double num4 = 3

num3 + num4;

This will return 8.0.  They're added.

num3 - num 4;

This will return 2.0.  They're subtracted.

num3 / num4;

Will return 1.666666667.  Decimal points!

num3 * num4;

Returns 15.  Multiplied

Mixing data types

If you try mixing ints with doubles in an operation, weird things happen.  You can override this by using a cast function.  If you put

  • (int) before a double number, it treats it as an integer
  • (double) before an int number, it treats it as a double

So ...

(int) num3 / num2;

Returns 1.

(double) num1 / num3;

Returns 1.66666667.

Mixed arithmetic

Hopefully you've seen this before somewhere.  But if you have a long calculation such as ...

7 - 2 * 3;

What's the answer?  Computers apply multiplication and division before they apply addition and subtraction.

We tend to process from right to left so would expect an answer of 15.

A computer sees it as...
2 * 3 = 6
7 - 6 = 1

And answers 1.

You can use brackets to set orders.  Things inside brackets are processed before things outside.  So

(7 - 2) * 3;

Is 15.  If this shocks you, you need to look this up.

Strings

Arithmetic doesn't seem to make much sense in terms of strings.  However the + operator joins together (sometimes called concatonate) two Strings to make return a longer string made of both parts.

String str1 = "Hello ";
String str2 = "World";
String str3;

str3 = str1 + str2;

Returns "Hello World".


Assignment operators

Another key part of this, is assignment operators.  We've used them before for initialisation - we use the name of a variable, the = sign and a value.  The = operator sets the variable to the value we provided.

So if we've declared

int answer;

Then if we do,

answer = 2 * 3;

It returns 6.

If we do the following,

answer = answer + 2;

It will increase the value of answer by 2 ... so now 8.  But we could also do ...

answer += 2;

Whereas,

answer -= 2;

Will decrease the value of answer by 2.

All these will work for double numbers too.

Finally,

answer++;

Is a method used for increasing an integer by 1.  You can use,

answer--;

To reduce it by one.



See operators in action

I have an example on Github filled with operator actions for you to see at first hand.  Find the code here.




Extension material

Look for other types of basic operators here.


Tuesday, August 23, 2016

JAVA 4 - Oh I do declare ... variables.


Today we explore the world of Java programming a little more by looking at variables.

When I was a kid, reading my first book of computers, they explained that a computer was "a machine for processing data.


Variables are handles for data which was used in software.  There are multiple core types - although we're able to specify many more complex ones if we want to - although typically they're combinations of multiple of these data types.

Before we use a variable, we typically do something called declaration.  This is where we define what name we're using for the variable, what type of data item it is, and we might even perform "initialisation" which is setting it to an initial value.

Lets look at some types now ...

Integer

The integer type is declared by the int keyword as below,

int line_count = 0;

We used this last time...

  • int - declares it as an integer
  • line_count - is the name of the variable.  Whenever we use line_count, it'll substitute the value of the variable instead.
  • = 0 - this is the initialisation part.  It sets the value of line_count to zero.


Integers are whole numbers.  You never use fractions or decimals in integers.

Integers are great for counting the number of times you've been through it.  Everyone but parents counts in whole numbers.

If you had a mother like mine, then you might remember the fractal way they count - "you have until the count of three Michael!  One ... two ... two and a half ... two and three-quarters ...".

Double

The float data variable is a "double accuracy" floating point number, or decimal number.  An example is below,

double pi_val = 3.142;

Similar to our integer,

  • double - declares it as a double decimal number.
  • pi_val - is the name.
  • = 3.142 - initialises the value.


Strings

Strings are ways the computer languages handle text.  A string is considered to be a grouping of characters.  We've already been handling strings - "Hello, World" was a string in our first program.  We use the combination of "" to show we're handling data for a string.

So, let's declare a string here,

String person_name = "Mike Talks";

Here,

  • String - declares it as a string
  • person_name is the name of the variable.
  • = "Mike Talks" = initialises the string to contain my name.


Example

Find the coded example here.


This method declares several data types, and prints them out as below.




Extension material

Sometimes you need other forms of data variable.  Look up and read about

  • long
  • float
  • char

JAVA 3 - Debugging. The code doesn't bother me anyway.

Last time we looked at all the ways that your development environment will try and keep you on the right path.  I promised to teach you another useful tool - so today we're going to use the debugger.



Now I need you to build a brand new project - which you can call whatever you like, and copy into it the code from here.  Which looks like this ...


Unlike yesterday, this has a whole series of print commands, and "other things", which I'm not going to explain right now.

Sometimes code goes wrong, and the only way to be sure is to instead of running and watching it fail, you run it in a debugger.  A debugger allows you to run part of your code a line at a time, and to also keep an eye on the data.

This article is going to introduce you to the basics.

Set a breakpoint

Choose line 25 which has the line "Can't hold it back anymore".  Choose the far left edge and right click as below, then select "Toggle Breakpoint".


Once set, you'll see a blue dot next to the line - this is our breakpoint.  When the system is run in the debugger, it will run to this point, then wait.


Run in debug

To run in debug select Run -> Debug from the top menu.  You'll be asked if it's okay to change your perspective, and select OK.

Your view should now look like this...




You will notice the line we've selected is highlighted (it's not run yet).

Under the console, you can only see the first two lines have been printed,



Similarly, in the top right, there's a panel labelled "variables" which shows that line_count is 2.


This area allows you to keep track of your data items used by your code.

Move through the debugger

Press F6 - this is the "step over" button.  You'll notice the highlighted line moves down.

Every time it passes over a println command, a new line of the song is printed.  Every time it passes over the line_count++ command, the line_count variable in the top right increases by one.

Later on when we've covered methods, you can chose to "step over" or "step into" methods,

  • Step over [F6] means you just have the method execute and return
  • Step into [F5] means you follow the method, executing line-by-line as we're doing now


When you've had enough select to resume with the F8 command.  The rest of your program will execute.



Have a go again until you're familiar.  When you're done, return to normal view by selecting the Java view button in the top right, next to Quick Access.


And there you go.  Combined with last time's look at how the compiler will complain to you, this should be handy for when things go a little wrong for you!


Monday, August 22, 2016

JAVA 2 - Let it ...no!!!

So - we've successfully done our first program.  The next two sections will show you some useful tools to help you investigate when things go wrong.


Coding is such a tricky discipline, forget a semicolon, misspell a name or even use the wrong capitalisation, and bad things can happen.

Fear not though - the tools are on your side, and will try and help you when they can.

We're going to go back to our Hello World program from last time.

Problem 1

Now ... let's take the line,

System.out.println("Hello, World");

And remove that semicolon.  Oh yeah, we're going there!  Now save your project.

Immediately on your line, you can see a red cross next to your line ...


Likewise, if you go under your problems tab, you can see a breakdown of where you have an error ...


If you hover your mouse over the red cross on your code line, it'll even give you suggestions.

Replace the semicolon and save.  All those problems should go away.

Problem 2

Now - let's remove one of the brackets, and see what happens!


Problem 3

Does it really matter if the main function is static?  Let's remove it and find out ...


It doesn't seem to mind too much - not big red cross.  I guess it's okay ... so let's run it ...


The Console clearly objects, and makes it clear we need to change it to static.

Problem 4

What happens if our main method is private not public?


Again it doesn't seem to mind, so let's run it ...




Extension material

Try all kinds of ways to trash your Hello World and see how it generates errors.

JAVA 1 - Do you want to build a program?

So ... do you want to build a program?


Before we start, if you haven't already I need you to download both a version of Eclipse for Java, and the Oracle JDK - I gave instructions for this back here.

When you open Eclipse the first time, you'll have to set a workspace - it can be anywhere, but it helps to remember where it is!



Create a project

Your project space is pretty important, it's your work area on ... well a project.  Where you collect all your objects and files together.  We won't be doing much here on large scale with our programs, because by necessity we'll have to work with relatively small pieces which demonstrate a working idea.

From the menu select File -> New -> Project




Select Java Project, then Next


Set a project name as project helloWorld & select Finish


Within our package explorer, you'll see your project all set up ...


Create a class

Java depends on classes for everything - so we need to add one in order to do anything.

Right click our HelloWorld project and select New -> Class


Now to avoid confusion, I'm going to suggest you go all Yorkshire and call this class "ayeUpWorld".  I also want you to select the tick box for "public static void main".


Now select the Finish button.  You should see your new class added under the Package Explorer ...


Meanwhile under the class, you can see a breakdown of the contents of the class ...


Right now, all this is just default code, but it's worth going through it a line at a time

public class ayUpWorld {

This is a declaration of our class

  • public - this declares that the class can be seen outside of this file area.  Java contains elements called classes, methods and variables - all of which are typically set to either private or public.  Public is easily seen and accessed.  Private, you have to be inside a class to use.  You're probably thinking right now "why not make everything just public - it's easy".  To which I'll say to you right now "shhh ... spoilers!".
  • class - declares that this is a class
  • ayUpWorld - is just the name of the class
  • { ... } these curly brackets are used in Java to show that everything between them belongs to the class we've just defined


public static void main(String[] args) {

This defines our main method.  When we run this program, the main method is immediately run.  Note because of that you can only have one main method per project.

Let's likewise put everything through analysis,

  • public - again we need this public to be accessible.
  • static - this is a complex one for a beginner.  But static just means there's only one instance of this main method.  You could create a whole load of instances of this class, but there'd only be on main method.  [Don't worry if you don't get this right now]
  • void - this position in a method declaration is where the return from the method goes.  We're using void to say that when the main method is finished it's not going to return any form of value.  We'll return to this when we cover methods.
  • main - methods can have any name.  But when we use main (which is a reserved word) it signifies that this method will be called initially when the program is run.
  • (...) - notice methods have normal brackets after the name.  Within here is a list of any parameters passed when a method is called.  We'll return to this when we cover methods.
  • String[] args - you can supply from the command line a whole series of arguments for your system to use - this is defined by this set of Strings.  We won't be using this here.

// TODO Auto-generated method stub

This is a comment - which is used to make code more readable.  The compiler ignored any text after // or between /* and */

Comments allow you to give anyone reading your code some useful background into your project




Let's say "Hello World"

Right now it's really nice ... but it doesn't really do much.  Let's change that.

We're going to make a Hello World program - this is a time honoured program used to learn languages, because it's pretty much a software minimum viable product.  It will output the text "Hello World" to screen.  And that's it.  But along the way we see how the core of the language is structured.

Under the comment line, add this line ...

System.out.println("Hello, World");


  • System.out.println - is a print command with a parameter afterwards in ()
  • "Hello, World" - is the string (defined with the "") that we want to print


REALLY important, and easy to miss is the semicolon ;

All statements in Java end with a semicolon ";".  You'll notice we didn't need them when declaring our class or main method.  But you need them after any line that "does an action".


You're ready to go!

Right let's run this - you'll find a green play button here ...

What happens once selected - your code will compile (right now it's as small as you can make, so this won't seem like long) before running.  Compiling is when your Java text is turned into an executable file.

Once finished, you'll see under the Console ...





Let's Learn Java - setting our rules

As I mentioned last time, I'm going to focus on the core features of Java over this series, to help those of you less experience to build up a familiarity with the language and some of it's features.

As such, this series will provide an introduction to core features of the language, but it's not in any way expected this will be all you need.  Much as I talked about in the automation series, this series will introduce core concepts with examples to you.  It's goal is to illustrate a framework for you to develop your own mastery.

How do you do that?

Practice

It's one thing for me to show you how to do something.  But the best way to learn is for you to do it yourself, change a few things, and see what happens.  Try and expand beyond what I've done.


I recently spent a couple of days in a Buddhist monastery, where there was a poster that said "I practice every day to become better".  That's exactly how I feel about testing, and it's also the method I learned to program.

Nothing throws what you've learned into such sharp focus as trying to do.  If you're a great success at it, try and be more daring.





If you find a problem, explore - read the error message.  Try Googling your problem and reading around.  Try different things.

My advice is to try and make discrete changed, and run your program regularly to see what happens.  That should help you catch problems as early as possible.

Read

I worked for 10 years as a C++ developer.  I've worked in the IT world for 20 years.  I have 3 higher education qualifications, and none of them is in computing.

I learned to program C++ by finding a really good introduction I could work through.  Key was it had to have a lot of examples - for me the book was Software Engineering in C++ by Michael J. Pont.

But reading "a book" doesn't make you an expert.  Combined with my experimental practice, I also read a couple of other sources to refine and fix what I'd learned.

As a teacher, we're taught the importance of "the rule of three" when learning something new.  You had to be told something three times, in three different ways for you to learn best, reinforce and sink in.

Likewise in programming - reading allows you to get some familiarity, the best way to test that is to try and write something that uses this.  This in turn will lead you to Google and read up more stuff, as a kind of cycle.  Repeat this enough, and you're learning.

Yes - the two things form some kind for infinite feedback look - and that folks is the path of mastery.


Most books I've come across are giant tomes - whilst that's great to be authoritative, I'm always intimidated by the idea of reading a 1000 page book.  Although, unlike Game Of Thrones, it's not likely anyone will die in this [brace yourself ... a meme is coming].


One book I heartily recommend as a companion to this series is Alan Richardson's Java For Testers - it has some nice explanations, and plenty of practical examples

This series will be designed to complement that book, I'll be working with my own descriptions and examples.

Competition Time

I've never ran a competition before?  Well I am now!

I'll be giving away an electronic copy of Java For Testers to one lucky winner.*

To enter - just comment below including your Twitter ID.  On Wednesday 31st August (NZ time) I'll chose one person at random (I might even write a program for this), who'll be the winner.

You have no obligation to do anything beyond that.  However to make sure the book is going to a relevant home, when I look at your profile on Twitter, I'm hoping to see the word "testing" (at a stretch "QA") somewhere.  Good luck!


* Just to be very clear - we're testers, and clarification is everything.  I won't be "giving away" as much as "buying as a gift".  Just in case you were wondering if I'm shafting Alan on his royalties.