Sunday, January 31, 2010

Day 19

Some serious refactoring and boolean reduction. My last post showed an attempt at making a long if statement more readable, using a technique that really didn't fit the situation. I used some hidden logic to generate some numbers with no clear meaning, to decide what action to take next. Though the action was clear, how I arrived on this action was not. I also drastically increased the amount of code in order to obtain only a bit more clarity.

Micah and I went back to thoroughly refactored and reduced the if statement. This was made quite easy because of a comprehensive test base, so that our refactoring could focus solely on simplification without worrying about function.

The process of simplication is pretty amazing. Though somewhat time consuming and attention demanding, it yielded some interesting results. As we refactored, we simply looked for patterns in the code, and through these patterns we searched for a higher level of abstraction. Bit by bit we were able to generalize and generalize until we would suddenly hit a new understanding, at which point great leaps of simplification could be made.

So after many itterations and cycles of refactoring we discovered what the logic really meant, and thus were able to greatly reduce the number of lines of code it took to express the same algorithm.

Once again, this is logic to decide what words need to be selected while dragging the mouse over some text after you double click and hold (in some word processors and this one, when you double click and drag the selection mode switches from individual characters to full words) . All of the 'isRightOf ' sorts of references refer to the position of the mouse in relation to the cursor and selected text.
Here was the process:

Starting with the If-Else chain I showed on my last post, we started refactoring out some of the conditionals into expressive methods:

public void invoke()
{
if (mouseIndex > boxInfo.findWordsRightEdge(boxInfo.cursorIndex))
{
if (mouseIndex > boxInfo.selectionIndex)
{
boxInfo.selectionIndex = boxInfo.cursorIndex;
boxInfo.cursorIndex = boxInfo.findWordsRightEdge(mouseIndex);
}
else if (boxInfo.cursorIndex < boxInfo.selectionIndex)
boxInfo.cursorIndex = boxInfo.findWordsLeftEdge(mouseIndex);
else
boxInfo.cursorIndex = boxInfo.findWordsRightEdge(mouseIndex);
}
else if (mouseIndex < boxInfo.findWordsLeftEdge(boxInfo.cursorIndex) && mouseIndex > boxInfo.selectionIndex)
{
boxInfo.cursorIndex = boxInfo.findWordsRightEdge(mouseIndex);
}
else if (mouseIndex < boxInfo.selectionIndex && mouseIndex < boxInfo.findWordsLeftEdge(boxInfo.cursorIndex))
{
if (boxInfo.cursorIndex > boxInfo.selectionIndex)
boxInfo.selectionIndex = boxInfo.cursorIndex;
boxInfo.cursorIndex = boxInfo.findWordsLeftEdge(mouseIndex);
}
}



With a limited understanding of what the true nature of this logic was, we tried several different naming schemes to see what worked:

if (isRightOfCursor())
{
if (isRightOfSelectionOnOriginalWord())
{
swapSelectionDirectionAndExtendToRight();
}
else if (isSelectionFacingLeft())
reduceSelectionFromLeft();
else
extendSelectionToRight();
}
else if (isLeftOfCursorInsideSelection())
{
reduceSelectionFromRight();
}
else if (isLeftOfSelection())
{
if (isSelectionFacingRight())
swapSelectionDirection();
extendSelectionToTheLeft();
}
}


Then we worked to get some symmetry to simplify it:

if (isRightOfCursor())
{
if (isInsideSelection)
reduceSelectionFromLeft();
else if(isRightOfSelection())
{
if (isSelectionFacingLeft())
swapSelectionDirection();
extendSelectionToRight();
}
}
else if (isLeftOfCursor())
{
if(isInsideSelection())
reduceSelectionFromRight();
else if (isLeftOfSelection())
{
if (isSelectionFacingRight())
swapSelectionDirection();
extendSelectionToTheLeft();
}
}



This new format gave us the idea that we have a head and a tail, since the Cursor is always at the head we could say the selection ends at the tail. Now we have a direction and position built into our abstraction:

if (isRightOfHead())
{
if (!isRightOfTail())
reduceSelectionFromLeft();
else if(isRightOfTail())
{
if (isSelectionFacingLeft())
swapSelectionDirection();
extendSelectionToRight();
}
}
else if (! isRightOfHead())
{
if(isRightOfTail())
reduceSelectionFromRight();
else if (!RightOfTail())
{
if (isSelectionFacingRight())
swapSelectionDirection();
extendSelectionToTheLeft();
}
}


A little Simplification:

if (isRightOfHead())
{
if (!isRightOfTail())
reduceSelectionFromLeft();
else
{
if (isSelectionFacingLeft())
swapSelectionDirection();
extendSelectionToRight();
}
}
else
{
if(isRightOfTail())
reduceSelectionFromRight();
else
{
if (isSelectionFacingRight())
swapSelectionDirection();
extendSelectionToTheLeft();
}
}



Now its clear that we are only doing 2 things. Moving the head and swapping the head and the tail (which is really just turning around). This allowed us to simplify the actions and lead us closer to a good solution. (also a little extra extracting methods to variables and such):

if (rightOfHead)
{
if (!rightOfTail)
repositionHead(boxInfo.findWordsLeftEdge(mouseIndex));
else
{
if (!selectionFacingRight)
turnAround();
repositionHead(boxInfo.findWordsRightEdge(mouseIndex));
}
}
else
{
if (rightOfTail)
repositionHead(boxInfo.findWordsRightEdge(mouseIndex));
else
{
if (selectionFacingRight)
turnAround();
repositionHead(boxInfo.findWordsLeftEdge(mouseIndex));
}
}


At last it is clear, for the most part, what is going on. We will always be moving the head, and we will be turning around only if the mouse is trailing the tail. If we are going to the right, we will always be positioning the cursor on the right edge of the word. Going to the left, the cursor is on the left edge of the word. This understanding leads us to these two boolean equations, and their respective actions:

boolean isMouseTrailingTheTail = selectionFacingRight && !rightOfTail || !selectionFacingRight && rightOfTail;
boolean isHeadingToTheRight = selectionFacingRight && !isMouseTrailingTheTail || !selectionFacingRight && isMouseTrailingTheTail;

if(isMouseTrailingTheTail)
turnAround();

if(isHeadingToTheRight)
repositionHead(boxInfo.findWordsRightEdge(mouseIndex));
else
repositionHead(boxInfo.findWordsLeftEdge(mouseIndex));


Then with some boolean arithmetic and De' Morgan's Law I found a remarkably simple and, after the fact, obvious solution:

boolean isMouseTrailingTheTail = selectionFacingRight && !rightOfTail || !selectionFacingRight && rightOfTail;
if(isMouseTrailingTheTail)
turnAround();

if(rightOfTail)
repositionHead(boxInfo.findWordsRightEdge(mouseIndex));
else
repositionHead(boxInfo.findWordsLeftEdge(mouseIndex));


A massive simplification, clarification, and reduction for what was once an incomprehensible If-Else chain. This new form is leaps and bounds better than the switch statement.

Thursday, January 28, 2010

Day 18

Switch statement. Most of the time it seems like a judgement call whether or not they are actually better than chains of if statements.

