376 Head First Software Development

Head First Software Development

  by Dan Pilone and Russ Miles Copyright © 2008 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.

  Series Creators: Kathy Sierra, Bert Bates Series Editor: Brett D. McLaughlin Design Editor: Louise Barr Cover Designers: Louise Barr, Steve Fehler Production Editor: Sanders Kleinfeld Indexer: Julie Hawks Page Viewers: Vinny, Nick, Tracey, and Corinne Printing History:

  December 2007: First Edition.

  Vinny, Tracey, Russ and Corinne

  Nick and Dan

  The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations,

  Head First Software Development, and related trade dress are trademarks of O’Reilly Media, Inc. Java and all Java-

  based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly Media, Inc. is independent of Sun Microsystems. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. No sleepovers were conducted in the writing of this book, although one author did purportedly get engaged using his prototype of the iSwoon application. And one pig apparently lost its nose, but we’re confident that had nothing to do with the software development techniques espoused by this text. TM TM

  ™ This book uses RepKover , a durable and fl exible lay-fl at binding.

  ISBN-10: 0-596-52735-7

  ISBN-13: 978-0-596-52735-8

  table of contents

Table of Contents (Summary) Table of Contents (the real thing) I nt ro

  Who is this book for? xxvi We know what you’re thinking xxvii Metacognition xxix Bend your brain into submission xxxi Read me xxxii

  The technical review team xxxiv Acknowledgments xxxv

  Intro xxv 1 great software development: Pleasing your customer 1 2 gathering requirements: Knowing what the customer wants 29 3 project planning: Planning for success 69 4 user stories and tasks: Getting to the real work 109

  5 good-enough design: Getting it done with great design 149 6 version control: Defensive development 177 6.5 building your code: Insert tab a into slot b... 219 7 testing and continuous integration: Things fall apart 235 8 test-driven development: Holding your code accountable 275 9 ending an iteration: It’s all coming together... 317

  10 the next iteration: If it ain’t broke... you still better fix it 349 11 bugs: Squashing bugs like a pro 383 12 the real world: Having a process in life 417

Your brain on Software Development. You’re sitting around trying

  to learn something, but your brain keeps telling you all that learning isn’t important. Your brain’s saying, “Better leave room for more important things, like which wild animals to avoid and whether naked rock-climbing is a bad idea.” So how do you trick your brain into thinking that your life really depends on learning how to develop great software?

  table of contents great software development

Ple a sing your c ust om e r If the customer’s unhappy, everyone’s unhappy!

  Every great piece of software starts with a customer’s big idea. It’s your job as a professional software developer to bring those ideas to life. But taking a vague

  1 idea and turning it into working code—code that satisfies your customer—isn’t

  so easy. In this chapter you’ll learn how to avoid being a software development casualty by delivering software that is needed, on-time, and on-budget. Grab your laptop and let’s set out on the road to shipping great software.

  Tom’s Trails is going online

  2 Most projects have two major concerns

  3 The Big Bang approach to development

  4 Flash forward: two weeks later

  5 Big bang development usually ends up in a big MESS

  6 Great software development is...

  9 Getting to the goal with ITERATION

  10 Each iteration is a mini-project

  14 Each iteration is QUALITY software

  14 T he Goa l The customer WILL change things up

  20 It’s up to you to make adjustments

  20 But there are some BIG problems...

  20 Iteration handles change automatically (well sort of)

  22 Your software isn’t complete until it’s been RELEASED

  25 Tools for your Software Development Toolbox

  26 You’re this far down the The original goal...

  

path towards delivering

great software You’ve been iterating to

  ...but now the aim for the goal... goal has moved!

  table of contents gathering requirements

