Register your product to gain access to bonus material or receive a coupon.
Learn what it takes to build a professional, robust software system using Java, integrating the best features of Test-Driven Development.
° Gives you the skills to translate requirements into tests, and tests into working code
° Seamlessly integrates the new language features of Java 5 into the learning experience
° Based on the author's experience instructing classes using TDD as the driving force-- and TDD is a great source of immediate feedback
Agile Java is a valuable tutorial and reference. It introduces the Java languagewith no assumptions about a developer's background in Java, object-orienteddevelopment, or TDD. The book will also retain significant value as acookbook that readers will turn to time and again to learn how to approachTDD with respect to various language features.Teh author stresses the importance of TDD by showing coded tests for everyJava feature taught. A programmer learning with this book will understand howto translate oral requirements into tests, and tests into working code. Readersalso learn how TDD impacts the design of the system, and vice versa. In short,anyone who wants to understand what it takes to build a professional, robustsoftware system using Java will want this book. Agile Java will be ideally timedto coincide with Sun's forthcoming release of Java 5 (J2SE 1.5).
Agile Documentation: Specification by Example
Crafting Java with Test-Driven Development, Part 1: Getting Started
Crafting Java with Test-Driven Development, Part 10: Building the View
Crafting Java with Test-Driven Development, Part 11: Making Things Happen
Crafting Java with Test-Driven Development, Part 13: Nine Reasons Why You Should Be Using TDD
Crafting Java with Test-Driven Development, Part 2: Testing Equality
Crafting Java with Test-Driven Development, Part 3: Testing Hash Codes
Crafting Java with Test-Driven Development, Part 4: Shuffling and Dealing
Crafting Java with Test-Driven Development, Part 5: Handling Exceptions
Crafting Java with Test-Driven Development, Part 6: Refactoring Tests
Crafting Java with Test-Driven Development, Part 7: Adding Some Bulk
Crafting Java with Test-Driven Development, Part 8: It's Just Code
Crafting Java with Test-Driven Development, Part 9: Driving a User Interface
Crafting Java Code with Test-Driven Development: the Basics
Download the Sample
Chapter related to this title.
About the Author.
Foreword.
Acknowledgments.
Introduction.
Who Is This Book For?
What This Book Is Not
How to Use This Book
Exercises
Conventions Used in This Book
An Agile Overview.
What Is “Agile?”
What Is Java?
Why OO?
What Is an Object?
What Are Classes?
Why UML?
What Is Inheritance?
Why Test-Driven Development?
Setting Up.
Software You’ll Need
Does It Work?
Compiling Hello World
Executing Hello World
Still Stuck?
Lesson 1: Getting Started.
Testing
Design
A Simple Test
JUnit
Adding a Test
Creating a Student
Creating the Student Class
Constructors
Local Variables
Returning a Value from a Method
Assertions
Instance Variables
Summarizing the Test
Refactoring
this
private
Naming Conventions
Whitespace
Exercises
Lesson 2: Java Basics.
CourseSession
Enrolling Students
int
Initialization
Default Constructors
Suites
The SDK and java.util.ArrayList
Adding Objects
Incremental Refactoring
Objects in Memory
Packages and the import Statement
The java.lang Package
The Default Package and the package Statement
The setup Method
More Refactoring
Class Constants
Dates
Overload Constructors
Deprecation Warnings
Refactoring
Creating Dates with Calendar
Comments
Javadoc Comments
Exercises
Lesson 3: Strings and Packages.
Characters and Strings
Strings
StringBuilder
System Properties
Looping Through All Students
Single-Responsibility Principle
Refactoring
System.out
Using System.out
Refactoring
Package Structure
Access Modifiers
Using Ant
Exercises
Lesson 4: Class Methods and Fields.
Class Methods
Class Variables
Operating on Class Variables with Class Methods
Static Import
Incrementing
Factory Methods
Simple Design
Static Dangers
Using Statics: Various Notes
Jeff’s Rule of Statics
Booleans
Tests as Documentation
More on Initialization
Exceptions
Revisiting Primitive-Type Field Initialization
Exercises
Lesson 5: Interfaces and Polymorphism.
Sorting: Preparation
Sorting: Collections.sort
CourseReportTest
Interfaces
Why Interfaces
Implementing Comparable
Sorting on Department and Number
The if Statement
Grading Students
Floating-Point Numbers
Testing Grades
Refactoring
Enums
Polymorphism
Using Interface References
ArrayList and the List Interface
Exercises
Lesson 6: Inheritance.
The switch Statement
Case Labels Are Just Labels
Maps
Inheritance
Abstract Classes
Extending Methods
Refactoring
Enhancing the Grade Enum
Summer Course Sessions
Calling Superclass Constructors
Refactoring
More on Constructors
Inheritance and Polymorphism
The Principle of Subcontracting
Exercises
Lesson 7: Legacy Elements.
Looping Constructs
Breaking Up a Student’s Name
The while Loop
Comparing Java Loops
Refactoring
Looping Control Statements
The Ternary Operator
Legacy Collections
Iterators
Iterators and the for-each Loop
Casting
Wrapper Classes
Arrays
Refactoring
Exercises
Lesson 8: Exceptions and Logging.
Exceptions
Dealing With Exceptions
Checked Exceptions
Exception Hierarchy
Creating Your Own Exception Type
Checked Exceptions vs. Unchecked Exceptions
Messages
Catching Multiple Exceptions
Rethrowing Exceptions
Stack Traces
The finally Block
Refactoring
Logging
Logging in Java
Testing Logging
Logging to Files
Testing Philosophy for Logging
More on FileHandler
Logging Levels
Logging Hierarchies
Additional Notes on Logging
Exercises
Lesson 9: Maps and Equality.
Logical Operators
Short-Circuiting
Hash Tables
Courses
Refactoring Session
Equality
The Contract for Equality
Apples and Oranges
Collections and Equality
Hash Tables
Collisions
An Ideal Hash Algorithm
A Final Note on hashCode
More on Using HashMaps
Additional Hash Tables and Set Implementations
toString
Strings and Equality
Exercises
Lesson 10: Mathematics.
BigDecimal
More on Primitive Numerics
Integer Math
Numeric Casting
Expression Evaluation Order
NaN
Infinity
Numeric Overflow
Bit Manipulation
Java.lang.Math
Numeric Wrapper Classes
Random Numbers
Exercises
Lesson 11: IO.
Organization
Character Streams
Writing to a File
Java.io.File
Byte Streams and Conversion
A Student User Interface
Testing the Application
Data Streams
CourseCatalog
Advanced Streams
Object Streams
Random Access Files
The Student Directory
sis.db.DataFileTest
Static Nested Classes and Inner Classes
sis.db.DataFile
sis.db.KeyFileTest
sis.db.KeyFile
sis.util.IOUtilTest
sis.util.IOUtil
sis.util.TestUtil
Developing the Solution
Exercises
Lesson 12: Reflection and Other Advanced Topics.
Mock Objects Revisited
The Jim Bob ACH Interface
The Mock Class
The Account Class Implementation
Anonymous Inner Classes
Adapters
Accessing Variables from the Enclosing Class
Tradeoffs
Reflection
Using JUnit Code
The Class Class
Building the Suite
Class Modifiers
Dynamic Proxy
A Secure Account Class
Building the Secure Account Solution
The SecureProxy Class
Problems With Reflection
Exercises
Lesson 13: Mulithreading.
Multithreading
Search Server
The Search Class
Less Dependent Testing
The Server
Waiting in the Test
Creating and Running Threads
Cooperative and Preemptive Multitasking
Synchronization
Creating Threads with Runnable
Synchronized
Synchronized Collections
BlockingQueue
Stopping Threads
Wait/Notify
Additional Notes on wait and notify
Locks and Conditions
Thread Priorities
Deadlocks
ThreadLocal
The Timer Class
Thread Miscellany
Summary: Basic Design Principles for Synchronization
Exercises
Lesson 14: Generics.
Parameterized Types
Collection Framework
Multiple Type Parameters
Creating Parameterized Types
Erasure
Upper Bounds
Wildcards
Implications of Using Wildcards
Generic Methods
Wildcard Capture
Super
Additional Bounds
Raw Types
Checked Collections
Arrays
Additional Limitations
Reflection
Final Notes
Exercises
Lesson 15: Assertions and Annotations.
Assertions
The assert Statement vs. JUnit Assert Methods
Annotations
Building a Testing Tool
TestRunnerTest
TestRunner
The @TestMethod Annotation
Retention
Annotation Targets
Skipping Test Methods
Modifying TestRunner
Single-Value Annotations
A TestRunner User Interface Class
Array Parameters
Multiple Parameter Annotations
Default Values
Additional Return Types and Complex Annotation Types
Package Annotations
Compatibility Considerations
Additional Notes on Annotations
Summary
Exercises
Additional Lesson I: Swing, Part 1.
Swing
Getting Started
Swing Application Design
Panels
Refactoring
More Widgets
Refactoring
Button Clicks and ActionListeners
List Models
The Application
Layout
GridBagLayout
Moving Forward
Additional Lesson II: Swing, Part 2.
Miscellaneous Aesthetics
Feel
Tables
Feedback
Responsiveness
Remaining Tasks
Final Notes
Additional Lesson III: Java Miscellany.
JARs
Regular Expressions
Cloning and Covariance
JDBC
Internationalization
Call by Reference versus Call by Value
Java Periphery
What Else Is There?
Appendix A: An Agile Java Glossary.
Appendix B: Java Operator Precedence Rules.
Appendix C: Getting Started with IDEA.
IDEA
The Hello Project
Running Tests
Taking Advantage of IDEA
Agile Java References.
Index.
I am a software craftsman 1 . I have spent much of my software development career trying to be able to quickly build solutions to problems. At the same time I have tried to ensure that my solutions demonstrate carefully crafted code. I strive for perfection in code, yet I know that it is unattainable, particularly with the constant pressure from business to get product out the door. I take modest pride in the code that I build daily, yet I look on the very code that I wrote the day before and wonder, "what the heck was I thinking?" This is what keeps the craft challenging to me—the constant desire to figure out how to do things a little better the next time, and with a little less pain than this time.
Agile Java represents a successful approach to learning and mastering Java development. It is based on the way I have learned to best teach programming, and to learn new programming languages myself: using test-driven development (TDD). TDD is a technique that introduces a large amount of low-level feedback. This feedback allows you to more quickly see the results of your actions. Using TDD, you will learn how to craft Java code to produce solid object-oriented designs and highly maintainable, high quality systems.
I have used TDD in production systems for over three years, and am still amazed at what it does for me. It has improved the quality of my code; it has taught me new things each week; it has made me more productive. I have also created and taught language courses using TDD, both at my own company and at Object Mentor (who continues to teach their language courses with this approach).
Prior to learning TDD, I spent more than fifteen years learning, developing in, and teaching languages the "classic" way—without using tests to drive the development. The student builds and executes example code. The student obtains feedback on what the code is teaching by viewing the output from code execution. While this is a perfectly valid approach, my anecdotal experience is that using it results in less-than-ideal retention of language details.
In contrast, the high volume of rapid feedback in TDD constantly reinforces correct coding and quickly points out incorrect coding. The classic code-run-and-observe approach provides feedback, but at a much slower rate. Unfortunately, it is currently the predominant method of teaching programming.
Others have attempted more innovative approaches to teaching. In the 1990s, Adele Goldberg created a product known as LearningWorks designed for teaching younger students. It allowed a user to directly manipulate visual objects by dynamically executing bits of code. The user saw immediate results from their actions. A recent Java training tool uses a similar approach. It allows the student to execute bits of code to produce visual effects on "live" objects.
The problem with approaches like these is that they are bound to the learning environment. Once you complete the training, you must still learn how to construct your own system from the ground up, without the use of these constrained tools. By using TDD as the driver for learning, you are taught an unbounded technique that you can continue to use in your professional software development career.
Agile Java takes the most object-oriented approach feasible. Part of the difficulty in learning Java is the 'bootstrapping" involved. What is the minimum you must learn in order to be able to write classes of some substance?
Most books start by teaching you the prototypical first Java program—the "hello world" application. But it is quite a mouthful: class Hello { public static void main(String args) { System.out.println("hello world"); } } . This brief program contains at least a dozen concepts that you must ultimately learn. Worse, out of those dozen concepts, at least three are non-object-oriented concepts that you are better off learning much later.
In this book, you will learn the right way to code from the start, and come back to fully understand "hello world" later in the book 2 . Using TDD, you will be able to write good object-oriented code immediately. You'll still have a big initial hurdle to get over, but this approach keeps you from having to first understand not-very-object-oriented concepts such as static methods and arrays. You will learn all core Java concepts in due time, but your initial emphasis is on objects.
Agile Java presents a cleaner break from the old way of doing things. It allows you to pretend for a while that there was never a language called C, the syntactical basis for Java that has been around for 30 years. While C is a great language, its imprint on Java left a quite a few constructs that can distract you from building good object-oriented systems. Using Agile Java, you can learn the right way of doing things before having to understand these legacies of the Java language.
I designed Agile Java for new programmers who want to learn Java as their first language. The book can also be effective for programmers familiar with TDD, but new to Java, or vice versa. Experienced Java developers may find that going through Agile Java presents them with a new, hopefully better, way of approaching things.
This edition of Agile Java covers Java 2 Standard Edition (J2SE) version 5.0.
Sun has made available dozens of class libraries, or APIs (application programming interfaces), that enhance the core Java language. Some examples: JMS (Java Messaging Service) provides a definition for standard messaging-based solutions. EJBs (Enterprise Java Beans) provide a means of building component-based software for large enterprise solutions. JDBC (Java DataBase Connectivity) supplies a standard interface for interacting with relational databases. About a dozen of the advanced APIs are collectively known as J2EE (Java 2 Enterprise Edition). Many of the APIs require entire books for comprehensive coverage. There are dozens of books on J2EE.
This book covers only a few of the additional APIs at an introductory level. Technologies that are used pervasively in the majority of enterprise applications, such as logging, JDBC, and Swing, are presented in Agile Java. Some of the information (for example, logging) will teach you all you need to know for most applications. Other lessons (for example, Swing and JDBC) will teach you a basic understanding of the technology. These lessons will provide you with enough to get started, as well as where to go for more information.
If you are developing mobile applications, you will be using J2ME (Java 2 Micro Edition). J2ME is a version of Java geared toward environments with limited resources, such as cell phones. J2ME has some significant limitations in comparison to J2SE. This book does not discuss anything specific with respect to J2ME. However, most of the core techniques and concepts of Java development are applicable to the J2ME environment.
In order to use any of these add-on Java technologies, you must first understand the core language and libraries provided in J2SE. Agile Java will help you build that knowledge.
Agile Java is not an exhaustive treatise on every aspect of the Java language. It instead provides an agile approach to learning the language. Rather than give you all the fish, I teach you how to fish and sometimes where to find the fish. Agile Java will teach you the majority of the core language concepts. Indeed, upon completing the core fifteen lessons, you will be able to produce quality production Java code. However, there are bound to be a few esoteric language features and nuances that I do not cover in the book.
One way to become familiar with the dusty corners of the language is to peruse the Java Language Specification (JLS). The second edition of the language specification is available at http://java.sun.com/docs/books/jls. This edition covers versions of Java up to but not including J2SE 5.0. A third edition of the JLS is in the works at the time I write this. You can find a maintenance review version at: http://java.sun.com/docs/books/jls/java_language-3_0-mr-spec.zip
For additional understanding of what is in the Java API library, the Java API documentation and actual source code is the best place to go.
Agile Java is not a certification study guide. It will not prepare you for a certification exam. A good book on certification will teach you how to take a test. It will also teach you how to decipher (deliberately) poorly written code that shouldn't have been written that way in the first place. Agile Java will teach you instead how to write professional Java code.
Agile Java doesn't attempt to coddle you or distract you with flashing headlines and cute images. Learning to program is a significant challenge. Programming involves thinking and solving problems—it is not an easy undertaking for idiots or dummies. I've attempted to avoid insulting your intelligence in this book. That being said, I have tried to make Agile Java an enjoyable, easy read. It is a conversation between you and me, much like the conversations you will continue to have in your professional development career. It's also a conversation between you and your computer.
Some developers experienced in TDD will note stylistic differences between their approach and my approach(es) in Agile Java. There are many ways to do TDD. None of these techniques are perfect or ordained as the absolute right way to do things. Do whatever works best for you. Do what makes the most sense, as long as it doesn't violate the basic tenets set forth in Agile Java.
Readers will also find areas in which the code could be improved 3 . Even as a beginning developer, you no doubt will encounter code in Agile Java that you don't like. Let me know. Send in your suggestions, and I may incorporate them in the next edition. And fix your own implementations. You can improve almost any code or technique . Do!
After the first lesson in Agile Java, the tests appear wholesale, as if they were coded in one fell swoop. This is not the case: each test was built assertion by assertion, in much smaller increments than the book can afford to present. Keep this in mind when writing your own code—one of the most important aspects of TDD is taking small, small steps with constant feedback. And when I say small, I mean small! If you think you're taking small steps, try taking even smaller steps.
The core of Agile Java is fifteen lessons of about 30 pages each. You will start with baby steps in Java, TDD, and OO. You will finish with a strong foundation for professional Java development.
The core lessons are sequential. You should start at lesson 1 and complete each lesson before proceeding to the next. Once you have completed section 1, you should have a solid understanding of how to build robust Java code.
If you haven't completed the core lessons, you should not assume you know how to write good Java code! (Even if you have completed the lessons, you're not an expert... yet.) Each lesson builds upon the previous. If you stop short of completing the lessons, your lack of full understanding may lead you to construct poor code.
Each lesson starts with a brief overview of the topics to be discussed. The remainder of the lesson is a narrative. I describe each language feature in the text, specified by test code. I demonstrate each feature in a corresponding code implementation. I have interspersed discussions of TDD technique, OO principles, and good development practices in these lessons.
I've supplied three additional lessons to cover a few more Java topics. Two of the lessons present an introduction to Java's tool for user interface development, Swing. These two lessons will provide you with enough information to begin building robust user interface applications in Java. But the bigger intent is to give you some ideas for how to build them using TDD. The third additional lesson presents an overview for a number of Java topics, things that most Java developers will want to know.
For the most effective learning experience, you should follow along with the lessons by entering and executing each bit of test and implementation code as I present it. While the code is available for downloading (see the next paragraph), I highly recommend that you type each bit of code yourself. Part of doing TDD correctly is getting a good understanding of the rhythm involved in going back and forth between the tests and the code. If you just download the code and execute it, you're not going to learn nearly as much. The tactile response of the keyboard seems to impart a lot of learning.
However, who am I to make you work in a certain way? You may choose to download the code from http://www.LangrSoft.com/agileJava/code . I've organized this code by lesson. I have made available the code that is the result of working each lesson— in the state it exists by the end of the lesson . This will make it easier for you to pick up at any point, particularly since many of the examples carry through to subsequent lessons.
Each of the fifteen core lessons in Agile Java has you build bits and pieces of a student information system for a university. I chose this single common theme to help demonstrate how you can incrementally build upon and extend existing code. Each lesson also finishes with a series of exercises. Instead of the student information system, the bulk of the exercises, provided by Jeff Bay, have you build bits and pieces of a chess application.
Some of the exercises are involved and quite challenging. But I highly recommend that you do every one. The exercises are where the real learning starts—you're figuring out how to solve problems using Java, without my help. Doing all of the exercises will give you a second opportunity to let each lesson sink in.
1 See McBreen2000
2 Don't fret, though: you'll actually start with the "hello world" application, in order to ensure you can compile and execute Java code. But you won't have to understand it all until later.
3 A constant developer pair would have helped.
© Copyright Pearson Education. All rights reserved.