Unchained Malady A Tangle of Times

Similar documents
MEETPLANNER DESIGN DOCUMENT IDENTIFICATION OVERVIEW. Project Name: MeetPlanner. Project Manager: Peter Grabowski

AEROSPACE MICRO-LESSON

Ranger Walking Initiation Stephanie Schneider 5/15/2012 Final Report for Cornell Ranger Research

SWIM MEET--RULES AND REGULATIONS. 1. Each swimmer may swim in no more than three events per meet plus a relay. All swimmers may swim all meets.

Sanction Requirements and Considerations

SWIM MEET--RULES AND REGULATIONS

Summer Development Series

Rules Modernization FAQs March 2018 Update

APPENDIX 1 GLOSSARY OF TERMS


Rules Modernization FAQs March 2018 Update

CS Problem Solving and Object-Oriented Programming Lab 2 - Methods, Variables and Functions in Alice Due: September 23/24

2008 Excellence in Mathematics Contest Team Project B. School Name: Group Members:

Swim Meet Primer. Competition Groups: Gender: Male/Female

ONLINE SHOP FREQUENTLY ASKED QUESTIONS

Injury Prevention for Runners

Saturday 21 st / Sunday 22 nd January All Events UEA Sportspark Saturday 28 th / Sunday 29 th January All Events UEA Sportspark.

Minnesota Regional Championships Rochester Swim Club Orcas

Youth Floorball Coaching Manual

Conceal Defense Basic Explanation and Purpose The is an initial defensive alignment I saw watching a community college game a few

How to run a club night

RUNNING MEET MANAGER IN SUPPORT OF MEETS (2016) Greg Wright(6/3/16) First, YOU DO NOT NEED TO DO THIS UNLESS YOU ARE THE HOME TEAM

THE STATE OF MIND MODEL

Verification of Peening Intensity

GHSA Swimming/Diving POP School User s Guide

Location: Facility: Meet Format:

Iteration: while, for, do while, Reading Input with Sentinels and User-defined Functions

2017 MN Short Course Age Group State Championships (All Zones) with Time Trials Med City Aquatics

Sincerely, Joe Alexander Meet Director Essex County Swimming Championships

RUNNING A MEET WITH HY-TEK MEET MANAGER

2018 LOUISIANA 13 and UP SHORT COURSE STATE SWIMMING CHAMPIONSHIPS

SOUTH ISLAND SECONDARY SCHOOLS SWIMMING CHAMPIONSHIPS 2015 EVENT INFORMATION

Newton s Laws of Motion

2016 LA84 Foundation Summer Swim Program Swim Coaches Packet

Generating Power in the Pool: An Analysis of Strength Conditioning and its Effect on Athlete Performance

201 8 Maryland AAU District Swimming Championships

SOUTH ISLAND SECONDARY SCHOOLS SWIMMING CHAMPIONSHIPS 2018 EVENT INFORMATION

Bradford Grassroots Invitational Meet Level 4 Sunday 14 th January 2018

Arizona Swimming 2017 Long Course Junior Olympics Championship July 7 9, 2017 Held under the sanction of USA Swimming

SWIMMING 2017 GENERAL RULES

IDeA Competition Report. Electronic Swimming Coach (ESC) for. Athletes who are Visually Impaired

2015 Gwinnett County Swim League Championships July 11-12, Page 1 of 7 Printed

Parent s Guide to Swimming Galas

2018 NCSA Age Group Swimming Championships

BFH/HTA Biel/DUE/Course 355/ Software Engineering 2. Suppose you ll write an application that displays a large number of icons:

LAB : Using A Spark Timer

HANDICAP REVIEW APPENDIX PORTUGUESE GOLF FEDERATION INTRODUCTION

Situations and Resolutions Stroke and Turn USA Swimming

2019 North Country League Club Championships Gloversville Middle School, Gloversville, NY- February 9, 2019

Place one jack each at the far 2-meter mark and at each hog line, centering them and placing a chalk mark under them.

Introduction. Progressive Tennis

2015 AM LC Team Pittsburgh Junior Olympics -- 1

CCASA Intermediate Gala. Rules and procedures for individual events in the Intermediate Gala:

Welcome Your Coaches

Analysis of recent swim performances at the 2013 FINA World Championship: Counsilman Center, Dept. Kinesiology, Indiana University

Loveland Sweetheart Meet

2008 FISH Qualifier. February 7-8, 2009 Spring Hill Recreation Center McLean

Sunday 5 February Warm Up 8.30am, Start 9.30am Dist. Stroke Division Age Friday 3 February Warm Up 6.00pm, Start 6.45pm Dist. Stroke Division Age

SUMMER SENIOR CHAMPIONSHIP St. Petersburg, FL

Including Swimmers with a Disability: A Guide for Swimmers and Parents