K now ing w hat t he c ust om e r w a nt s You can’t always get what you want... but the customer better!

  Great software development delivers what the customer wants. This chapter is all about talking to the customer to figure out what their requirements are for your software.

  inside your customer’s head. That way, by the time you finish your project, you’ll be confident you’ve built what your customer wants... and not just a poor imitation.

  Orion’s Orbits is modernizing

  30 Talk to your customer to get MORE information

  33 Bluesky with your customer

  34 Sometimes your bluesky session looks like this...

  36 Find out what people REALLY do

  37 Your requirements must be CUSTOMER-oriented

  39 Develop your requirements with customer feedback

  41 User stories define the WHAT of your project... estimates define the WHEN

  43 Cubicle conversation

  47 Playing Planning Poker

  48 Put assumptions on trial for their lives

  51 A BIG user story estimate is a BAD user story estimate

  54 The goal is convergence

  57 The requirement to estimate iteration cycle

  60 Finally, we’re ready to estimate the whole project

  1/2

  1

  

2

  3

  5 days day day days days days

  8

  13

  20

40 100

? days days days days days

  table of contents project planning

Pla nning for suc c e ss Every great piece of software starts with a great plan

  In this chapter you’re going to learn how to create that plan. You’re going to learn how to work with the customer to prioritize their requirements. You’ll define iterations that you

  3 and your team can then work towards. Finally you’ll create an achievable development plan that you and your team can confidently execute and monitor. By the time you’re done, you’ll know exactly how to get from requirements to milestone 1.0.

  Customers want their software NOW!

  70 Prioritize with the customer

  73 We know what’s in Milestone 1.0 (well, maybe)

  74 If the features don’t fit, re-prioritize

  75 More people sometimes means diminishing returns

  77 Work your way to a reasonable milestone 1.0

  78 Iterations should be short and sweet

  85 Comparing your plan to reality

  87 Velocity accounts for overhead in your estimates

  89 Programmers think in UTOPIAN days...

  90 Developers think in REAL-WORLD days...

  91 When is your iteration too long?

  92 Deal with velocity BEFORE you break into iterations

  93 Time to make an evaluation

  97 Managing pissed off customer Managing pissed off customers

  98 The Big Board on your wall 100 How to ruin your team’s lives 103

  table of contents user stories and tasks

Ge t t ing t o t he re a l w ork

  It’s time to go to work. User stories captured what you need to develop, but now

  it’s time to knuckle down and dish out the work that needs to be done so that you can bring those user stories to life. In this chapter you’ll learn how to break your user stories

  4 into tasks, and how your task estimates help you track your project from inception to

  completion. You’ll learn how to update your board, moving tasks from in-progress, to complete, to finally completing an entire user story. Along the way, you’ll handle and prioritize the inevitable unexpected work your customer will add to your plate.

  Introducing iSwoon 110 Do your tasks add up? 113 Plot just the work you have left 115

  Add your tasks to your board 116 Start working on your tasks 118

  A task is only in progress when it’s IN PROGRESS 119 What if I’m working on two things at once? 120 Your first standup meeting... 123 Task 1: Create the Date class 124

  Standup meeting: Day 5, end of Week 1... 130 Standup meeting: Day 2, Week 2... 136

  We interrupt this chapter... 140 You have to track unplanned tasks 141

  Mark, database expert

  Bob the junior developer. Velocity helps, but... 144

  Unexpected tasks raise your burn-down rate 143 and SQL blackbelt.

  We have a lot to do... 146 ...but we know EXACTLY where we stand 147

  Velocity Exposed 148 Laura the UI Guru.

  table of contents

  Good design helps you deliver. In the last chapter things were looking pretty

  dire. A bad design was making life hard for everyone and, to make matters worse, an unplanned task cropped up. In this chapter you’ll see how to refactor your design so that you and your team can be more productive. You’ll apply principles of good design, while at the same time being wary of striving for the promise of the ‘perfect design’. Finally you’ll handle unplanned tasks in exactly the same way you handle all the other work on your project using the big project board on your wall.

  good-enough design

Ge t t ing it done w it h gre at de sign

  iSwoon is in serious trouble... 150 This design breaks the single responsibility principle 153

  Spotting multiple responsibilies in your design 156 Going from multiple responsibilies to a single responsibility 159

  Your design should obey the SRP, but also be DRY... 160 The post-refactoring standup meeting... 164

  Unplanned tasks are still just tasks 166 Part of your task is the demo itself 167

  When everything’s complete, the iteration’s done 170

  5

  table of contents version control

De fe nsive deve lopm e nt

  

