Showing posts with label project. Show all posts
Showing posts with label project. Show all posts

Tuesday, December 9, 2014

Importing and Packages - Customs won't like this.

Alright, I've been ignoring it, but the time has come to take on a fairly important issue when it comes to organizing your code.  The topic of the day is packaging.

Packages are really not much more than a set of directories (or folders if you prefer) into which your .class files are placed.  This becomes important once your projects get beyond two or three .java files, because you really want to avoid namespace clashes.  You don't even know what they are yet but I'll bet you're agreeing that they sound like something to avoid.  More importantly, proper packaging will help you to keep your workspace and brain organized.  Programming is hard enough, you don't need to make it worse on yourself.  I may keep a messy desk but I do try to have my source code laid out in a logical fashion.

Most of the time, we bundle up our .class files into something called a Jar.  This is just a file with a .jar extension, and it's actually in technical terms a .zip archive file.  This is convenient because a sizeable system can contain dozens or hundreds of .class files, and managing them individually will make you want to gnaw your foot off.

Now, we could go ahead and just put all of the .class files into one giant list.  But that's not a list you want to be looking at or searching through.  It is almost always possible to separate out the various parts of a project into logical subsections, and you should do this.

At the most basic level, you can control packaging by putting a line at the top of your source file like this one:

    package com.oopuniversity.packages;

It dictates that the compiled .class file should be placed in a subdirectory called 'com.oopuniversity.packages'.  When you want to refer to a class called 'PackageDemo' in your java code, you can do it either the hard way:

    com.oopuniversity.packages.PackageDemo = new com.oopuniversity.packages.PackageDemo();

Or you can do it the easy way.  Add an 'import' line up above your class declaration like this:

   import com.oopuniversity.packages.PackageDemo;

This applies to any class that is not in the same package as the class on which you're working.  For classes within the same package the import statement is unnecessary.'

IDEs make this whole process really easy.  You tell them to create a new package, and they do so, creating all of the necessary directories for both java and class files.  You try to create an object and they can automatically figure out that you need an import statement and add it for you.  When they build the code, it's placed in the correct location.

At first this may seem like a needless complication, but it pays off as soon as you're doing any work that is not extremely basic in nature.

The rules for package names are simple.  While it's not hard and fast, stick to lower case letters.  Separate individual words with periods.  You can call them anything you like, but it's generally a good idea to go from less specific to more specific.  Most of the standard packages that come in the Java libraries start with 'java.' and most third party packages start off with the domain name of the developer (this 'com.oopuniversity') and are then followed by as many identifiers as needed for your purposes.  It is a good idea to organize this way, because if you use the same package names as someone else does you could badly confuse your ClassLoader and this leads to really irritating situations when you try to get programs to actually run.  In short, 'util' is a pretty bad package name, but 'org.mycompany.util' is better.  'org.mycompany.secretproject.util' is even better yet.

In summary:

Organize your code into packages.
Specify the package name at the top of your source file.
Import the classes you need by specifying their packages in import statements.

There are specific packaging rules I like to follow when building systems, related to how the code itself is structured.  I'll talk about those rules when it's appropriate.  Those are going to be more on the order of recommendations, but it won't hurt you (much) to go along with them.

Wednesday, November 12, 2014

Project Organization Part 1: Directory Layout

In our first post we set up a simplified project called HelloWorld.  That is of course, a very standard first program in virtually any language, designed to provide a minimal functional program to provide a bit of user output.  That's all well and good, but in the interest of getting something built I glossed over or just plain ignored some aspects of project setup.

First and foremost, we allowed the source code and the compiled .class files to sit in the same location.  I was tempted to avoid that even for the first post, but eventually decided it was best to just get something done and tackle that in a separate post.  So here we are.

As a general rule, I greatly prefer to set up my projects with two main directory trees, one for source files and one for build products.  Typically I'll use the names src and build for these directories.  You will find that once you start using an IDE this structure will tend to be built automatically for you, which will make it transparent and natural.

So let's take HelloWorld and convert it to a better structure:



Now we've got a couple of buckets for our files.  For now we'll ignore packaging and just rearrange the files.  Since class files can be regenerated at any time, we'll just get rid of HelloWorld.class.  We will then move HelloWorld.java to its new home.