Today I had a very large If-Else statement, and I needed some way to make it more transparent. I wanted to use a jump table or hash-map to solve this. I would create some key determined by a few common factors, and then assign a method to each key in the hash-map. Unfortunately... to the best of my understanding, Java doesn't allow you to place method calls in has-maps. I would have had to use the Command pattern, make some 'Runnable' classes for each of the methods I wanted, and then stick these runnable objects into the hash-map in place of the methods.

A whole new Command Pattern seemed overkill to simplify my one method with the if-else chain, so instead I did Java's equivalent to a jump table. A switch statement in Java actually compiles directly down to a jump table. I find this a bit annoying because if Java is just going to make a jump table anyway, they should let me make one too. Either way, I used the same basic principle to create a code, and then use the code to select the correct method.

The if statement was being used to decide some word selection criterion. Say you double click and hold on a word, if you then begin moving your cursor over another word, many text areas will jump into a word selection mode and select the entire word at once rather than just following your cursor. So here was the if statement:




if (mouseIndex > boxInfo.findWordsRightEdge(boxInfo.cursorIndex))
{
if (mouseIndex > boxInfo.selectionIndex)
{
boxInfo.selectionIndex = boxInfo.cursorIndex;
boxInfo.cursorIndex = boxInfo.findWordsRightEdge(mouseIndex);
}
else if (boxInfo.cursorIndex < boxInfo.selectionIndex)
boxInfo.cursorIndex = boxInfo.findWordsLeftEdge(mouseIndex);
else
boxInfo.cursorIndex = boxInfo.findWordsRightEdge(mouseIndex);
}
else if (mouseIndex < boxInfo.findWordsLeftEdge(boxInfo.cursorIndex) && mouseIndex > boxInfo.selectionIndex)
{
boxInfo.cursorIndex = boxInfo.findWordsRightEdge(mouseIndex);
}
else if (mouseIndex < boxInfo.selectionIndex && mouseIndex < boxInfo.findWordsLeftEdge(boxInfo.cursorIndex))
{
if (boxInfo.cursorIndex > boxInfo.selectionIndex)
boxInfo.selectionIndex = boxInfo.cursorIndex;
boxInfo.cursorIndex = boxInfo.findWordsLeftEdge(mouseIndex);
}

Unfortunately blogspot makes it rather difficult to display code, and the if statement is hardly readable even properly formated, so good luck reading that...

So to refactor this I created a method object, and used a few criterion to determine an index, and then plugged this into a switch statement. I then made a descriptive method for each action. Here is the refactored code:




public void makeProperWordSelection()
{

switch (calculateSelectionDispatchIndex())
{
case 0:
extendSelectionToRight();
break;
case 1:
extendSelectionToRight();
break;
case 2:
reduceSelectionFromTheLeft();
break;
case 3:
swapSelectionDirectionAndExtendToRight();
break;
case 4:
swapSelectionDirectionAndExtendToLeft();
break;
case 5:
reduceSelectionFromTheRight();
break;
case 6:
extendSelectionToLeft();
break;
}
}

private int calculateSelectionDispatchIndex()
{
int dispatchIndex = 0;
if (mouseIndex > boxInfo.getSelectionIndex())
dispatchIndex += 1;
if (boxInfo.getCursorIndex() < boxInfo.getSelectionIndex())
dispatchIndex += 2;
if (mouseIndex < boxInfo.findWordsLeftEdge(boxInfo.getCursorIndex()))
dispatchIndex += 4;
return dispatchIndex;
}

private void swapSelectionDirectionAndExtendToLeft()
{
boxInfo.setSelectionIndex(boxInfo.getCursorIndex());
boxInfo.setCursorIndex(boxInfo.findWordsLeftEdge(mouseIndex));
}

private void reduceSelectionFromTheRight()
{
boxInfo.setCursorIndex(boxInfo.findWordsRightEdge(mouseIndex));
}

private void extendSelectionToLeft()
{
boxInfo.setCursorIndex(boxInfo.findWordsLeftEdge(mouseIndex));
}

private void reduceSelectionFromTheLeft()
{
boxInfo.setCursorIndex(boxInfo.findWordsLeftEdge(mouseIndex));
}

private void swapSelectionDirectionAndExtendToRight()
{
boxInfo.setSelectionIndex(boxInfo.getCursorIndex());
boxInfo.setCursorIndex(boxInfo.findWordsRightEdge(mouseIndex));
}

private void extendSelectionToRight()
{
boxInfo.setCursorIndex(boxInfo.findWordsRightEdge(mouseIndex));
}




Its debate-able whether or not this is actually better, but I think it at least makes it more readable if you are looking for a specific outcome. It just so happens that it lined up much better with the tests.
I'd like to hear if you think this helps or not, and if not, how you would refactor.

Wednesday, January 27, 2010

Day 17

Lots of busy work today. Micah was trying to whip together a quick website that could do HD video streaming. As a result, I spent a lot of time fishing for HD videos we could use as well as getting converters to get the video format we needed. Blasted watermarks... Useable free converters are a rare commodity. Also, who knew there were so many versions and formats for .mp4 files alone? Its kinda ridiculous.

Streaming videos was another topic we looked into. As it turns out, real streaming is actually fairly rare. YouTube by default doesn't actual, at least for all the videos I looked at, use streaming. True streaming is where the video data is only on your computer for as long as it needs to be. Typically there is a slight buffer, so the video is loaded for just a few seconds before the portion which you are watching, but after you watch it - it is gone. It doesn't save the video on your computer, nor does it keep downloading if you stop watching. It only downloads as much as is needed to create a reasonable buffer.
Most sites will simple download the video onto your computer and play it from your computer's memory rather than from a live feed. What is often mistook for streaming is when the video is downloaded, but starts playing before it is complete. This is what most websites seem to do, and as a result the file is actually on the computer...
Now that I think about it... in a way that seems to be breaking copyright laws in some manner. A sight like Pandora, which 'streams' songs like a radio, is actually creating copy after copy of those songs on the client's computer. Since the files are already on your computer, the distribution has already been achieved. In most cases the client never knows this, and the file is deleted once they close the browser or perhaps when the cache is cleared; however, it is actually quite easy to capture those files. All you have to do is find the source of the file (which the browser tells you by the way...) and then redirect the download to say... your desktop.
This isn't so easy with real streaming. I don't know of anyway, yet, to capture and save a live stream. I am sure it is possible, but it certainly seems like it is less of a copyright violation. You would actually have to be making a copy of the data that is otherwise free flowing through the web and your computer.

So how about that iPad? I know a lot of people are saying its no big deal - it doesn't really have anything new - it's just a bigger iPhone. I suggest you think twice.
Consider the difference between a little car and a bigger car. They are really just the same thing. They basically have all the same parts, nothing exceptionally different... its just that one is bigger. Consider that the purpose and goal of each car is to get the driver from point A to point B. The size difference, however, is no small matter. giggle giggle. There are a vast number of things you can do with a big car that you couldn't dream of doing with a small one, such as: hauling a trailer, driving many passengers, carrying lots of luggage or boxes, and a lot more. Naturally a small car can do things the bigger car can't do as well, but the point is that the fact that they are drastically different in size makes a huge difference!