When it comes to writing great software, Safety First!

  Writing great software isn’t easy... especially when you’ve got to make sure your code works, and make sure it keeps working. All it takes is one typo, one bad decision

  

6 from a co-worker, one crashed hard drive, and suddenly all your work goes down the

  drain. But with version control, you can make sure your code is always safe in a code repository, you can undo mistakes, and you can make bug fixes—to new and old versions of your software.

  You’ve got a new contract—BeatBox Pro 178 And now the GUI work... 182

  Demo the new BeatBox for the customer 185 Let’s start with VERSION CONTROL 188 First set up your project... 190

  ...then you can check code in and out. 191 Most version control tools will try and solve problems for you 192

  The server tries to MERGE your changes 193 If your software can’t merge the changes, it issues a conflict 194

BeatBox Pro 1.0

  More iterations, more stories... 198 We have more than one version of our software... 200

  Good commit messages make finding older software easier 202 Now you can check out Version 1.0 203 (Emergency) standup meeting 204

  Tag your versions 205 Tags, branches, and trunks, oh my! 207

  Fixing Version 1.0...for real this time. 208 We have TWO code bases now 209 When NOT to branch... 212

  BeatBox Pro 1.x

  The Zen of good branching 212 What version control does... 214 Version control can’t make sure you code actually works... 215 Tools for your Software Development Toolbox 216

  2.0!

  table of contents building your code I nse r t t a b a int o slot b...

It pays to follow the instructions... ...especially when you write them yourself

  It’s not enough to use configuration management to ensure your code stays safe. You’ve

  6 / also got to worry about compiling your code and packaging it into a deployable unit. On

  top of all that, which class should be the main class of your application? How should that class be run? In this chapter, you’ll learn how a build tool allows you to write your own

  instructions for dealing with your source code.

  Developers aren’t mind readers 220 Building your project in one step 221

  Ant: a build tool for Java projects 222 Projects, properties, targets, tasks 223 Good build scripts... 228 Good build scripts go BEYOND the basics 230

  Your build script is code, too 232 New developer, take two 233

  Tools for your Software Development Toolbox 234

  Pieces of your project Build process Working system olders You’ve got f of source code and

  ...probably some unit tests... binary files, like images or icons... .jar log4j .jar commons apache-

And out pops your

system, ready to run.

  The build magic ...libraries, jars, iptors, happens here.

  ...deployment descr dlls, so’s...

  HTML files, app. configs, etc... t we need

  This is what we’ve been Here’s wha focusing on so far... to work on now.

  table of contents testing and continuous integration

T hings fa ll a pa r t Sometimes even the best developer breaks the build

  Everyone’s done it at least once. You’re sure your code compiles, you’ve tested it over and over again on your machine and committed it into the repository. But somewhere

  7 between your machine and that black box they call a server someone must have changed

  your code. The unlucky soul who does the next checkout is about to have a bad morning sorting out what used to be working code. In this chapter we’ll talk about how to put together a safety net to keep the build in working order and you productive.

  Things will ALWAYS go wrong... 236 There are three ways to look at your system... 238

  Black-box testing focuses on INPUT and OUTPUT 239 Grey-box testing gets you CLOSER to the code 240

  White-box testing uses inside knowledge 243 Testing EVERYTHING with one step 248 Automate your tests with a testing framework 250

  Use your framework to run your tests 251 At the wheel of CI with CruiseControl 254 Testing guarantees things will work... right? 256 Testing all your code means testing EVERY BRANCH 264

  Use a coverage report to see what’s covered 265 Getting good coverage isn’t always easy... 267

  Black-box testing

  What CM does... 270 Tools for your Software Development Toolbox 274

  • + getGC(gcId : int) :GiftC TestInsufficientDBAcc + saveGC(card : GiftC + getGC(gcId : int) :GiftC essor MySqlDBAcc TestGoodDBAcc essor processOrder(...) ard) :void ard essor Order Utilities ard saveOrder(...) check balanc + saveGC(card : GiftC + saveGC(card : GiftC DB + saveGC(card : GiftC + getGC(gcId : int) :GiftC

  <<interface>> DBAccessor es, etc. ard) :void + getGC(gcId : int) :GiftC insert into ... ard) :void + getGC(gcId : int) :GiftC TestInvalidDBAccessor ard ard) :void ard + saveGC(card : GiftC ard) :void ard saveGC(...) update amnt ...

  Grey-box testing White-box testing

  table of contents test-driven development

  