1. A Tutorial on LSA SwimMeet

The 2018 Super FISH Bowl VIII

SUMMER SENIOR CHAMPIONSHIP St. Petersburg, FL

Time trials will not be offered at this meet.

2015 AM LC Team Pittsburgh Junior Olympics -- 1

Sanction # PVC Dave Greene (240) Jim Garner

CENTRAL VICTORIA SWIMMING

MEET CLASSIFICATION: This meet is open to all USA Swimming athletes and clubs.

Sample Summer Swim League Swimming Rules and Regulations

Arizona Swimming Inc Long Course Junior Olympics Championship July 13 15, 2018

How to Guide for Registering Online. Click here to reveal dropdown menu

PVS & U Junior Olympic Championships

Dear Parents and Swimmers, Welcome to the 2017 Summer Season! My name is Grant Alef and I will be your head coach this summer. This will be my third

MID-PENN SWIM LEAGUE RULES AND REGULATIONS REVISED 2016

MEET REFEREE Lynne Gerlach

2018 ELITE SHOWCASE CLASSIC SWIMMING CHAMPIONSHIP St. Petersburg, FL March 28 th 31 st

CCAA Swimming Officials Test for 2016

Bikes and Energy. Pre- Lab: The Bike Speedometer. A Bit of History

Horse Farm Management s Report Writer. User Guide Version 1.1.xx

Operations Procedures and Rules of the Lynchburg Aquatic League (LAL) (updated April 2018)

Any session reaching the four (4) hour limit will be closed unless the host club has received approval from the Technical Planning Committee.

LITHGOW SWIMMING CLUB SQUAD PROGRESSION POLICY & COACHING GUIDELINES

Project 1 Those amazing Red Sox!

AD Coaches and Contacts R/E AD Gold SC Championships

2015 USA Swimming Rules and Regulations

EMMAUS AQUATIC CLUB Fall A/BB/C Invitational Meet November 15-17, 2013

2016 NCSA Age Group Swimming Championships

North Midlands Water Polo & Swimming Association

COASTAL CITIES AQUATIC ASSOCIATION

Dive Sheets & Running Events Meet Management Software Tutorial for EZMeet Version 3.1 revised 2/4/2006

Another window pops up where you can input some parameters (called System Preferences) for your team as shown

Held under the sanction of USA Swimming, Inc. and Border Swimming, Inc. Sanction # BD 14-02

PVS 2019 Short Course Junior Championships

Pam Dolan Coordinator: Officials Contact: MEET CLASSIFICATION: This meet is open to all USA Swimming athletes and clubs.

WORLD SAILING PACKAGE OF TEST RULES FOR MATCH RACING UPDATED DECEMBER 2015 BRIEFING DOCUMENT

2011 Area 1 & 4 Championship Hosted by: AmberJax (EAJ) March 12 13, 2011

Alamo Area Aquatic Association Meet Information

AMS Senior and 10 and under Championships, sponsored by Mt. Lebanon Aqua Club March 4-5, 2017

BRIEFING NOTES FOR TIMEKEEPER. Candidate Name.

Statewide Cycloplan: Bicycle Planning Tool & Participatory GIS

Transcription:

Unchained Malady James W. Cooper toc: Here s a simple way to expand the number of tests you make on a set of values without writing spaghetti code. deck: The Chain of Responsibility pattern can help you write code that is easier to modify. Some years ago, I became interested in the technology of data handling for competitive swimming, and as a hobby developed a set of programs for running swim meets and managing swim team records. [A hobby is a business (labsoftware.com) that doesn t make any money.] Recently I was presented with a problem in these programs that was difficult to solve, and it got me to thinking about how Design Patterns might have helped me out of this tangle. The current software is the sixth generation of a simple program written in Basic, and it is written in Visual Basic. VB has some OO features but as a language system, it doesn t particularly encourage or support OO approaches. This is another way of saying if I only knew then what I know now, which is a common programmer s complaint in all languages. You learn a lot in writing a complete system and you could always do this better if you had the time to rewrite the system based on what you ve learned. In this case, we ll assume that my learning includes both design patterns and the fact that Java might be a superior way to tackle this system. A Tangle of Times In order to solve this problem, we have to define it carefully. End of season championship swim meets frequently have qualifying times. In other words, you have to have gone this fast in this distance and stroke to enter the meet. For youngsters, these cut off times are further defined by age group as well as by sex. So the problem of selecting swimmers from your team s roster who qualify for an event would seem to be quite simple: for each event, look for swimmers who have times faster than the established standard and enter them in the meet. But, of course it is more complicated than that. In the next three paragraphs, I m going to give you a simplified explanation of the problem. The actual problem is worse, but the simplified version is enough to get us back to OO programming sooner. In the US there are short course and long course pools. The shorter pools are 25 yards, and the longer Olympic-size pools are 50 meters. It is not possible to convert times achieved in these two courses because there are a different number of turns in a race and there simply is no analytic algorithm for such a conversion. Instead, qualifying times are usually posted for both courses. So the entry algorithm is: If the swimmer has a time in the course the meet is to be swum in, use that. Otherwise, check to see if they have a qualifying time in the other (nonconforming) course, and use that. Now consider the fact that swimmers have to qualify somewhere. So qualifying meets are held for swimmers who have not achieved this standard yet. If a swimmer has a time slower than the standard, enter them in the qualifying meet. Since this could cut too wide

