<em>Reasoning: Consider that the programmer looking at your code is probably examining
each method starting at the top and working down. When encountering a loop, the first
thing the programmer wants to know is what terminates the loop. If you have that logic at
the bottom, it is harder to read. Further, many less experienced programmers are not
familiar with do..while, but may be required to modify your code.</em>
So rather than:
<em>Reasoning: Using "return" in the middle of a method makes it difficult to
later break the method into smaller methods. It also forces the developer to consider more
than one exit point to a method. </em>
<em>Reasoning: Using "continue" makes it difficult to later break the
construct into smaller constructs or methods. It also forces the developer to consider
more than one end point for a construct. </em>
<em>Reasoning: Using "break", other than for switch statement control, makes
it difficult to later break a construct into smaller constructs or methods. It also forces
the developer to consider more than one end point for a construct. </em>
Use an extra line for the increment or decrement.
Examples:
Try to not declare a variable until just before it is used unless it will impact the
performance of the code.
Examples:
I have worked on no less than five projects where the standard, when I arrived, was to have a build.properties file
right
next to the build.xml file. Both go into version control. What always happens is that somebody changes a property to
make the build work on their system. Then they check in their changes and everybody else's build breaks.
The most common first solution is to simply not check in that file. This works kinda-okay until somebody accidentally
checks it in. Then at least one person's properties file gets wiped out and .... no backup. And if you are new to
the
project, you need somebody to feel sorry for you and e-mail you a copy of a properties file to get a start. Sure,
there
can be documentation - but I have yet to see the documentation be kept up. And I have experienced multiple projects
where the solution was to develop to the documentation and when it doesn't work, exchange e-mail with somebody until
the
documentation works.
The next solution is to put build.properties into your home directory and have ant find it there. This works until
you
have more than one project. Then you change it to flooberproject.properties or start having properties like
flooberproject.db.schemaname. This solves the problem of somebody accidentally checking in the properties, but
incoming
developers still need to depend on somebody sending them a properties file.
The next improvement is to make a conf directory within the project that is in version control. This directory
contains lots of
username.properties files. This solves the incoming engineer problem and brings all the pluses that come with
version
control, but there are a couple of minor problems introduced. One is people that have the same username. Or the same
person (with the same username) developing from two different boxes. Another is that sometimes you have data that
you
are not comfortable with moving into version control (a password perhaps?).
A) Have as few properties defined outside of build.xml as possible.
I have seen projects that have hundreds of build properties defined. I'm sure when they started out they had two
or
three. And then there were forty. And then it just grew and grew and nobody could come up with a clear reason to
not
just add a few more now and then. Here's one reason: Anybody new coming to the project needs to understand
these before they can configure them correctly. It is far earier to understand eight properties than three hundred.
I think that if any project has more than 15 properties, it should be
considered a
bad smell and something should be done. Maybe the project is too big and should be broken up. Maybe there are a
lot of
things that can be moved into build.xml - not every developer needs it to be different? Maybe some coding
standards
could eliminate some properties? Maybe some properties are not being used any more?
The focus of this article is properties that change from developer to developer. Once you have just a few
properties to manage, everything else becomes much easier to solve. I have to say that having fewer properties
is (IMO) ten times more important than what is being covered in this article. And it would be silly to write an
article that simply says "use fewer properties." I only mention it because it is such a serious problem for some
shops and there isn't a better time/place to express it.
B) Try to keep as many properties as possible in version control.
If the properties you are currently using are in version control, then when new people come to the project, they
can
look at the most recent property files that other developers are using and emulate those properties files.
Further, if
you make changes and those changes turn out to be poor, well you always can look up your older properties in
version
control!
C) Provide a mechanism for sensitive properties to not be in version control.
Database passwords are an example of something that you might want to keep out of version control. But when we
are
talking about a development box, and the database is configured to not talk to anybody outside of the box ...
well,
maybe it isn't such a big deal. As long as some people can have security if they want it and some people can go
the
version control route if they want that.
D) Provide a mechanism to share build properties between projects.
If you have really good communication between teams and within teams, you will avoid duplicated effort and use
shared
resources. If any one team will have, say, eight projects they are working on during a year, and some common
property
needs to change, it just seems wise to facilitate making the change just once and all of the projects still
build
properly.
E) Properties need to be self documenting.
Be considerate of engineers coming to this project. Also be considerate of the other engineers on a project when
you
are adding properties.
A doc file, a readme file or a wiki can help, but they can easily become outdated and lead to confusion.
Actual, functioning properties files make for an excellent form of documentation. Using "fail unless" ant tasks
can
help too!
This is just one humble solution. I suspect that there are many others that will work great. And I can't help but
think that as the years pass, this solution will be enhanced.
I'm a big fan of "do the simplest thing that could possibly work". In this case, all of the solutions
mentioned
earlier are simpler than what I'm about to propose. But the needs do exceed each of these solutions. So while this
hybrid solution does add four lines to the simplest ant script, it does solve several problems. And
when combined with making it a standard (as it now
is for JavaRanch projects)
there is predictability.
The reason why I call this a hybrid is that it attempts to collect properties from any one of three places used
in the previous solutions! Each solution has strengths and weaknesses. With all three you have all of the strengths
and you have eliminated all of the weaknesses. I think that the optimal use of the hybrid approach is to keep as
many properties as possible within version control (a config
directory in the project). Keep sensitive properties in one of the user home properties files. Keep properties
shared between
projects in the common property file.
Drop these ant tasks into the init of your build.xml to pull this off:
So when I'm working on the floober project on windoze, I can put my properties in one of these three files:
And if I sometimes work from home, where my login is the same, I can define "config.filename" in build.properties in
my home dir as, say,
"paul_home"
and then keep the rest of my properties in paul_home.properties in the conf directory for all projects.
Since ant always uses the first definition of a property and ignores any attempt to change a property, you can
declare
some default properties in build.properties and override them with project specific properties in your home dir. You
might be tempted to read in the config dir properties first, but that will eliminate the ability to define
config.filename
without adding yet another properties file.
Old, moldy programming pearl: Debug only code. Comments lie.
Any time you leave something to the discipline of a human, you are looking for mistakes to be made. I've worked in
shops
where the technique to let you know about new properties was to send you an e-mail. So the next time you do a "get
latest"
from version control, you need to remember to look that e-mail up again and work the new properties in and test
to make sure you did it right. Some shops use web pages or wiki pages. Some do both e-mail and wiki. Some put
comments in the ant files. The problem with all of these is that things change, people forget to send the info,
look up the info, or .... well ... all sorts of common, natural human stuff. And then it takes time to resolve
things.
Using the approach where properties go into version control helps a lot. If your build isn't working now and the
last
time you got the latest code was three hours ago, then somebody checked something in within the last three hours.
Take a look at the config directory - if there is a file there that is less than three hours old, you found your
culprit. A diff to the last version of the file will show you new or changed properties.
What is proposed next is a pretty significant improvement. It does depend on the developer to remember to add one
thing
to the ant script, so there is still a hole in this process. But if that developer can remember this one thing,
all of the other developers don't need to be as disciplined.
For every property that needs to be defined by a developer, use fail/unless tags. Like so:
Now, every time you have a required property, add one fail/unless tag. The next time the other six people on your
team
tries to build, each build will fail and a message will spell out exactly what to do.
[Bonus Trick!] Instead of using fail/unless, simply declare a property after reading in the property files. It will
act as a default. If somebody wants that value to be different, they can specify what they want in one of their property files!
Ant is a fantastic tool. And now I'm ready for whatever is going to replace ant. I tinkered with maven for a while
and ended up going back to ant. I had high hopes for gravy (groovy plus ant) and it doesn't seem to have caught on.
As a Java programmer, I would like somebody to come up with something that lets me do loops and have a little more
control over my build. Something that takes into account multiple developers, code re-use, cruise control, IntelliJ,
sub projects, common projects, and ... properties!
There are many ways to do things well. And there are at least as many ways to do the same things poorly.
When many developers come together to do one project, there can be long debates on which approach
is "best" or "right". These discussions can, in the long run, take hundreds of man hours to resolve. For larger
organizations, multiple projects will need to integrate - different ideas of "best" can lead to more debate and
serious integration issues.
This document is a feeble attempt to outline one approach to project build issues. Some goals of this document include:
reduce debate time within teams and between teams
provide vocabulary between developers and between teams
smooth integration between components developed by different teams
improve ramp time for new developers and developers that might be shifting between teams/projects
ease the integration of multiple projects into a continuous integration environment
Provide description attributes for all targets that are intended to be exercised directly by the developer. This makes only
those targets viewable under "ant -p". Many IDE's will take advantage of this also. Do not provide a description for
targets that are not to be exercised directly by the developer.
1) Have as few properties outside of build.xml as possible!
2) Properties are gathered with the following ant tasks:
3) Put all properties in the config directory unless there is a powerfully compelling reason to put them in the home directory.
4) Use "fail unless" tasks for all properties that need to be defined outside of build.xml:
5) Have as few properties outside of build.xml as possible! (yes! This is the same as 1!)
1) Each developer has a database instance on their own development system.
2) For each table and view in the database, there is one .sql file in the src/db directory for creating that table or view.
3) The ant target "db" will drop all tables and views from the database and recreate a fresh instance of the database.
1) "ant vbuild" must successfully run from the command line before checkin.
2) If cruise control is not yet running for the project, "ant ffvbuild fntest" must successfully run from the command line before checkin.
<EM>Grab your marshmallows and a stick and gather 'round the campfire for some Java stories. The Ranch writers won't be winnin' any literary prizes, that's fer sure. But ya still might learn a thing or two.</EM>
Getting in Touch with your Inner Class
A bittersweet, yet ultimately uplifting story.
Rating: INTERMEDIATE
Prerequisites: Understand Classes, Objects, Static vs. Instance members
Evil Unit Testing
Everybody goes on and on about unit tests. Sure, sure, sure, it is all well and good until it starts to SCREW UP EVERYTHING! A few minutes with this article will make everything right as rain.
Rating: INTERMEDIATE
Prerequisites: having written a few small programs.
Cup Size
A tale of Java variables
Rating: VERY BEGINNER
Prerequisites: a pulse
Pass-by-Value Please
Cup Size.. the story continues
Rating: BEGINNER
Prerequisite:Cup Size
How my Dog learned Polymorphism
You too can learn one of the most powerful concepts in all of OOP-land.
Rating: BEGINNER++
Prerequisite: Understand Classes, Objects and References
Better Enterprise/Network Monitoring with Component Diagnostics
When Captain Picard asks for a Level 3 diagnostic, what, exactly, does that mean? If your component goes stupid, do you want to fix it before your boss finds out? The alternative might be users calling customer service, calling the veep who calls your boss who ... well .... you get the idea.
Rating: INTERMEDIATE
Prerequisites: having written a server component.
Evil Ant Build Properties
So you need to check your code in, but when you do a "get latest" on version control, the build breaks. You check with the guy that checked in the stuff that doesn't work and "well, it works for me!" -- he's checked in some environment stuff that works on his system, but not yours. There are some solutions, but ... a lot of those solutions have worse problems! This article explores several different lousy solutions and recommends a hybrid solution - not perfect, but a big improvement!
Rating: ADVANCED
Prerequisites: having worked in a multi developer environment.
Cat and Mouse Games with Bits
Bit manipulations in Java
Rating: BEGINNER+
Prerequisite:Cup Size
Uncle Martin's Ghost Stories
Tales of the Unified Modeling Language (UML), Rational Unified Process (RUP), and Extreme Programming (XP) from Martin Fowler.
Rating: None
Prerequisite: None
To pass the SCJP you must:
1. STUDYYou gotta read books; you gotta write some code. Give yourself 3 months (less if you're a C++ programmer).
Get some examples from the CodeBarn, and stories at the Campfire.
The SCJP exam is now for Java2 (Java language version 1.2), but you can still take the 1.1 exam. The Java2 certification is almost identical to the Java 1.1 exam, but adds two new objectives: Collections and GridBagLayout.
2. PRACTICEwith the Rule Roundup Game and then mock exams. Find a great list o' links at Marcus Green's site.
Make flash cards for yourself.
Get your friends to quiz you.
Explain polymorphism to your dog.
3. REGISTER(and pay around US $150). See Sun's certification area for info on registration.
4. Get some SLEEP(can't help you with that one)
5. TAKE THE TESTYou'll take it at an authorized examination center. They will have security to make sure you don't take anything in, or out, and that you are the registered person (can't send a Java Guru in to take it for you).
About 2 hours, 60 questions. There's plenty of time, but the questions are HARD. Shockingly hard.
But not so bad if you do steps 1 and 2 and 4.
How do you know if you're ready?
If you're over 29 (in human years) -- and you can trust the CowGirl on this -- reread step 4.
This is stuff that people have done in the past that resulted in being asked to do it over.
This is by no means a complete list, but it does show the most common problems.
The homework must exactly meet the style guidelines.
By far, the most common problem during the first pass of the first assignment is
not following the Style Guide.
Try to not declare a variable until just before it is used.
This isn't C.� See section 3.3 of the style guide for more info.
Try to initialize all variables when they are declared.
Again, a common problem with old C programmers.
Start loops at zero.
Start for loops at zero if you can.� This usually makes your programming life easier in
the long run.
Use a for loop any time that you know in advance how many times you are going to do a loop
And in this assignment, you know in advance that you will write the name 100 times.
If you have a lot of computations inside of your loop that always
come up with the same result, it would be wise to move that computation outside of the
loop, store it in a variable and refer to that variable inside the loop.
Double check what the class name should be for the assignment.
Use the name of the assignment (also seen in the sentence "In other words, I want to type ...")
Don't add extra stuff unless specifically mentioned ( the KISS principle ).
You can easily make this program test for a million things and the program would be two
million lines long.� But realistically, this program is for you to get a tiny amount of
exercise using loops and, for the second half, math.� You don't need to test for
multiple names, or if the name is too big.� You are the only person that will be running
the program.� If you choose to pass in bizarre data, it is okay if the program crashes.
OOP is a great thing. But that doesn't mean it's the best solution for all problems.
The important thing is good, simple, clean, readable code. In this case, adding object
stuff just complicates things.
Page maintained by
[url=https://coderanch.com/wiki/659748/ActiveStaffMarilyn de Queiroz[/url]
Write a program that will read in a number from the command line and tell me if it is
even or odd.
In other words, I want to type
and see
To do this, you will need to know how to:
Instructor's solution:
Page maintained by
Marilyn de Queiroz
"package" (if used) must always come first.
"import"s are next.
Any non javadoc comments are next.
Any javadoc class documentation is next.
The class is last.
Only one class per file (excepting inner classes).
Example:
There once was a wise servant who saved the life of a princess. The king promised to
pay whatever the servant could dream up. Knowing that the king loved chess, the servant
told the king he would like to have grains of wheat. One grain on the first square of a
chess board. Two grains on the next. Four on the third, and so on.
There are 64 squares on a chessboard.
Write a program that shows how many grains were on each square and the total number of
grains.
In other words, I want to type
and see
etc.
To complete this assignment, you will need to find a class in the Java standard library
that you have not used yet. The search for this class is the real meat of this assignment!
Instructor's solution:
After you have tied up this assignment, lasso the next one:
Assignment Java-7 (Sum)
Page maintained by
Marilyn de Queiroz
Write a program that will read in a name from the command line and write it out 100 times.
In other words, I want to type
and see
To do this, you will need to know how to:
If you have completed the first pass of the assignment, take a look at these
'common mistakes' before you submit it.
It might save you a lot of time.
Hint: Instructor's solution is 20 lines long, including 2 blank lines. **
Formatting is not necessary, but modify Java-1a so words are never split up.
Assume that the console is 80 characters wide.
In other words, I want to type
and see
Hint: Instructor's solution is 26 lines long, including 2 blank lines and one comment line.
** Your assignment will most likely not be the same size as the instructor's solution.
This information is provided because some students have turned in assignments that are
far more complex than required. This information gives you an idea of how sophisticated
your solution should be.
After you have tied up this assignment, lasso the next one:
Page maintained by Marilyn de Queiroz
All identifiers use letters ('A' through 'Z' and 'a' through 'z') and numbers ('0'
through '9') only. No underscores, dollar signs or non-ascii characters.
Hungarian Notation violates OO abstraction and is not to be used.
All class and interface identifiers will use mixed case. The first letter of each word
in the name will be uppercase, including the first letter of the name. All other letters
will be in lowercase, except in the case of an acronym, which will be all upper case.
Examples:
Customer
SalesOrder
TargetURL
URLTarget
Package names will use lower case characters only. Try to keep the length under eight
(8) characters. Multi-word package names should be avoided.
Examples:
common
core
lang
All other identifiers, including (but not limited to) attributes, variables, methods
and parameters will use this default naming convention. This includes final identifiers
(using all upper case, as traditionally done in C, is a violation of OO abstraction). The
first letter of each word in the name will be uppercase, except for the first letter of
the name. All other letters will be in lowercase, except in the case of an embedded
acronym, which will be all uppercase. Leading acronyms are all lower case.
Examples:
customer
salesOrder
targetURL
urlTarget
Okay, saddle up folks.
We're gonna git some real life experience writin' actual java code!
Before you get going, you should read [url=http://javaranch.com/drive/about.jsp]about
the cattle drive[/url]. It explains a few things worth knowin!</em>
Here we go!
Read the Java programming tutorials, find Java programming examples and learn some Java programming basics in the cattle drive
Get the book
<em>Just Java 2</em>
by Peter van der Linden.
Download the Java SE Development Kit 7
<!-- J2SE and J2EE SDKs -->
from Sun. If you are trying to learn Java you shouldn't use an IDE. Otherwise, you learn the IDE instead of learning Java. I generally use the JDK for all of my Java work.
It is possible that once you have installed the JDK, everything will work fine as is.
If you are not one of the lucky ones, you may need to adjust your PATH and CLASSPATH
environment variables. Instructions are included with the JDK and help specific to you can
be obtained at the campfire in the Cattle Drive (java college) forum.
I put all of my stuff into a directory called java (off of my root, C:\, in Windows and
off of my home directory in unix). On my windows machine,
my PATH includes
and
my CLASSPATH is set to
Here is a program that you can cut and paste to make sure that you have everything set
up correctly. Make sure you put it into a file called HelloWorld.java (case is important!
even on Windows computers):
Make sure that you paste this into a text editor (like notepad) and not a word
processor. A word processor will stick a bunch of extra formatting text into the file.
Pull up a console (DOS) or terminal window and put the HelloWorld.java file into your
java directory. Make the java directory your current directory. Type
and press enter. Remember: case is still very important, even on Windows computers. If
the program compiles without flaw, you will get your command prompt back. Otherwise, go to
the Cattle Drive (java college) forum and tell us what went wrong.
To run your program, type
and press enter. You should then see "hello world!" on your screen. If you
don't, post a message on the Cattle Drive (java college) forum.
Read chapters 1 and 3 in "Just Java 2".
Chapter 1 will give you a good overview of what Java is all about.
<!--On page 3, Mr. van
<br /> der Linden offers to take you on a journey to compile a sample program. That program is a
<br /> little biggish for my tastes on a first whack. I suggest that you browse through that
<br /> without doing the actual work.</p> <p> Stop at the part about exceptions.
<br /> We'll look into that later. -->
Chapter 3 is going to give you an idea of the nuts and bolts of Java. The chapter mentions
"unicode" - this can be tough reading for a beginner. It also covers autoboxing and
unboxing (new in Java 5). You don't have to memorize this stuff, just kinda browse it.
Most of the chapter is about the different primitive types (I like to call them the
atomic types). This is stuff you really need to be familiar with.
You might want to read the section on Strings twice! You can just browse the sections on
byte, short and float since you won't be using those types for a while.
After the first couple of assignments, you will want to read chapters 4, 7, and 9.
Chapter 4 will introduce you to branching constructs and how to organize your statements.
Just browse the stuff on "do..while" and "continue" - you should know that it exists,
but I don't want you to use it.
Chapter 7 will have a thorough introduction to identifiers, and operators.
Make sure you thoroughly understand comments. Browse the keywords. There
will be some discussion on classes and objects - don't get too concerned with that yet.
We'll cover that later.
Chapter 9 talks a bit about arrays. Stop at the part about the Math package.
We'll look into that later.
You may want to go to Style Guide before sending me your
completed assignments.
Have you read about the Cattle Drive yet?
Yep? Then let%27s git them dogies movin%27.
Page maintained by
Marilyn de Queiroz
Playtime diversion: Paul Wheaton, who wrote the original Java College, now dabbles in permaculture. He%27s a certified master gardener and has written articles on organic lawn care, proper use of diatomaceous earth and a new way of raising chickens. His research into less toxic living prompted him to write about using cast iron skillets and a healthier way to control fleas in the home.
You can follow Paul%27s future work on his permaculture blog, his Missoula blog or by following his permaculture podcasts or permaculture videos.
Yep, there's plenty o that here.
But before you start diggin holes all over the place we want to let you know that
JavaRanch isn't a script archive or code mill where ya go to grab code, fight with
it, and dump it into yer project without knowing what it does and how it works. Our
goal here is to try an guide greenhorns down the path to learnin how these darn
things work for themselves.
Most of our code is kept in the Code Barn
but that's not the only place where you'll find it.
Every so often, when the critters don't need tending and the fishin ain't all that good,
we release a new edition of the
JavaRanch Journal.
They say a code sample is worth a thousand words (or was that a picture?) but that don't
mean that there ain't no merit in spillin a thousand words if it helps you to understand
what something does before givin to ya.
Heck some concepts are just hard to understand, even with the code starin ya straight
in the face. Sometimes it makes sense to light a fire, sit back, and have someone
explain it to ya in plain ol English; comparin it to simple things that ya already
know about.
So mozey on over to the Camp Fire
and see if it don't help to make those bits o code fall into place.
Still can't find what yer lookin fer, or still don't quite understand what that piece
of code does? Well then, head on over to the
Saloon. That place is always full of people
you can ask. There're lots of code samples there as well.
Shy about asking questions in a saloon? Not sure you know the best way to approach
folks with your question? Well we've all been there. We even wrote a guide to
askin questions there. What if the question's been asked and answered lots
o times aleady? When that happens, someone usually takes a little time to put a new
entry in our Frequently Asked
Questions (FAQ) section. Go over and take a look.
Some of the folks over there like talkin so much, we gave em their own
Radio Show.
(sshhh, don't tell them this but... They ain't really on the radio. It's one o
those blog thingys but, either way, there are plenty o code samples there to
go along with what their talkin about)
Now we gave you the shovel and we just told you where to start diggin but you
say you've got a stagecoach to catch and don't have time to dig through all
those pages? Well the FAQ page and the saloon both have them new fangled
search tools on em so you
could try using them and see if it don't get ya just what you're lookin fer.
Now you help yourself to as much as you like, it's all free.
We're just hoping you'll stick around a bit and maybe help out some of newer
greenhorns that might come wandering in. Now I'd love to hang around and jaw
with ya all day but I'm late fer my nap.
Thanks fer stopping by.
written by Ben Souther
2) For any database change, it takes a great deal of discipline to find all
of the table names and column names used throughout your code that now
function differently. Even the slightest lack of discipline results in
a bug that might not be discovered until run time. Strong typing eliminates
this problem. This program (Jenny) provides the strong type checking.
For each table and view in a given database, Jenny will create a java source class file. Each of these classes will provide
a collection of general purpose methods for working with the table/view. They will also provide a list of all the column
names, the table/view name and an inner class called Row that can be used to manipulate a single row in the table.
Many tables have a primary key that is a non-nullable integer called "tablenameID" or sometimes "ID". If Jenny
finds this, she will add extra methods to the generated source for working with the primary key.
This same code using plain JDBC could be 10 to 40 lines long depending on
how it would be implemented. You would need to get a connection, create a
statement, build your sql string, exceute your statement, wade through the
result set, and each of these things need try/catch/finally blocks! Don't
forget to close your connection, statement and result set!
Download jr.jar
From the command line:
Page maintained by
Marilyn de Queiroz