H olding your c ode a c c ount a ble

Sometimes it’s all about setting expectations. Good code needs to

  work, everyone knows that. But how do you know your code works? Even with unit testing, there are still parts of most code that goes untested. But what if testing was a

  8 fundamental part of software development? What if you did everything with testing in

  mind? In this chapter, you’ll take what you know about version control, CI, and automated testing and tie it all together into an environment where you can feel confident about

  fixing bugs, refactoring, and even reimplementing parts of your system.

  Test FIRST, not last 276 So we’re going to test FIRST... 277

  Welcome to test-driven development 277 Your first test... 278

  ...fails miserably. 279 Get your tests to GREEN 280 Red, green, refactor... 281 In TDD, tests DRIVE your implementation 286 Completing a task means you’ve got all the tests you need, and they all pass

  288 When your tests pass, move on! 289

  Simplicity means avoiding dependencies 293 Always write testable code 294 When things get hard to test, examine your design 295 The strategy pattern provides formultiple implementations of a single interface 296

  Keep your test code with your tests 299 Testing produces better code 300

  More tests always means lots more code 302 Strategy patterns, loose couplings, object stand ins... 303

  We need lots of different, but similar, objects 304 What if we generated objects? 304 A mock object stands in for real objects 305

  Mock objects are working object stand-ins 306 Good software is testable... 309 It’s not easy bein’ green... 310

  A day in the life of a test-driven developer... 312

  table of contents ending an iteration I t ’s a ll c om ing t oge t he r...

  You’re almost finished! The team’s been working hard and things are

  wrapping up. Your tasks and user stories are complete, but what’s the best way to spend that extra day you ended up with? Where does user testing fit in?

  9 Can you squeeze in one more round of refactoring and redesign? And there

  sure are a lot of lingering bugs... when do those get fixed? It’s all part of the end of an iteration... so let’s get started on getting finished.

  Your iteration is just about complete... 318 ...but there’s lots left you could do 319

  System testing MUST be done... 324 ...but WHO does system testing? 325

  System testing depends on a complete system to test 326 Good system testing requires TWO iteration cycles 327 More iterations means more problems 328

  Top 10 Traits of Effective System Testing 333 The life (and death) of a bug 334

  So you found a bug.... 336 Anatomy of a bug report 337

  But there’s still plenty left you COULD do... 338 Time for the iteration review 342

  Some iteration review questions 343 A GENERAL priority list for getting EXTRA things done... 344 Tools for your Software Development Toolbox 346

  table of contents the next iteration

I f it a in’t broke ...you st ill be t t e r fix it Think things are going well? Hold on, that just might change..

  Your iteration went great, and you’re delivering working software on-time.

  all. Software development is all about change, and moving to your next

  iteration is no exception. In this chapter you’ll learn how to prepare for the next iteration. You’ve got to rebuild your board and adjust your stories and expecations based on what the customer wants NOW, not a month ago.

  What is working software? 350 You need to plan for the next iteration 352 Velocity accounts for... the REAL WORLD 359 And it’s STILL about the customer 360

  Someone else’s software is STILL just software 362 Customer approval? Check! 365

  Testing your code 370 Houston, we really do have a problem... 371

  Trust NO ONE 373 It doesn’t matter who wrote the code.

  If it’s in YOUR software, it’s YOUR responsibility. 373 You without your process 378 You with your process 379

  table of contents bugs

Squa shing bugs like a pro Your code, your responsibility...your bug, your reputation!

  When things get tough, it’s up to you to bring them back from the brink. Bugs, whether they’re in your code or just in code that your software uses, are a fact of life in software

  