a swath, a more common case is to enter the kid in the qualifying meet if his time is slower than the championship meet standard, but faster than some arbitrary slower time that is used to keep out the rank beginners. So now, we have an algorithm that says: if the swimmer has a time slower than the standard but faster than some slower standard, enter them in the qualifying meet. Now, this final fillip is where it gets tricky. Supposing a swimmer has a qualifying time in the non-conforming course but not in the conforming course. That means he can legitimately enter the championship meet. But suppose he wants to compete to obtain a time in the conforming course. Should this be allowed? The organization decided that this should not be allowed, making the decision of who is legitimately entered that much more difficult. It was this change in policy that made me throw up my hands and say it was too hard to change the code quickly, and it would lead to a spaghetti code of ifstatements that I couldn t guarantee would work soon enough for the now just-ended season. Trying A New Pattern Now if I had used better OO principles and an appropriate design pattern, would I have been better off? Emphatically yes. Let me briefly outline the Chain of Responsibility pattern. You use this pattern when you want several classes to attempt to handle some kind of request without any of them having knowledge of the other classes or their capabilities. For example, in a Help system you might have specific help on one visual control, more general help for a group of related controls and even more general help for the entire window. You start with help at the most local level and search upward until you find a help message that has been implemented. The way to do this is to have a series of classes linked together in a chain, with each one forwarding to the next if it can t satisfy the request. New button File button All buttons All controls General help Figure 1- A model of a Help system using the Chain of Responsibility pattern, Figure 1 shows a Chain of Responsibility for a Help system for a simple user interface. The interface has a File button and a New button. If you ask for help, it the control receiving the help request sends it to the chain until one item in the chain can satisfy the request and display the appropriate level of help. Thus, if you have not written help for every element, the next more general help is shown instead.

Additionally, the Chain of Responsibility pattern helps keep separate the knowledge of what each object in a program can do. Objects don t need to know about other related objects, and the each can act independently. Chains of Responsibility also are frequently used in compilers and interpreters, where you recognize language tokens in a group on a stack and then send the stack frame pointer to a chain until one can act on it. They probably have lots of other uses I haven t yet come across, but it occurred to me that this swimming cutoff time problem is one that is amenable to this pattern. In both the Help system example and the compiler-interpreter example, the request is passed along the chain of objects, each one examines the request and acts on it if it can. Otherwise, it sends it on along the chain. Another way to build such a system is to have each object act on the request and pass it along as well. This would mean that each object could further modify a decision made by a previous object without knowing whether it was the first, last, or only object in the chain. Swimmers in Chains Now let s actually write some Java. We ll start by defining an interface for a Chain: //The basic Chain interface interface Chain { //add an element to the chain public void addchain(chain c); //get the next object in the chain public Chain getchain(); //send data requests along the chain public void sendtochain(swimmer swmr, Event evnt); For simplicity, we ll define a Swimmer object as one who has a single time in each of two courses, and ignore the complication that there are multiple strokes and distances. Our Swimmer will just have a name, two times (conforming course and nonconforming course) and a flag that indicates whether he is eligible to swim in this meet. //a simple Swimmer object public class Swimmer { //name private String firstname, lastname; //whether eligible to enter event private boolean eligible; //times in conforming nad nonconforming course private float stime, nctime; public Swimmer(String frname, String lname) { firstname = frname; lastname = lname; //set the times public void settimes(float time, float nctime) { stime = time; nctime =nctime; //get the times public float gettime() {