The iPad will have thousands of new possibilities and enormous potential because of its greater size. It will live in a whole new niche of its own. At first, I see this device being extremely desirable for most common house wives/husbands who use computers for just a few key things. They like to have access to a computer in their kitchen, or study that they can use to write papers, surf the web, write emails, watch movies or videos, collect (but certainly not listen to) music, and so forth. These are the exact things which the iPad will offer. Not only will it provide those things, it provides them in better ways, and for less of a dent in the piggy bank.
Soon after these house wives/husbands become addicted to the iPad, bringing it everywhere in the house that they go and almost making it a 5th limb, their spouses will begin to really want one too.

The next, and fairly obvious, niche the iPad will fill is the student's backpack. It's easy to picture a classroom of students using iPads to take notes in class, read their text books, work on their homework, check and set their schedule, and even take quizzes or tests on secure networks. How could anyone brush off the iPad as no big deal when it could completely revolutionize the way students interact with their classes. Backpacks could transform from - heavy burdens filled with books, calculators, pencils, and other various materials - to a lightweight carrier for a single 1.5lb electric device and maybe a few utensils.

These are just two, out of many, clear niches that no other product has yet been able to fill, and that the iPad will slide into gloriously.

This is just the beginning.
If you don't think this product will succeed, sell all your apple stock and make it cheaper for me to buy it all up.

On a side note... I have to agree that its kinda crappy it doesn't have multitasking. I sure hope they include this in later versions because its pretty stupid to not be able to write a paper while listening to Pandora.

Tuesday, January 26, 2010

Day 16

Estimating a large project can be a very time consuming endeavor. Today Micah and I were making estimating how many man days it would take to build up a project for a possible client. First, Micah spent several hours splitting up the project into groups of stories, organized by topic and possible release points. Then we sat down and estimated every single one of the stories, first briefly discussing what it would entail, and then sticking both hands out and giving some estimates. I believe I have discussed the optimistic-realistic-pessimistic estimate strategy Micah uses, but what I would like to discuss is how long it all takes.

Some stories are easy to estimate and take 30 seconds to a minute to figure out. Other stories can take a few minutes if we have to discuss, in a fair amount of detail, what it will require. When you have a lot of stories to get through, this process just takes too long. I would imagine the same danger comes in with SAT graders who, after spending the whole day grading, might start to rush a little bit. Near the last few stories, the estimates begin to come off a bit faster. Given, these are just estimates and not hard contracts, it could still be a concern. It might be better to do just a few estimates at a time, or perhaps to charge a small fee to get an estimate since it takes so much time.


"90% of confusion comes from bad naming" - Eric Smith. Its funny that he said this today, because I also got a text from a previous co-worker today quoting some of my code:
be_in_the_tab = !conditional_not.nil?
Its pretty awful... I spent a few minutes myself just trying to figure out what I meant. The issue is the name 'conditional_not' which was actually a boolean meant to represent if the word "not" was in a string. This was for a cucumber step definition, which had an affirmative and negative version, so I wanted to keep the same logic but just reverse it if there was a 'not' in the acceptance test.

So true it is though. One poorly named class can drastically confound the poor soul trying to unveil the intent of a package. One inaccurately named method can hide the purpose of a class. A single thoughtlessly named variable can transform a simple method into an enigma. Just one boolean named 'conditional_not' can inspire a coworker to remind you of your ineptitude.

If you can't think of the right name for a class, method, or variable at the time you need it, then remind yourself to change it later. You don't want to be leaving behind a trail of confusion. Just as a poor name can hide the purpose or goal of some code, a good name can make it clear as day.

Monday, January 25, 2010

Day 15

Its amazing what men can do. Its simply astounding to look at a website, see that it works and has all these neat features and nic-nacs... and then you look at the code and your brain drips away into a coma. These days, with Rails and all, its pretty easy to whip up a website, add some nice features, and show someone else your code without them vomiting. In fact, they might actually be able to add on to your code without leading to code rot. I think, however, it is the true test of man to be able to write an absolutely heaping... smoldering mass of what only a maladjusted juvenile from the pits of a decaying Sparta could call code, and then to be able to add features to it. Its kind of like going down a mile of slip and slide made of sand paper and coated with boiling oil saturated with salt... it takes some serious balls.

I saw this pile of code today. I swear when Micah opened the file a small chunk of my soul escaped into the null ether. Written primarily in PHP, coated in some HTML, and lathered with hidden chunks of JavaScript, this project was pretty nasty.