11 development. And, like everything else, the way you handle bugs should fit into the rest

  of your process. You’ll need to prepare your board, keep your customer in the loop,

  confidently estimate the work it will take to fix your bugs, and apply refactoring and prefactoring to fix and avoid bugs in the future.

  Previously on Iteration 2 386 First, you’ve got to talk to the customer 386 Priority one: get things buildable 392

  We could fix code... 394 ...but we need to fix functionality 395

  Figure out what functionality works 396 NOW you know what’s not working 399

  What would you do? 399 Spike test to estimate 400

  What do the spike test results tell you? 402 Your team’s gut feel matters 404

  Give your customer the bug fix estimate 406 Things are looking good... 410

  ...and you finish the iteration successfully! 411 AND the customer is happy 412 Tools for your Software Development Toolbox 414

  table of contents

  go pinning burn down graphs in everyone’s office, there’s just a little more you need to know about dealing with each project... on its own terms. There are a lot of similarities and best practices you should carry from project to project, but there are unique things everywhere you go, and you need to be ready for them. It’s time to look at how to apply what you’ve learned to your particular project, and where to go next for more learning.

  the real world

H aving a proc e ss in life

  Pinning down a software development process 418 A good process delivers good software 419

  Formal attire required... 424 Some additional resources... 426 More knowledge == better process 427

  Tools for your Software Development Toolbox 428

  St or y a nd Bur n Dow n boa rd U se r St orie s Configurat ion M a na ge m e nt (CM ) Cont inuous I nt e grat ion (CI ) Te st Drive n Deve lopm e nt (T DD) Te st Cove ra ge Each class is listed individua lly (broken up by package) One measure of testing coverage is line coverage-what percentage of the total lines of code are we executing through our tests? Another measur e is branch cov erage- hat percentage of the alterna te flows (ifs, elses, etc.) ar e we executing?

  table of contents

T he t op 5 t hings (w e didn’t c ove r) Ever feel like something’s missing? We know what you mean..

  Just when you thought you were done... there’s more. We couldn’t leave you without a few extra things, things we just couldn’t fit into the rest of the book. At least, not if you want to be able to carry this book around without a metallic case and castor wheels on the bottom. So take a peek and see what you (still) might be missing out on.

  appendix 1: leftovers

  #1. UML class Diagrams 434 #2. Sequence diagrams 436 #3. User stories and use cases 438 #4. System tests vs. unit tests 440 #5. Refactoring 441

  i Airplane

  • speed :int

Send a picture to other users

  • getSpeed() :int
  • setSpeed(speed : int) :void

  Click on the “Send a P icture” button to send a p icture (only JPEG n eeds to be supported) to the o ther users. The ot her user should have the o ption to not accep t the file.

  There are no size l imits on the file b eing sent.

  De sc ript ion : Priorit y: Est im at e : T it le :

  20

  4

  table of contents appendix 2: techniques and principles

Tools for t he ex pe rie nc e d soft w a re deve lope r Ever wished all those great tools and techniques were

  in one place? This is a roundup of all the software development techniques and principles we’ve covered. Take a look over them all, and

  see if you can remember what each one means. You might even want to

  ii cut these pages out and tape them to the bottom of your big board, for everyone to see in your daily standup meetings.

  Development Techniques 444 Development Principles 446

  6 version control

  

Defensive development

  Alright guys, listen up. Bob’s writing new code. You’ve got to keep him safe, no matter what happens, understand?