return stime; public float getnctime() { return nctime; //set whetehr eligible public void seteligible(boolean b) { eligible = b; public boolean geteligible() { return eligible; //get the name public String getname() { return firstname+" "+lastname; Likewise, we ll define an event as having a stroke and distance and fast and slow cutoff times for both the conforming and nonconforming course: //an Event object public class Event { private int eventnumber; private String strokename; private int distance; private float slowcut, fastcut; private float ncslowcut, ncfastcut; //save event number, distance and strokt public Event(int number, int dist, String stroke) { eventnumber = number; distance = dist; strokename = stroke; //save the slow cuts public void setslowcuts(float slow, float ncslow) { slowcut = slow; ncslowcut = ncslow; //save the fast cuts public void setfastcuts(float fast, float ncfast) { fastcut = fast; ncfastcut = ncfast; //return the cut you ask for public float getslowcut() { return slowcut; public float getfastcut() { return fastcut; public float getncslowcut() { return ncslowcut; public float getncfastcut() { return ncfastcut;

Building Your Own Timing Chain Now what about this chain? The crucial technical breakthrough is realizing that rather than setting an eligible/ineligible Boolean in a set of if-statements, it is much better to keep that flag inside the Swimmer object. Then each chain element can set the flag to eligible/no eligible depending on the result of its test. And each element thus needs to make only one test. Rather than writing a bunch of complicated tests, you string together a set of simple tests in a chain. You just have to make sure that the chain goes from least to most restrictive. Here s a basic chain element that tests for a time faster than the slow cut: //Check a swimmer's time in a chain public class TimeChain implements Chain { protected Chain chain; public TimeChain() { chain = null; public void addchain(chain c) { chain = c; public Chain getchain() { return chain; //check to see if swimmer's time is faster than slow cut public void sendtochain(swimmer swmr, Event evnt) { if (swmr.gettime () <= evnt.getslowcut ()) swmr.seteligible (true); else swmr.seteligible (false); System.out.println("TimeChain:"+swmr.getEligible ()); sendchain(swmr, evnt); //test for null and send to next chain element protected void sendchain(swimmer swmr, Event evnt) { if( chain!= null) chain.sendtochain (swmr, evnt); We can derive the rest of the chain elements from this one, so the amount we have to rewrite is very small indeed. Here is the one that tests for a time slower than the fast cut: public class stimechain extends TimeChain { //check to see if swimmer's time is slower than fast cut public void sendtochain(swimmer swmr, Event evnt) { if(swmr.gettime () > evnt.getfastcut () ) swmr.seteligible (true); else swmr.seteligible (false); System.out.println("sTimeChain:"+swmr.getEligible ()); sendchain (swmr,evnt); //send along chain

Overall here, we create 4 little classes for the four tests we ve described and connect them together in a chain. Here is the code that sets this all up. The times were taken from standards for 11-12 girls 100-yard breaststroke at a qualifying meet. public class ChainSwim { public ChainSwim() { //set up the event Event evnt = new Event(2,100,"Breast"); evnt.setfastcuts (121.0f, 136.5f); evnt.setslowcuts (132.99f,149.49f); //set up a swimmer Swimmer Evelyn = new Swimmer("Evelyn", "Earnest"); Evelyn.setTimes (123.5f, 131.0f); //set up the timing chain TimeChain timechn = new TimeChain(); stimechain stchn = new stimechain(); timechn.addchain (stchn); nctime nctchn = new nctime(); stchn.addchain (nctchn); snctime snchn = new snctime(); nctchn.addchain (snchn); //begin the tests timechn.sendtochain (Evelyn, evnt); //and print out the result System.out.print(Evelyn.getName ()+" is "); if(! Evelyn.getEligible ()) System.out.print("not "); System.out.println("eligible"); static public void main(string argv[]) { new ChainSwim(); We defined this swimmer so she qualified for the meet based on her conforming times but not based on her non-conforming times. We designed each of the timing chain classes so it prints out its decision, so we can monitor the decisions it makes, in case we got one wrong. Here are the results: TimeChain:true stimechain:true nctime:true snctime:false Evelyn Earnest is not eligible As you can see, it found her eligible until the very last test. Advantages of Chains One great advantage to taking these tests apart and putting them in a chain of objects is that you can add more at any time. I alluded to further complexity earlier. Some of that lies in the fact that even in the US and Canada there are really 3 courses to consider, the

other being 25- meter pools. In the UK they recognize a wide variety of other pool lengths based on the fact that there are a wider variety of pools in the UK. This system is adaptable to more courses and more distances very easily. Diagramming Our Chains It is sometimes instructive to see that this is really quite a simple and extensible system by looking at its UML diagram, as we show in Figure 2.

Figure 2- The UML diagram of our timing chain of responsibility. To review, we start with a Swimmer and an Event object, and a Chain interface. We implement the Chain interface in TimingChain, and then derive the remaining classes from it. Concluding the Chain We ve seen here that the Chain of Responsibility takes a set of decisions and puts on in each object and passes the data long so each object can work on it. The objects can then decide to pass it on or not based on what they are to accomplish. In a real-life situation you also need to decide what to do when the data does not match any of your preconceived notions. You can fail silently, pass the data to an error handler chain object or take some default action. Any of these are possible, based on the last item in the chain. In any case, it s a far simpler and more flexible system than a page of if-else tests and flags. James W. Cooper is the author 13 books, most recent of Java Design Patterns: A Tutorial, published by Addison-Wesley in 200. He is also the president of Lab Software Associates, which loses money supplying swimming software.