Now let's rebuild our class file to make sure we can still operate.  Go into the build directory and run javac, but this time you'll have to enter a relative path in order for the system to find it.  After that you can, if you so choose, do a test run to make sure it still works correctly.




I mentioned earlier that we're not going to discuss packaging, but I do want to quickly mention that we still have not gone far enough with moving our files around.  The reason for this involves the way that Java loads classes, and has no real implications until you start assembling slightly larger programs.  Suffice it to say that we're not done yet, but we can wait a while before we get into that.  Next time around, we'll talk about functions, which will be a key concept you must understand before we get around to creating objects.

Getting Started with Java (Hello, World)

I spend some time on the subreddit /r/javahelp, and see many of the same questions and errors crop up again time after time.  People who are trying to learn how to program get caught up in the syntax, and wind up down the rabbit hole.

So let's take a look at the very basics of Java.

The basic unit of Java programming is the class.  We define a class by creating a text file (with a .java extension) according to some strict rules, then we compile the .java file to a .class file using the javac command.  Better yet, we use an Integrated Development Environment, but I will discuss that in a future post.

Your source code files, which is what we call the .java text files, can be created with any text editor.  Notepad will work fine for these early examples, but there are certainly better ones out there.  Even for your first efforts, you will want a clean work area free of clutter, so it is best to create a new directory somewhere on your hard drive for each project on which you will work.  I prefer to base everything under a "\Dev" directory so that all of my work is in one easily identifiable place.  Since my main system at home uses a solid state drive plus a storage drive, that means my work area is inside of "D:\Dev".  I'm going to write everything here as though I'm using the C: drive, though, since that's more likely to be what you are using.

We want to have a directory for our project, which will be where we go to do all of our work on any given task.  Finally, while this may not seem very important right now, it's best not to cluster your source files right there in the project directory.  So I like to have a 'src' directory in which to save my source code files.

So, since by convention our first project is "Hello World", we wind up saving our .java to the following directory:

C:\Dev\HelloWorld\src

There is one additional complication relating to source, which is what we call "packages".  I'll defer discussion of this for the time being, but they are set up in your workspace as directories off of the src directory above.

So, that being said, what does Hello, World look like in Java?  It quite literally cannot get any simpler than the following example:

HelloWorld.java

Everything here is necessary to the task at hand.  Let's go through it line by line:

public class HelloWorld {

Every java class needs to be declared.  While there are a few other possibilities for this line, this is the most common way in which you will declare your classes.  The word 'public' means this class can be seen (and ultimately used to do work) by any other class that knows about this project.  We are defining a class, and giving it the name 'HelloWorld'.  By convention we always start our classes with an upper case letter, and follow that with what is called "Camel Case", which means lower case words with upper case initial letters.

Finally, there is an opening curly bracket, which matches the curly bracket on the very last line.  Curly brackets (or braces) are going to be your close companions as you work with Java, so get used to them.  They are always 'balanced', meaning that each opening bracket '{' has to be matched by a closing bracket '}'.

public static void main(String[] args) {

Next up, we have 'main'.  Any command line Java program will start at main, and main is always declared the same way.  The only thing you can really change here is the name 'args', which is arbitrary.  Command line switches and parameters will be found in args, and although we aren't making use of them in this program, we still have to mention the possibility.  Again, we have an opening bracket.  Any 'method' (or 'function') you create in a Java class will have a set of brackets around its code.

System.out.println("Hello, world!");

Here's the only line that actually does something in our little demonstration.  It writes the literal value Hello, world! to the console output.  All Java programs (and indeed, all programs in most languages have 'standard output' and 'standard input' available by default for simple user interaction.

}
}

These two lines are just needed to balance the brackets.  The first closes the definition of "main", the second closes the definition of the class HelloWorld.

Presuming that a Java Development Kit is available and configured correctly, this can be built with the 'javac' command.:
Compiling HelloWorld
If we get no error messages, we should now have the file "HelloWorld.class" sitting here as well.


Now we can run it with the 'java' command:
Running HelloWorld

In a future installment, I will discuss further organization of the project space.  There are good reasons not to mix all the .java and .class files in one place.  Integrated Development Environments make all of these tasks simpler, and I definitely recommend obtaining IntelliJ IDEA or Eclipse or NetBeans (or all three).

View code here