When it comes to writing great software, When it comes to writing great software, Safety First! Safety First!

  Writing great software isn’t easy...especially when you’ve got to make sure your code Writing great software isn’t easy...especially when you’ve got to make sure your code works, and make sure it keeps working. All it takes is one typo, one bad decision works, and make sure it keeps working. All it takes is one typo, one bad decision from a co-worker, one crashed hard drive, and suddenly all your work goes down the from a co-worker, one crashed hard drive, and suddenly all your work goes down the drain. But with version control, you can make sure your code is always safe in a drain. But with version control, you can make sure your code is always safe in a code repository, you can undo mistakes, and you can make bug fixes—to new and code repository, you can undo mistakes, and you can make bug fixes—to new and old versions of your software. old versions of your software. You’ve got a new contract—BeatBox Pro Congratulations—you’ve been getting rave reviews from iSwoon, and you’ve landed a new contract.

  You’ve been hired to add two new features to the legendary Head First Java BeatBox project. BeatBox is a multi-player drum machine that lets you send messages and drum loops to other users over the network. Like every other software development project out there, the customer wants things done as soon as possible. They even let you bring along Bob, one of your junior developers, to help out. Since the stories aren’t big enough to have more than one person work on them at a time, you’ll work on one and Bob will work on the other. Here are the user stories for the new features you’ve got to add:

  You’ll take tasks associated with this story.

  The BeatBox program f rom Head First Jav a, our starting p oint.

  Bob will pull task s from this story.

  Send a picture to other users Click on the “Send a Picture” button to send a picture (only JPEG needs to be supported) to another user. The other user should have the option to not accept the file. There are no size limits on the file being sent.

  Description: Priority: Estimate: Title:

  20

  4 Send a Poke to other users

  Click on the “S end a Poke” button to send a n audible and v isual alert to t he other members i n the chat. The a lert should be short and not t oo annoying—y ou’re just tryin g to get their at tention.

  Description: Priority: Estimate: Title:

  20

  3 introducing beatbox pro

  • *You can download the code that we’re starting with from http://www.headfirstlabs.com/books/hfsd/

  version control Stickies

  Task Magnets ask Magnets

  Let’s get right to the new features. Here’s a snippet from the BeatBox client code. Your job is to map the task stickies to the code that implements each part of the “Send a Poke...” story. We’ll get to the GUI work in a minute.

  Task 1 MDE

  this Sound an audible alert // ... more BeatBox.java code above

  when receiving a poke

  s Runnable { public class RemoteReader implement

  message (can’t be

  boolean[] checkboxState = null;

  annoying!) .5

  String nameToShow = null; Object obj = null;

  Task 2 LUG

  public void run() {

  Add support for

  try { = null) { while((obj=in.readObject()) !

  checking for the Poke

  object from server"); System.out.println("got an

  command and creating

  lass()); System.out.println(obj.getC ) obj; a message.

  String nameToShow = (String

  .5

  in.readObject(); checkboxState = (boolean[]) START_SEQUENCE)) { if (nameToShow.equals(POKE_

  Task 4 BJD

  playPoke(); tention.";

  Merge Poke visual

  nameToShow = "Hey! Pay at }

  alert into message display system.

  , checkboxState); otherSeqsMap.put(nameToShow

  .5

  listVector.add(nameToShow); stVector); incomingList.setListData(li } // close while ntStackTrace(); }

  Task 3 MDE

  } catch (Exception ex) { ex.pri } // close run

  Implement receiver code to read the

  private void playPoke() { p(); Toolkit.getDefaultToolkit().bee

  data off of the

  } network. } // close inner class

  1

  digging into code Stickies

  Task Magnets Solution ask Magnets Solut We’re not in Head First Java anymore; let’s get right to the new features.

  Here’s a snippet from the BeatBox client code. Your job was to map the task magnets to the code that implements each part of the “Send a Poke...” story.

  o All of this code goes int BeatBox.java. e this ox.java code abov

  // ... more BeatB ts Runnable { teReader implemen public class Remo

  Here’s the code boxState = null; ass boolean[] check that will run in the ow = null;

  This is the inner cl String nameToSh es data from ll; new thread context

  Object obj = nu that receiv for BeatBox. the server.

  () { public void run This is original try { != null) { code-it reads in.readObject()) er"); while((obj= object from serv

  Task 3 MDE messages sent t.println("got an System.ou

  Class()); t.println(obj.get from the server. System.ou

  Implement receiver

  g) obj; meToShow = (Strin ; String na

  ) in.readObject() code to read the tate = (boolean[] checkboxS

  Task 2 LUG data off of the

  { _START_SEQUENCE))

oShow.equals(POKE

if (nameT network.

  Add support for e();

  1 playPok ttention.";

how = "Hey! Pay a

checking for the Poke nameToS

  If we get the POKE_ } command and creating

  ; w, checkboxState) a message.

  Map.put(nameToSho otherSeqs .5

  ; we play the poke sound r.add(nameToShow) listVecto istVector); and replace the message ist.setListData(l incomingL while with our alert text.

  } } // close Task 4 BJD intStackTrace(); ption ex) { ex.pr

  } catch (Exce Merge Poke visual

  } // close run alert into message ayPoke() { private void pl ep(); display system.

faultToolkit().be

Toolkit.getDe

  Here’s our new .5

  } playPoke() method class

  Task 1 MDE } // close inner that just beeps for

  Sound an audible alert now. If you want a real when receiving a poke challenge, add MP3 message (can’t be poke-sound support. annoying!)

  .5

  version control Bob’s making good progress on his end, too. Can you think of