To begin I did some wikiearch (its like research... but with wiki's) and I discovered that PHP is quite similar to Java or C++ in syntax, but is more of a dynamic language. So unconcerned with my ability to decipher the meaning of some jolly PHP files, I joined up with Micah to look at the code.
Normally when I see experienced programmers look at a new batch of code, even if it is pretty cryptic, I see little flares or sparks in their eyes as they catch something familiar and gain a greater understanding of the code's intent. Sometimes I even see smirks as a connections are formed and the big picture sets in. Micah's face was solid, unflinching, and deeply determined to find any meaning in the code.

It's times like these that make me really appreciate knowing about this whole Agile - Craftsmanship world. All I could picture, as we attempted to decrypt the code, was a team of men trying to change the color of a single item of text on a page and as a result were pulling out gobs of rapidly graying hair, screaming and yelling in the ancient spirit of the blame game, and a pilling up the corpses of the developers before them.

This is why I will now vow that:
- I, Justin Martin, shall never, for any reason beholding, relinquish or let degrade my standards of code, and hereby choose to do unto my code that which I wish others would do unto me"

Perhaps a bit much... but just like a pendulum, when you swing far to one side you can't help but swing far back to the other.


Thursday, January 21, 2010

Day 13

I got a lot of tid-bits of information today. I spent much of the day making a Keynote presentation for one of our new potential client, using the mockups that I created from Balsamiq. Micah and I then did some estimates on how many man-hours it would take to finish a workable minimum value sort of design. I also attending an iteration meeting and a code review on another one of 8th Light's projects. After work I went to a Scala User Group and heard a talk from Daniel Spiewak. He was very impressive, offering good information along with answering a lot of excellent questions.

From the code review I learned how difficult it can be working with a third party application. Say you have set up an application with a design that fits it nicely, and a flow that suites all of your needs. Then, suddenly your customer wants you to use an unanticipated third party program or web service in your application. Even if you have a nicely organized, highly decoupled and flexible program, implementing a third party into the mix can be quite a challenge.
The first challenge would of course be understanding how this third party program works. This might be reasonable, but your employer wants you to start implementing it NOW. So you start writing code, rather guessing how it works, and within less time than you might think, you get a bit of a mess. The more you incorporate the third party app, the more you learn about it, and the more you realize that you were wrong when you started working with it. Yet, you can't just go back and try again because your customer is expecting functionality and isn't all that pleased when you tell him/her that you have to take it away.
Another issue is that you might be fitting a square block into a round hole. You have this pretty design that you are extremely pleased with, and suddenly you have to find a way to jam some ugliness into it. Not saying all third party apps are ugly, but it seems like thats how they always appear when you first realize you have to fit it in with your design. Of course, you can't suddenly redesign your entire program just to work with this third party app, because your customer would freak. Instead you have to use some hodge-podge means to link everything together. If your not super careful, which is extremely difficult but always easy in hindsight, you will wind up with a mess.

The way Micah and I did the estimating was pretty interesting, and made a lot of sense. He set up a table with the features - an optimistic - a realistic - and a pessimistic estimate of how long the each feature would take. Then he calculated the standard deviation for each feature, and for the project as a whole. This gave us a pretty big range for how long this project might take, which I believe is necessary since it is virtually impossible to accurately estimate a fair sized project before you even get started.


From the talk and after:
* Mix-in: A way to add functionality to a class or instance by making a new class or module which isn't meant to be instantiated. In Ruby, you can do this by creating a module with some concrete methods, and then extend from this module in some other class.

* Comet: This is a HTTP means to maintain a long held link between a server and a browser. Typically HTTP sends a request, waits for a response, then sends data. This is a very tedious process, and doesn't fit all models. Using Comet allows the server to keep an open connection and send data without receiving any reply. Systems similar to Google Wave, with live updates, would use something like comet.

* Actors: An actor is actually a mathematical model for performing parallel or concurrent computation. When using the model, everything is an actor. Actors don't run sequentially or in a particular order, but run simultaneously. Actors can send messages to one another, create new actors, and perform some specific actions. Since everything is an actor, there is no supreme controller, thus actors can only talk to actors they know about. One of the biggest advantages to the Actor Model is that it separates the sender from sent communications.
- Supervised Actors: This is an Actor Model, but with a supervisor for each actor that can monitor its activity. The main purpose I gathered from the supervisor, is that if the actor is destroyed for whatever reason, the supervisor can see this and restart the actor.


* Cake Pattern: The Cake Pattern is a way to implement Dependency Injection, largely in Scala.



Wednesday, January 20, 2010

Day 12

I spent today creating a mockup of a website we will be building for a client. First I was using Photoshop to, rather tediously, make layer after layer to build up a flexible mockup. I was making it in a similar manner to how I write a program. I followed the Single Responsibility Principle in that I gave each layer a single purpose so that I could more easily reuse each layer, and mix and match them when the time came to make a Keynote presentation.
Then Micah found a cool mockup tool called Balsamiq mockup, which not only is design to make mockups, but also makes the mockup look... like a mockup. All the components, like text panels and button, have a hand drawn - kindergarden sort of look. This is especially cool because it emphasizes to the client that what you are presenting is in no way a hint towards the actual website design. It emphasizes that the mockup's only purpose is to demonstrate how the website might function and flow, largely in order to get some feedback.

Design Patterns:
* Factory Method Pattern: The Factory Method Pattern is a way to design an application that can create objects and act upon them, without actually knowing what class defines the object. It pushes the responsibility of defining which objects to instantiate to the subclasses.

The actual pattern is summed up in a single method, the Factory Method, and the rest is to make that method work. This is either an abstract method, or a method with a simple default constructor that is to be overridden. The Factory Method lies in the Creator class, and it returns an object called the Product. The Product is actually an interface that defines the objects which the Factory Method is meant to create. The Concrete Product is the implementation of the Product, and is actually created in the Concrete Creator, which implements the Creator.
So there is an application with a Factory Method. This application is meant to be versatile, and can't know the classes of the objects it is creating, but must act on them none the less. Some user of this application defines a Concrete Product and defines a Concrete Creator. Another part of the application tells the Creator that it needs a Product. The Creator then uses its Factory Method, which has now been overridden by the Concrete Creator, to make a Product, and returns a Concrete Product from the Concrete Creator. Then another part of the application can tell the Creator to perform some operation on the Concrete Product. The Creator can perform operations on the object without knowing its actual origin or class since the object implements the Product interface.

A simple example of this comes in the form of ice cream, and everyone likes ice cream. Say there is some ice cream cone maker that can put together a hot fudge ice cream cone. This dream maker doesn't know what flavor of ice cream is in the cone, nor does it care. All the dream maker knows is that it can put some fudge on some ice cream. The dream maker or Creator will make a cone only when something tells it to. The Creator will say ' I'm going to make a cone now' or run the Factory Method, at which point some other machine, the Concrete Creator, will supply the dream maker with a bucket of, say, vanilla ice cream or Concrete Product. The dream maker will then scoop up the Product, put it in a cone, and perform its fudging operation on the Product.

* Singleton Pattern: The Singleton Pattern is a simple pattern designed to help make sure there is one, and only one instance of a class. This is useful in situations where you have a system with several classes looking to use a Singleton, but if there are multiple instances of the Singleton, then the system breaks down. Some examples of this would be if you had some application with a Context class that holds all the essential data for the app, or if you had an operating system with a file system storing all the information of the running processes. Multiple unexpected contexts or file systems could complete destroy the program, thus you want to make sure there is always just one.
This works by designing a Singleton class that catches all attempts to construct it and with an easy and well known way to get the existing instance. You would create a class which has some static reference to itself. This reference could be initialized to null, or could be given a static instance. The Singleton's constructor should be set to do nothing, to defeat attempts at re-instantiation. You would also create a static getInstance() method, which would return the single instance. This would be the method all classes would use to get the Singleton instance.

If you used lazy instantiation by starting the Singleton ref out as null, then you get the benefit of only creating an instance when it is needed, but then you also might get a nasty race condition. Assuming in your getInstance() method you check to see if the ref is null before you instantiate it, then if you have two threads running which call getInstance() at the same time, it is possible that one thread will pass the conditional statement and then loose the processor before it creates an instance. Then the other thread could create an instance, return the processor to the first thread, which would then create a second instance since it already checked for null. So if you are using a Singleton in a multithreaded environment, you might be better off taking the safe route and sacrifice your lazy initialization to make sure you never end up with a race condition.

Tuesday, January 19, 2010

Day 11

I started the day off by finishing the refactoring of the Painter classes, and their respective tests. I then began thinking of the ways I could isolate regions to be individually marked as dirty and repainted with the appropriate painters. The biggest issue is that anytime a region needs to be repainted, I need to discover what text lies in that region, if there was a selection in that region, and where the cursor was.
Repainting all these different components independently and situationally might actually end up being slower than skipping all the extra logic, and just repainting the full region each time it is marked dirty. To be certain that I am actually optimizing rather than slowing, I will need to find out what part of the painting process is slow. Once I have some metrics to determine which of the following takes longer - painting pixels, determining which pixels to paint, or defining regions - I can then move to minimize the time consuming actions to optimize the paint algorithm.

The last part of my day was spent working with Micah on a new Rails app. We were trying to find ways to make accessing a bunch of the client's data intuitive for the users of the app. Since we really weren't sure how these users wanted to view the data, we were basically shooting in the dark with some general solutions.

To really know what the client wants, especially when you aren't sure how they want to use the app, is nearly impossible. This is why we will present to them a basic and minimum functionality demo in order to get some feedback and hone in on a better solution to meet their needs. We must stay flexible and not set our hearts on a certain solution.

Now I must begin making some general concepts of what the website will look like and how it will function using PhotoShop. We will use the photoshop generated images to show the overall feel and flow of the website in powerpoint slides. I suppose we wont begin really coding until we know we are heading in the right direction.


Design Patterns:
* Abstract Factory Pattern: The Abstract Factory Pattern can be used when there is a need for multiple groups of related objects without having to specify any concrete classes. In other words, the AFP is useful if you have several themes, with multiple components, that you want to be interchangeable to one idea or niche.

This works by first creating an Abstract Factory class that is to be the interface the client uses to make its desired theme. The Abstract Factory will have some concrete subclasses, one for each theme, which will implement the interface's abstract methods, and that will be used to generate the different components of the underlining idea for the respective theme.
There is also an interface for each of the different components of the underlining idea, and each theme will have its own implementation of these component interfaces.
Each of the Abstract Factory subclasses, call them Themed Factories, will depend on the corresponding concrete component classes.
When then client asks its Abstract Factory reference to generate an instance of the underlining idea or a component, the operation is delegated to whatever Themed Factory is populating the reference. In this way, the client never has to know about any of the concrete classes, but can receive instances of them none the less.

Say there is some simple clothing store. This store sells just one top and one bottom, which differ depending on if its summer or winter. This store wants some program to manage what items they are selling at any given point, and they hire you to make this system. You decide that you can implement this using the Abstract Factory Pattern, and so you start designing away. You make a ClothingFactory interface (the Abstract Factory) and then implement it with a concrete SummerClothingFactory and a WinterClothingFactory (Themed Factories). You also create a TopClothing and a BottomClothing interface (Components), and then implement these with concrete summer and winter - top and bottom classes (Themed Components). Finally you link the Themed Factories with their respective Themed Components so that the factories can generate instances of the components.
The client to your ClothingFactory, likely a cash register or online register, holds a reference to the factory. The reference is populated, with either of the Themed Factories, by the application's main class, based off whether its summer or winter. The client may then ask the factory for a top, or a bottom, and will get the appropriate clothing object without ever knowing about the different types.

An excellent advantage to this is that if the store owners wanted to add footwear to their vast variety of clothing, you could easily add sneakers to the summer theme and snow shoes to the winter theme. The Themed Factories could then be made to implement constructors for the footwear, and you would never have to worry about selling a t-shirt and shorts along with a pair of snow shoes.


Monday, January 18, 2010

Day 10

Today was all about optimizing the paint method for the TextInputPanel. I spent awhile trying out a few different strategies, picking and choosing things that worked and that I liked, and finally decided on one. It ended up being a combination of a Command Pattern, and another strategy that is similar to a Facade Pattern, but is lacking in the logic.

I made a TextPanelPainter interface with an abstract paint(Graphics2D g2) method. The subclasses would be a variety of single purpose painters like the TextPanelCursorPainter, or SelectionPainter, which would use an instance of the TextModel to change some data and draw the appropriate graphics. This is the Command Pattern portion.

In order to avoid having to create a new instance of say the CursorPainter every time the cursor had to be redrawn, I created a PainterStore class. The PainterStore would, upon initialization, make and save an instance of all the TextPanelPainters, as well as contain getters for each of them. This way, everytime I needed a CursorPainter, I would ask my PainterStore instance for one. This would be a Facade, if I gave the store all the logic, asked it for the painter I need, and then it spat out the appropriate painter based on the situation. I may switch to the Facade Pattern if I find an easy way to implement it.

The TextInputPanel would have a single painter reference, and anytime the panel was marked as dirty, it would called paint() on the painter. The painter would contain a reference to the paint job needed to be performed. For example, if a selection was being made and the user was holding shift and pressing an arrow key, then a SelectionPainter would get placed in the painter reference. When the key was finished being processed and the panel marked dirty, Limelight would then tell the panel to repaint, at which point the painter would call paint() and the SelectionPainter's paint method would update the selection instead of having to repaint absolutely everything.

Certain modification will be needed because when a region gets marked as dirty, it gets cleared and has to be completely repainted. The concept should still work though.

Design Patterns:

*Facade Pattern: The Facade Pattern can be used to create a single unified interface to a batch of classes that the client wishes to use.
This is useful when there are two separate groups of classes which need to interact, but you want to avoid having a web of dependancies. Instead of trying to mix and match the classes of the two groups, you can instead create a Facade which can sum up one of the two batches in a single easy to use interface.
This is done by creating a Facade class which know about all the classes of one of the two groups. Next, several methods are added to the Facade which, using all of the classes of the one group, sum up the functionality of the full subsystem. The second group can then call these methods on the Facade and use the full functionality of the subsystem, without ever having to know about any of the subsystem's classes.
An example of this would be if I had a textbox that needed to be constantly repainted for various reasons and there were a flurry of painter classes which could achieve this functionality. If I didn't want the textbox to have to decide which of the many painters I wanted it to use, but instead wanted the textbox to just call a few paint methods from one class, I could use a Facade. I would create a PainterFacade, that used all of the painter classes to create a few simple paint methods, or even just one paint method, for the text box. This paint method would then look at the current text box state, and decide which of the painters was needed, and what it had to do.

State/Objects for States Pattern: The State Pattern can be used to give a class a variety of different behaviors using the same methods, dependent on the state.
This can be useful if you have a situation in which you want all the operations for a task to occur in one class, but the operations depend on the state of an external source. If for example you have a robotic dog that can take it self outside for a walk for a... oil change I suppose. This robotic dog has some commands that say 'go outside', 'change oil', and 'come inside'. These commands depend on the weather or the planet the robodog is on. Thus in order to retain the same commands for different states, the robodog must implement the State Pattern, so that when it tries to moon walk it doesn't bring an umbrella instead of the Billy boots.

To implement this, you must create some class for the Context, an interface or abstract class for the State, along with the need state subclasses, and have the Context hold a reference to the State. Each of the State subclasses will implement the same set of methods in different ways, for the Context to use. The Context can then call the same method on its State reference, and depending on which state it holds at a given time, it will get different results.

Say our robodog has the some State class with the 'go outside' method implemented differently for sunny days and rainy days. It also has some Context class which holds a daily routine for the robodog. The Context says that at 2 pm each day, robodog must 'go outside'. The Context holds it State reference, and the state changes automatically based on the weather. This way, come 2 pm when the Context tells robodog to 'go outside' by calling the appropriate method on the State reference, robodog will know to bring an umbrella for a rainy state and sunglasses for a sunny state.


Saturday, January 16, 2010

Day 9

I spent Friday finishing up the text box which is now nearly in its final state. Just before lunched I paired with Mike, a visitor to 8th Light, and gave him a general intro to Test Driven Development and Pair Programming. At lunch I presented my two new testing patterns to the 8th Light guys, and got some general feedback. For the rest of the day, I wrote the Mouse Processor, completed some linkage between the TextModel and both Key and Mouse processor. All that remains to be done is optimize the repainting of the TextPanel at appropriate times.

Design Patterns:

*Command Pattern: The Command Pattern can be used to capture and store a request as an object, and then calling some abstract command, thus allowing you to populate clients with different and log-able operations.
To do this, a Command interface is created with an abstract execute() method and several concrete subclasses which are designed to define their own execute(). Whenever a request is made, it will call execute() on its instance of the Command interface. The instances of the subclasses will know who their respective receivers are, and what steps must be taken to complete their action.
This could be used to create a flexible barrier between some UI and application. A user could initialize some request by pressing a button or clicking some start key, thereby calling the application to action. Since the UI doesn't know who the request belongs to, or who the receiver of action will be, it would use its instance of a Command (given to it upon initialization) and call execute() which will generate the appropriate response.
So when, for example, a start button is created, it is given a Command object from the application. This command object will be some concrete class named StartCommand, which is a subclass of a Command interface. When the start button is clicked, it calls execute() on its Command object (of which the type is unknown to the button) which gets routed to the StartCommand. The StartCommand is then able to follow through with the necessary actions to 'start', calling the appropriate methods on its receiver.
Using this strategy, all UI interactions can be separated from the application, and all dependancies will flow at the Command Interface. It also means that all commands can be logged, and thus many of them could even be reversed.

This is actually quite similar to the structure I set up for my KeyProcessor. The TextInputPanel gets some keyPressed event which then uses some algorithm to select the appropriate processor. The TextInputPanel then calls processKey() on the selected processor, which proceeds to make the needed changes on its receiver the TextModel. The main difference is that for the Command Pattern I might have a KeyProcessor for each key which calls processKey() on its own KeyProcessor rather than having a Dispatcher in the keyPressed() method that decides who gets the command. The basic idea is quite similar though.

*Adapter Pattern: The Adapter Pattern allows two unrelated or unconnected interfaces to be connected so that they may be used in conjunction. This is done in one of two ways; either using a Class adapter or an Object adapter. The class adapter will inherit from one of the interfaces, and implement the other, linking the methods of the inherited interface to the methods of the implemented class. The object adapter will inherit from one interface and through some means get an instance of the other, and then connect the method calls from the parent by making calls on the instance. The exact manner in which this occurs is a tid-bit illusive to me and I think depends largely on circumstance.
Though a stretch, one example of this could be that my TextInputPanel, through the TextModel, is an adapter for the TextLayout class. A limelight app would be the Target, the TextInputPanel would be the Adapter, and the TextLayout would be the Adaptee. This would be the object adapter case. Limelight wants a Panel that can have some text and is clickable, and there is this TextLayout class out there that already has many methods to assist with these features, but isn't a Panel. Thus the TextInputPanel is used to adapt the TextLayout's functionality by inheriting from the Limelight Panel, and holding an instance of the TextLayout.
Limelight gets some MouseClick event, which is handed off to the TextInputPanel. The TextInputPanel then takes the request and (through some indirection) gets some TextHitInfo from the TextLayout, and therefore adapts the Layout to the Panel.
Let me know if there are any clarifications you can give as to the exact nature or best way to use the object adapter. I am not entirely certain as to how you get an instance of the Adaptee if it is meant to be an interface.

Now to optimize the painting of my panel.

Thursday, January 14, 2010

Day 8

I am pleased to say I have two new design patterns to blog about today, but these are of a slightly different nature. But first, a quick review of the day.

I spent about half the day today in an iteration meeting, observing and learning about one of 8th Light's productions. Trying to figure out what is specifically going on in a project, with minimal detail, but just a broad outline could develop into a very valuable skill. It is something I frequently see Uncle Bob do. It seems like he doesn't have to read the code to know what is going on, he just sees the shape of the code and immediately can tell the codes intention, and then even a better shape or form it can take to accomplish the same end.

The rest of the day I spent trying to refactor my tests for the KeyProcessor. It was especially challenging because I had never tested a framework like the Dispatcher I used, and so was struggling with the organization.

But now, the two new design patterns.

Design Patterns:

One of the reasons these two patterns are rather different is because they are actually for tests rather than production code. Another reason they are a little different is because I just made both of them! I came across them both in rapid succession, so the second pattern is actually an extension of the first pattern, but can also be used independently. Using a bit of insight from both Micah and Uncle Bob (as well as a nice feature in JUnit) I was able to find a testing strategy that perfectly fit my problem.

The Test Nest Pattern:
-Intent: To create a test file containing several tightly related test classes.
-Motivation: Consider designing tests to describe a case where there is some base abstract class and several small derivative classes that implement one or just a few methods of the base class. This could occur from using the Command Pattern, a Dispatcher/Jump Table, or other similar designs.
Having a file for each of the derived classes would not only seem overkill, since they are small and similar, but it would also make it more difficult to unveil the intent of the code using the tests. Instead, it makes more sense to have all the tests for these derivatives in one file, maybe named after the base class. The issue is that organizing the tests to be in accordance with their specific derivative becomes difficult.
One solution could be making a prefix title for each test, to first indicate which class it is for, and then describe the purpose of the test after the prefix. However this solution would lead to both long and complicated names as well as a test file that is difficult to parse through.
Another solution is the Test Nest Pattern.

-Structure: Using JUnit's SuiteClass technology it is possible to create a Suite Class, and several internal Test Classes.

Say you are trying to process all of the KeyEvents to use for some application. To do this, you create an abstract KeyProcessor class. This class is used as a dispatcher, and in conjunction with an indexing algorithm, it properly selects a derivative class to handle the KeyEvent. Each derivative implements a processKey() function, which is the derivatives only method. Say there is a CmdKeyProcessor and a ShiftKeyProcessor derivative that you are looking to test in the same file.
So you name this file the KeyProcessorSuite and you create two static internal classes named CmdKeyProcessorTest and ShiftKeyProcessor test. Next, you pull out all of the common fields and statically define them at the suite level. You could also statically define a standardSetUp() method that shares common setup steps that both test classes use. You then must add two lines above the suite telling JUnit that this a suite file, and which classes belong to the suite. It looks something like this:

@RunWith(Suite.class)
@Suite.SuiteClasses({KeyProcessorSuite.CmdKeyProcessorTest.class, KeyProcessorSuite.ShiftKeyProcessorTest.class})

public class KeyProcessorSuite{

public static KeyProcessor processor;
public static void standardSetUp(){...}

public static class CmdKeyProcessorTest{
@Before
public void setUp() {
standardSetUp();
processor = new CmdKeyProcessor();
}
@Test
public void canProcessCharacters(){
...
}
}
public static class ShiftKeyProcessorTest{
@Before
public void setUp() {
standardSetUp();
processor = new ShiftKeyProcessor();
}
@Test
public void canProcessCharacters(){
...
}
}
}

And voila! Each derivative class of KeyProcessor can get its own Nest for all its Tests in the KeyProcessorSuite. It provides a simple and intuitive organization for all the tests, and fits it all into a single file.



The Asserter Pattern:
-Intent: To provide a compact set of descriptive and reusable assertions.
-Motivation: There is a general rule that each test should have only one assertion. This could be a single assertEquals(int, int) or it could be a batch of closely related assertions checking the result of a single action. As test after test is written using a batch of similar assertions, even with different check values, there is still a lot of duplicated code. This should be avoided if possible.

One solution to this would be to extract methods that contain batches of reoccurring assertions and that take the check values for arguments. This is a practical solution if all the tests are in a single class, or if there is no underlining theme amongst the extracted assertion methods; however, if you are using a Test Nest Pattern and have several test classes, or if there is a theme in the extracted assertion methods, then this solution wont fit.

This is where you would use the Asserter Pattern.

-Structure: Using a separate or internal class, it is possible to create a class meant specifically to contain all of the assertion methods.

Say you have a TextBoxModel class, which contains all of the information of some abstraction. Say there are a set of actions you preform on the this data, after which you must check a similar set of fields. For example, you might have a set of three fields - int cursorIndex, int selectionIndex, boolean selectionOn - that define a selection, or a range of selected text. Then whenever an arrow key is pressed (perhaps when shift is being held down) you will want to check the values of these three fields. There is also another set of two fields - int cursorIndex, String text - that define the current text state. Whenever a character key or backspace is pressed, you want to check these two values.
You would then create a class (internal or external and static if it is inside a Test Nest Pattern), perhaps named TextModelAsserter, which would contain two assertion methods named - assertSelection, and assertTextState - that contain their respective assertions. It might look something like this:

public static class TextModelAsserter
{
TextModel boxInfo;

public TextModelAsserter(TextModel boxInfo)
{
this.boxInfo = boxInfo;
}

public void assertSelection(int cursorIndex, int selectionIndex, boolean selectionOn)
{
assertEquals(boxInfo.cursorIndex, cursorIndex);
assertEquals(boxInfo.selectionIndex, selectionIndex);
assertEquals(boxInfo.selectionOn, selectionOn);
}

public void assertTextState(int cursorIndex, String text)
{
assertEquals(cursorIndex, boxInfo.cursorIndex);
assertEquals(text, boxInfo.text.toString());
}
}

Next, you create a field of this class - TextModelAsserter asserter - in your test class, and then an instance of it, passing it the appropriate parameters, in a setup method. Using this instance, you can easily make precise and compact assertions, which not only speed up how quickly you can write solid tests, but also gives them a clean and regular look. You could use it something like this:

@Test
public void canProcessBackSpace()
{
processor.processKey(KeyEvent.VK_BACK_SPACE);

asserter.assertTextState(0, "ere are four words");
}

@Test
public void canProcessRightArrow()
{
processor.processKey(KeyEvent.VK_RIGHT);

asserter.assertSelection(2, 4, false);
}
And now you have a quick and easy way to make single lined, well organized, themed assertions throughout a single test class or across several test classes or Nests.



Tomorrow I get to finish writing up my KeyProcessor tests and code using there two new patterns I discovered!

Wednesday, January 13, 2010

Day 7

Lots of coding today. I spent the majority of the day coding away and implementing my KeyProcessor Dispatcher strategy. It felt good to be using TDD and switching around from class to class, all the while knowing everything still worked.

Now to try something a little different. There are still things I would like to include everyday, like notions of what it means to be a Craftsman, but I think I am going to get into the habit of adding at least two design patterns to my repertoire each day. Right now, I would like to focus on my architectural skills, and then latter on I will focus more on languages.

Notions of What It means to be a Craftsman:

* Having the Test Right Feeling: Previously, when I was spiking and trying to figure out how the text box would work, I always felt like I was hacking together some albatross of a program, and just hoped things would work. It still felt great when I got to see things work they way I thought, but more often then not... I ended up having to make several attempts to get it right, and was never completely sure something would work.
I would describe the Test Right Feeling as a sense of satisfaction from knowing that almost everything you type out is going to work just how you want it to. Its a confidence in your coding solution, because you explicit wrote out the problem. Most of the time you don't even feel the need to click the test button since you are so certain it will work, but you do it anyway because green makes you happy.
A Craftsman should be at home with the Test Right Feeling. It should be ingrained into him, and terribly important to him. Although, he can of course leave his comfort zone if need be, he always knows he has his home if he needs it.
In a way its like the difference between a carefree and reckless swordsman, hacking away at his foes in the middle of the battle field vs. the well disciplined Roman warrior who stays in formation and guards his brothers in arms. The swordsman might run out and rapidly chop up the enemy, but he is more likely to die quickly and leave his brethren hanging. The disciplined Roman will fight side by side, guarding the man on either side; and though he may not kill as quickly, he will certainly grind his enemy into nothing, while still staying alive and protecting his allies.
The Roman has safety in his shield, formation, and brethren. These are his tests. They give him the confidence in every step forward he makes. If he has he shield up, and his feet in synch with the ranks, he knows he will end victorious. And though it can be fun to hack away at your foes, recklessly but quickly getting the job done, in the long run you wont be able to match the frag count of the man who carefully and guardedly gets the job done.

* Put your Tests to the Test: Getting back into the groove of testing today, I began rapidly coding away: test, red, green ... test, red, green... test, red, green. In the process, I was constantly refactoring and keeping my production code neat, extracting methods with meaningful names, and removing any duplication. All the while, I neglected my tests. I wrote them, then made them pass, and then moved on to a new test. I forgot that it is not only important to keep your production code clean, but equally important to keep your tests clean. Since your tests are a form of documentation to your code, they better be just as easy to read, if not easier.

Design Patterns:

Bridge Pattern: The Bridge pattern is useful when you have some object, say a Text Panel, and you want to have multiple implementations of this Text Panel. You want to have a TextBoxPanel and a TextAreaPanel. So first you try out making an abstract TextPanel, and then having two implementations of it. Then you realize that you want each TextPanel to have the option of either Plain Text or Rich Text. So you then try implement another TextPanel that you call the RichTextPanel, and you implement another version of the TextBoxPanel and TextAreaPanel for the RichTextPanel. Already you notice this getting rather nasty.
The Bridge Pattern is a way to separate the Abstraction (TextPanel) from the Implementation (TextModel (either Plain Text or Rich Text)) making them both easily extendable and independent.
To do this, you create two separate abstract classes, TextPanel and TextModel, where the Abstraction will interact with the client and the Implementation will manipulate and handle the data or implementation. Next, you add some concrete derivative to each of these abstract classes to fulfill your intentions. You create a dual hierarchy where each piece on one side of the hierarchy is compatible with those on the other side. Thus you could have a TextBoxPanel with a RichTextModel or PlainTextModel, and likewise with the TextAreaPanel.
The Bridge comes through the connection between the Abstraction and Implementation. Typically the derivatives of the Abstraction call a method of the Abstraction, which then transfers the method call to the Implementation, which hands it down to an Implementation derivative; however, the system can work in either direction.
I used it in just this way except I would have, for example, the PlainTextModel calls a markAsDirty() method on the TextModel, which hands this off to the TextPanel, and then to a TextBoxPanel to indicate that this particular TextBoxPanel needs to be repainted.
The value of this is of course that it allows for easy expansion, but also that it hides the details of the TextPanel, in the TextModel, from the client.

Flip-Flop Pattern: Not an official design pattern, but still a useful one according to Uncle Bob. This pattern can be used when ever you have two concrete, or heavy abstract, classes that are cyclically dependent. In order to obey the Dependancy Inversion Principle, you don't want either of these classes depending on the other, let alone both. In order to resolve this debacle, you can add an interface on top of each of the two classes, each of which holds a reference to the methods used by the other class. Then you just draw crisscrossing dependancies to the corresponding interfaces and voila. Naturally this is why its called a flip-flop... since you flip, and then flop the dependancies. Yes. Like pancakes.

Tidbits:
Using typed arraylists: ArrayList < &type > list = new ArrayList < &type > (size)

Interfaces can only have abstract methods, no fields or data
Classes implement, not extend interfaces

Also, keep in mind the Abstraction vs. Instability graph, and the Main Sequence. Plot how abstract a class is vs. how unstable (the more classes that depend on it, the more stable it is -> the fewer the more unstable). The Main Sequence is where classes should be and is drawn something like this:

A |.\
B |...\
S |......\
T |........\ Main Sequence
R |..........\
A |............\
C |...............\
T |___________\_
.......UNSTABLE

Day 6

Yesterday was an enormously busy day, and I didn't have time to finish my blog.

Micah and I took a look at my design to see where improvements could be made. I'm happy to say, we found several areas in which it could be improved, and some areas where things already seemed like they could work. The first thing we did was compare my design against S.O.L.I.D. which I will go over a little more later. Then we played around with a few strategies until we found one that seemed to fit best. The rest of the day I spent re-factoring my code, rewriting code using TDD, and trying to implement my new design.

What I learned:

Underlining Principles of being a Software Craftsman:

* Using a standard to test your design: One standard I typically used is SOLID, for Object Oriented Design. The acronym S.O.L.I.D. was coined by Uncle Bob at Object Mentor. It stands for:

Single Responsibility Principle: A class should hold one concept, with one reason to change
Open/Closed Principle: A class should be Open for extension, Closed for modification
Liskov Subsitution Principle: A child class must be able to substitute its parent class
Interface Segregation Principle: No client should be forced to depend on methods it doesn't use
Dependancy Inversion Principle: Always try to avoid dependancies on concrete classes

These design standards (not all of which apply for all languages, like ISP in Ruby) can lead you closer to a robust and flexible design. Or at least, they will help you stay away from rigid and fragile designs.

* Personal Code Review: It is overwhelmingly helpful if you look over your code a few days after you wrote it. When your purpose behind doing some little trick, or some conditional is no longer quite so clear, you are able to see some weaknesses in your code.
Its rather like when writing a paper, and then going over it right after you write it with the intention of making sure everything you said makes sense. This is typically ineffective because your intentions, with the words you used, are still clear to you, but if you give your paper to someone else, they can point out where your words might not match your interpretation or intent.
Writing code is very similar, even though your code may function as you intended, it might not read as easily as you thought it would. Or at lease, it is likely that you can do a little more refactoring to make your intentions pop out of the code so obviously that it only take one look to understand what you are getting at.

* If you can write a mock yourself, write the mock yourself: This one stems right from Micah, who believes that adding complex mocking frameworks, adds needless complexity. Instead, if you ever need a mock object, write it yourself.
This has several advantages, the most prominent of which is that once you have written a good MockClass, you can use it anytime, anywhere. For example, yesterday I was trying to mock out a FocusEvent in Java, and I needed to pass a Component derivative for the constructor. Well it turns out, Micah has already written convenient mocks that I could use. Other advantages are that, you always know what your mocks can and can't do, and that you can keep it as simple and lightweight as possible.

General Knowledge of Language:

* Parallel inheritance structures can be dangerous: They might start out pretty, and you can add some nice abstract classes or interfaces to help segregate them, but eventually decay is inevitable... That is, assuming they continue to grow. There will be a point where if you want to make an addition to one side of the structure, that addition must be able to handle all the cases of the other side. This isn't too bad with just two or three derived classes, but thou shalt not make four. Five is right out.

* Just a note on abstract classes. A class is abstract if it has at least one abstract method. Though, you can declare a class as abstract even without an abstract method, thats just a phony.


Design Patterns:

* Strategy Pattern (aka Policy Pattern): The Strategy Pattern is way to use a variety of different algorithms for a single context at run time. Say you wanted to make a simple calculator that could add, subtract, and multiply. You could use the Strategy Pattern, with the calculator interaction with your user as the context, and the three operations as your strategies.
In Java, you would create a Calculator class, which had a means to interact with the user, and which would contain a reference to a Strategy Interface. The Strategy Interface would have an calculate method, and three derived classes which would implement this method. Then in the context, or the Calculator class, you would pass any of the operation strategies as an argument of the Calculator constructor, and then call calculate on the strategy reference to use the desired operation.

Now to finish implementing my KeyProcessor using the dispatcher!


Monday, January 11, 2010

Day 5

Today I finished designing my TextBox. At first I tried using a Chain of Responsibilities design pattern to help sort through all the possible key press and mouse click events, but then I switch to using a Dispatcher because of some insight from my father. I will explain these more later. After finishing my design, since Micah was no with me in the office today, I began coding my new design. When Micah and I review the design, there are likely to be some changes, possibly so much so that everything I coded today will go to waste.

What I learned today:

Underlining Principles of being a Software Craftsman:

*Experimenting with multiple Design Patterns: I am sure once a Craftsman reaches a certain point, they can simple pick up on the code scent and rapidly unveil the most logical Design Patter; however, before that point is reached, trying multiple patterns to a given problem might prove not only to create a better solution, but also to be a valuable learning experience.


General Knowledge of Language:

* Data classes, or classes composed of very little functional code and nearly all variables, can be dangerous. They typically will lead to procedural code, which is undesirable in Object Oriented software.

* It is usually better to avoid inheritance. If there is a way around it, even if you have to share instances of a class, you should use the lesser of two evils.

* Cyclic dependancies are typically a bad sign, however it is acceptable if two classes are logically dependent. In other cases you should stick an interface in between.

Design Patterns:

* Dispatcher / Jump Table: Though not really a design pattern so much as a strategy, I used it as a pattern to mold my code around. Typically a Dispatcher or Jump Table is an array of functions with indices as the result of some equation of operation. A common example is how C++ uses Jump Tables to access methods in a class.
I used a Dispatcher as an array of objects rather than functions. Each object was an instance of class designed to handle a different event. It was used to eliminate a flurry of if-else statements in order to determine which Key had been pressed, and if there were any modifiers (shift, command, alt being held down). I created an array of 16 different objects, each was the derivative of a KeyProcessor interface, and each had a processKey(int keyCode) method. Using 4 deciding factors, and scaling each, I created a simple algorithm to properly dispatch the KeyEvent to the proper handler.

* Chain of Responsibility Pattern: This patter works just as you might imagine from the name. It begins with some request that needs to be handle. This request is sent to some main processing object which checks to see if it can handle it, and if not, passes it along to the next processing object in the chain. If the next processing object can't handle the request, it the passes it along, and so forth until the request finally reaches something that can handle it. Typically there will be a well defined mechanism to pass requests along the chain, such that new processing objects can be easily added. The Chain of Responsibility pattern can actually be quite similar to a dispatcher with a pyramid like structure of responsibility.
I was going to use the Chain of Responsibility pattern just like a dispatcher, having high level links passing KeyEvents down to lower level links based off the same criteria I used to created my dispatcher algorithm. The chain would have been more like a tree, and each level would have a binary decision of which direction to pass the event on. In the end, this would have eliminated a large portion of the if-else chain, but would still contain several conditional statements.

Thats pretty much it for today. I have faith that tomorrow my design will withstand the scrutiny of Micah! Of course, it wouldn't surprise me if he had one simple improvement, which somehow alluded me, and that drastically alters my design...