anything else you should be worrying about at this point?

  Q: This isn’t a Java programming book. Why are we wasting time looking through all this code?

A:

MusicServer

A:

A:

  interface is Java’s way of wrapping up some code that should be run in another thread. The code you just looked at, in the last exercise, is the network code.

  BeatBox is always trying to grab data from the network so it can display incoming messages. However, if there’s nothing available on the network, it could get stuck waiting for data. This means the screen wouldn’t redraw and users couldn’t type in a new message to send. In order to split those two things apart, BeatBox uses threads. It creates a thread to handle the network access, and then uses the main thread to handle the GUI work. The

  Q: What’s all this threading and Runnable stuff about?

  come through, they replace it with our visual alert message, and the receiving user never actually sees that code sequence.

  file in the code you can download from http:// www.headfirstlabs.com/books/hfsd/). When other BeatBox instances see the

  BeatBox.java

  constant (the actual string value is in the

  POKE_ START_SEQUENCE

  . Normally when a message gets sent it’s just a string that is displayed to the user. We added the Poke functionality on top of the original BeatBox by coming up with a unique string of characters that no one should ever type on purpose. We can use that to notify the other BeatBoxes that a “poke” was sent. This sequence is stored in the

  Our story requires us to send a poke message to the other BeatBoxes connected to the

  A:

  Q:

So what’s the deal with that

POKE_START_SEQUENCE thing?

  . If you click on the received message, then you can hear the new sequence that was just sent.

  MusicServer

  Sound API to generate sound sequences that you can control with the checkboxes on the form’s main page. When you enter a message and click “sendit,” your message and your BeatBox settings are sent to any other copies of BeatBox connected to your

  and a Java Swing– based client piece (that’s Java’s graphical toolkit API). The client piece uses the Java

  BeatBox is a program first discussed in Head First Java. It has a backend

  A:

  Q:

I think I must have...misplaced...

my copy of Head First Java. What’s this

whole BeatBox thing about?

  That’s OK. Do your best to understand what the code is doing, and don’t worry about all the Java-specific details. The main thing is to get an idea of how to handle and think about code in a solid software development process. The tools and techniques we’ll talk about should make sense whether you know what a Java thread is or not.

  Q: I don’t develop in Java. I’m not sure what some of the code in there does. What do I do?

  prioritization and estimation; you’ve still got to write good, working, reliable code.

  itself. Software development isn’t just about

  Software development techniques cover everything related to a project, from organization and estimation down through code. Earlier, we talked about the planning and execution parts of a project, and then we got a little closer to code and talked about design. Now, we need to dive all the way down and talk about some tools and techniques you can use on your code

MusicServer

Runnable

  finish the story And now the GUI work...

  We need one more piece of code to get this story together. We need to add a button to the GUI that lets the user actually send the Poke. Here’s the code to take Task 5 <YOU> care of that task:

  Add button to GUI to send Poke sequence to other BeatBox

  // The code below goes in BeatBox.java, instances. // in the buildGUI() method .5

  JButton sendIt = new JButton("sendIt"); sendIt.addActionListener(new MySendListener()); buttonBox.add(sendIt); o create a new First we need t oke feature. button for our P

  JButton sendPoke = new JButton("Send Poke"); sendPoke.addActionListener(new MyPokeListener()); Then we set up a buttonBox.add(sendPoke); listener so we can react when it’s clicked. userMessage = new JTextField();

  Finally, add the button to the box buttonBox.add(userMessage); holding the other buttons.

  // Below is new code we need to add, also to BeatBox.java public class MyPokeListener implements ActionListener {

public void actionPerformed(ActionEvent a) { Here we create an array of

booleans for our state. We can

  // We'll create an empty state array here leave them all false because the boolean[] checkboxState = new boolean[255]; receiving side ignores them when it gets the POKE command. try { out.writeObject(POKE_START_SEQUENCE); out.writeObject(checkboxState); } catch (Exception ex) { System.out.println("Failed to poke!"); } o send a poke we send the

  } Here’s the magic: t RT_SEQUENCE and our array elay

  } magic POKE_STA er. The server will r ents, and of booleans to the serv e to the other cli er our magic sequenc they’ll beep at the user because of the earli code we wrote (back on page 180).

  version control And a quick test...

  Here’s our new Poke button.

  The “-d” tells the java compiler t o put the cl asses in the bin dir ectory. hfsd> mkdir bin hfsd> javac -d bin src\headfirst\sd\chapter6\*.java hfsd> java -cp bin headfirst.sd.chapter6.MusicServer File Edit Window Help Buildin’

hfsd> java -cp bin headfirst.sd.chapter6.BeatBox PokeReceiver

File Edit Window Help Ouch hfsd> java -cp bin headfirst.sd.chapter6.BeatBox PokeSender File Edit Window Help Hah

  The MusicServer will listen for connections and print out a line each time it gets one.

  We use different names here so we know which is which.

  Excellent! Your changes work as advertised. We’ll copy the code up to the demo server, and all that’s left is for Bob to merge his stuff in. Time to call it a night.

  DING! (Ser iously,. i t sounds like tha t.)

  Here’s our alert message.

  3 Hey! Pay attention.

  Now that both the client and server are implemented it’s time to make sure things work. No software can go out without testing so...

  3

  2 Now send off a Poke by clicking the “Send Poke” button on the instance we named PokeSender.

  2

  1 Then start the new BeatBox—we’ll need two instances running so we can test the Poke.

  1

  First compile and start up the MusicServer.

  Here’s our PokeReceiver instance.

  merging changes And Bob does the same...

  Bob finished up the tasks related to his story and ran a quick test on his end. His task is working, so he copies his code up to the server. In order to do the final build he merges his code in with ours, gets everything to compile, and retests sending a picture. Everything looks good. Tomorrow’s demo is going to rock...

  Here’s Bob’s version of BeatBox—the SendPicture button is implemented.

  Once the tasks are finished move the stories over to Completed.

  Completed o Send a Poke t

  Title: other users

  Task 2 Task 1 er side Title: sequence. side Poke button and Implement sender Implement serv of alert message. reception and pl aying 1.5 Send a picture to 1 other users

  Bob’s happy with the code so he cop Task 3 Task 4 Implement image Implement sender side Task 5 selection dialog. send picture button 5 and displaying code. and loading code. side image reception up to the demo server. After the build is 1 Implement receiver 2.5 ies it done, things are ready for tomorrow.

  

I’m not familiar with networking code. What’s Why did we make the bin directory before we

Q:

  Q: happening in that code we just added? compiled the code?

  On the sending side we represent the sequence settings We’ll talk more about this in the next chapter, but in

  A:

A:

  as an array of checkboxes. We don’t really care what they’re set general it’s a good idea to keep your compiled code separate to, since we won’t use them on the receiving side. We still need from the source. It makes it a lot simpler to clean up and rebuild to send something, though, so the existing code works. We use when you make changes. There’s nothing special about the

  Java’s object serialization to stream the array of checkboxes name “bin”; it’s just convention and is short for “binaries”—i.e., and our secret message that triggers the alert on the other side. compiled code.

  On the receiving side we pull off the secret sequence and the Wait, did Bob just merge code on the demo server? array of checkboxes. All of the serialization and deserialization

  Q: is handled by Java.

   Yup...

  A:

  version control Demo the new BeatBox for the customer We’re all set to go. Your code is written, tested, and copied up to the demo server. Bob did the final build, so we call the customer and prepare to amaze the crowds.

  Here’s our button—and the “Send Picture” button is from Bob’s code.

  Uh oh, this doesn’t look good.

  What’s going on? I’m not hearing any alert. omer.

  And what’s SECRET_POKE_

  Unhappy cust SEQUENCE? I’m not impressed.

  Not good.

  So what went wrong? Our code worked just a few pages ago. So what went wrong? More importantly, what would you do differently in the future to make sure nothing like this ever happens again?