Corey Ogburn

A Developing Developer

Let Your Voice Be Heard

clock August 9, 2010 15:20 by author coreyog

Oh, the irony! With a broken setup for comments, nobody could tell me they were broken. Anyway, the problem was caused by me not having a set of reCAPTCHA private/public keys. Now that everything appears to be in order, let me know what you think of everything. This site is still new, young and only run by one person so changes can happen quickly and suddenly. Now with working comments, you guys can tell me if other stuff is broken; I'm pretty sure the contact me section isn't operating properly. Don't forget that there's direct contact with me through the Digsby widget on the right side whenever I'm online! I look forward to hearing from you all.



Design Patterns: The Observer Pattern

clock August 8, 2010 20:58 by author coreyog

From Wikipedia: In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. Design patterns can be a touchy subject. Sometimes described as "a solution seeking a problem," they can complicate projects where they have been implemented incorrectly through misunderstanding the pattern or by being applied to a situation that doesn't warrant that design pattern. With that said, take this article with a grain of salt. Don't look for a place to use it, but keep it as a tool for when a problem that may need it arises. With that disclaimer behind me, let me introduce you all to the Observer Pattern.

Information changes. Constantly. If there's anything the web has taught us as developers, it's that stale data can hinder a project or a decision. When fields don't properly contain the newest, most up to date values your application feels flawed, or you receive invalid output. In today's world, a wide variety of information is time sensitive so the "freshness" of your data can quickly come into question. So how do you stay up to date? First thought is to continually check the information to see if it's updated, and if it has, then you update your representation of that information. Although at first glance this approach works, it brings problems. What if the data doesn't update frequently? What if it's an internet resource and your bandwidth is limited? Do you want to choke your bandwidth with the "what if" about your data's integrity? Ideally, you'd only check for new data when you know the data has changed, but that can mean that the new data has changed and you haven't/won't reflect that change for some time. Your next best bet is that you're notified when the value changes... Wouldn't that be something? The Observer Pattern is not perfect. It doesn't scale very well, so if you have thousands of things watching for an updated value, then there will be a slow down. The few times I've found that I need to use this pattern, it's been over a network.

Let's say you were in charge of writing some software for a gas station. You had to write the software that handled displaying the price at the pumps and the sign out in front. A quick fix would be to allow the pumps and the sign to repeatedly ask your software for the newest price and display that. This makes adding or removing new pumps or other price watching hardware or software less intuitive (especially if you want to update more than a single number or string). A better way is to separate things out. Instead each device initiating a connection to ask for the newest value to stay updated, these devices could register with the gas station software, giving the software a reference of themselves and allowing themselves to be notified when the gas prices change. The desktop software would simply keep every notifiable instance that has registered with it in a List, and when the price of gas changes, it notifies everything in that list. Doing this would help keep the desktop software maintainable if the gas station obtains more gas pumps, sells gas pumps, decides to post their prices online or change their sign out in front. As long as you maintain the code to have everything interface with the central desktop software using the Observer Pattern, things can subscribe or unsubscribe and can come and go quite easily.

This particular pattern gets used a lot in WPF by binding objects to controls. When an object is bound to a control and is updated, the control is as well. Consequently, if you have a Two-Way binding, you can update the object through the use of the control, such as changing to the text of a textbox to change a name in a phone book. Although not particularly useful as an application, I threw together a project that should help express the Observer Pattern, and you'll get to see a little binding in action. This project is in C# 4.0 and Visual Studio 2010. You can get the Express Edition here.

First, I made an ObservableObject like so:

public class ObservableObject : IObservable<int>

Note the generic typing of IObservable, the int. That is the type that will be passed from the ObservableObject to the ObserverObjects, to my understanding, this can be any type. If you right click IObservable<int> and Implement Interface, it'll add a method to the body of your code file:

public IDisposable Subscribe(IObserver<int> observer)

In my definition of the Observer Pattern above, it's unclear what the returned IDisposable object represents. The returned IDisposable object will allow an ObserverObject to cancel it's subscription and will no longer be updated when the ObservableObject updates it's value. To allow this to happen, an Unsubscriber class like the following is needed (this class is seperate from the ObservableObject class we started):

public class Unsubscriber : IDisposable {
    private List<IObserver<int>> _observers;
    private IObserver<int> _observer;
 
    public Unsubscriber(List<IObserver<int>> observers, IObserver<int> observer) {
        this._observers = observers;
        this._observer = observer;
    }
 
    public void Dispose() {
        if (_observer != null && _observers.Contains(_observer))
            _observers.Remove(_observer);
    }
}


When the object Disposes, it removes the IObserver from the List of IObservers and is no longer registered with the ObservableObject. With that in place, back to the ObservableObject class. Like I said, it needs to have a collection of all the registered Observers. So we're going to create a list and update the Subscribe method so that when something subscribes to this object, it's added to this list:

private List<IObserver<int>> observers = new List<IObserver<int>>();
public IDisposable Subscribe(IObserver<int> observer) {
    if (!observers.Contains(observer)) {
        observers.Add(observer);
    }
    return new Unsubscriber(observers, observer);
}

So now, we have something that can be subscribed to, but it doesn't have anything to pass to it's subscribers and it doesn't have any code to actually pass the value to them. Let's do both of these with a property.

private int _value = 0;
public int Value {
    get {
        return _value;
    }
    set {
        _value = value;
        observers.ForEach(x => x.OnNext(value));
    }
}


The ForEach method is a fun method when used with lambda expressions like it is now. It lets you run an expression on every entry in the list, we're currently passing the property value to a as-of-now unwritten method OnNext on each of the Observers in that list. Except for the Unsubscriber class, this is all in the ObservableObject class. Both of these classes are now done. It won't compile because I've actually used ObserverObject in the code as if that file was already written, but we're just now starting that file. Remember, this object passes itself to the ObservableObject through it's Subscribe method, and is then notified when the value changes. Let's start with having it implement IObserver<T>, since we're passing an integer between the ObservableObject and it's ObserverObjects, then it needs to implement IObserver<int> specifically:

public class ObserverObject : IObserver<int>

If you right click IObserver<int> and Implement the Interface, it'll add 3 methods: OnNext, OnError, OnCompleted. OnNext is the method that's called when it receives the Next value from ObservableObject. OnError is called if the ObservableObject runs in to an error, and that exception is passed back to all ObserverObjects. Eventually, for whatever reason an ObservableObject might be done broadcasting when it's value changed, at this point it calls OnCompleted. For this simple example application, we'll only implement OnNext. The ObserverObject will need a way to store the value it received in order to display on in a UIElement, so let's create another property.

public int _value = -1;
public int ReceivedValue {
    get {
        return _value;
    }
    set {
        _value = value;
    }
}

I didn't make an automatic property on purpose, I added custom binding here for the UIElements to stay bound, I'll talk about binding in a different post. With a variable to hold the observed value and a method to receive that value, let's connect the two.

public void OnNext(int value) {
    ReceivedValue = value;
}

Now the Observer Pattern is done being implemented by these two classes. We just need to use them. Back in the MainWindow.xaml that Wpf projects always start with, let's add some controls. Three labels, three textboxes, and one button. The labels and textboxes are paired together. I placed one label and one textbox and the one button near the top of the form, and each remaining label and textbox near each side of the bottom of the window, paired together. Using the labels, the top textbox was labeled "Observable" and the other two labels labeled their corresponding textboxes as "Observer." Since I'm going to talk about binding more in-depth later, I won't go into detail now, instead, I'll tell you that I bound one ObserverObject to each of the textboxes labeled Observer, and gave the button an event to set the ObservableObject's value to whatever int you type in the Observable box.

All the code for this post is in this project.

So, your own classes can implement IObservable and can update registered IObserver objects, updating them with each value, each error, and when it's done notifying them. This pattern is about reducing the communication between objects to that which is necessary for a remote value to stay updated with a changing value.



Motivation and Inspiration

clock August 3, 2010 23:12 by author coreyog

In order to become a good developer you need to have experience. Some people will start off appearing to be better developers than other people in class or early projects at work, but when the projects get bigger and the tasks get harder, the experienced developers shine. The best way to get experience is to go from job to job taking on a variety of different kinds of projects, but this is too reliant on other people hiring you and the kind of projects they give you. The better alternative is "private research," your own personal projects. I mentioned this before but some of the problems that arise are Motivation and Inspiration. A bunch of Hello, World! applications would provide you with some experience I guess, but obviously not the diversity that it'd take to be a valuable developer and a good colleague. Remember, it's not just important for your boss to like your output, it's equally (if not more) important for your coworkers to appreciate your input. A good quote about this is "write your code as if the developer who works with it after you is a psychopath and knows where you live." It could not be more true.

Inspiration. It's hard to practice a particular concept without having a desired outcome, so you need a semi-functional idea in mind. Of course the application is specific to the concept you're wishing to learn so there's no indefinite list of small apps to develop in order to learn everything. Some good starters might be a small chat program to learn about ports and sockets, maybe a calculator to learn about how to retain control over the state of the application when the user has a wide variety of choice inputs (a calculator app can be harder than you might think, even for a simple add, subtract, multiply, and divide integer based calculator), or even something as simple as an address book to learn about file storage and searching large amounts of data. You need to be inspired by somebody's needs. Even if your app isn't the best one out there, by having a set of goals to hold your output against, you no longer have a reason to call it quits on a feature if it gets too hard. This ties into motivation. Different people are motivated differently. Some people are motivated by the rewarding feeling of an empty to-do list, very task oriented people. Some are motivated with rewards for meeting these tasks or finishing a project. Sometimes it's the monetary gain of the finished project that motivates you. Regardless how noble your motivation is or not, it usually takes some sort of drive at two different points during a project:

  1. The beginning. Some projects seem daunting and it's not always obvious where to start. You need to use your own motivation technique to get past that hurdle. Abstract the project into each feature and start with the feature used my the most other features. A good foundation like that can make new features easier to add. Maybe all you need is the perfect design pattern, such as Model-View-Controller (MVC) or Model-View-ViewModel (MVVM), but read into them first, do not try and force a design pattern where it doesn't belong.
  2. The ending of a project. I especially lose motivation on personal projects where I don't have a due date or I have no gain for the finished project. The pieces of the project are all pulling together and you already have it all planned out. Sometimes you just want to move on or take a break. Well, it's not impressive on a resume to say "My personal research includes X, Y, and Z" and the interviewing company asks you to present these incomplete projects as part of the interview. You have to be prepared. The task-oriented have less of a problem with ending a project, in fact, many task-oriented people I know have a harder time beginning a project but near completion speed up and finish ahead of time.

Once you learn techniques that work for you, you can get yourself into a cycle of inspiring an application, and then motivating yourself through it to a finished project. Eventually it'll becomes a habit, and you'll find that there isn't enough time to work on all your projects. Currently I have 45 projects that are either done or in progress, most of which are in progress, even more are perpetually in beta. Having unfinished projects is not a sign of a bad developer nor is it holding you back from being a good one. However, not having any completed projects can be a red flag for potential employers. Not to mention, I know I feel a lot better when I complete a project. Good self confidence is good in any field.


Timeshift Is Now Up

clock August 1, 2010 12:22 by author coreyog

Timeshift, an encryption I've been working on with my friend Karl for over 5 years now, finally has a page of it's own. As it nears completion, Karl and I begin to gear up for starting a business around this algorithm, other algorithms we may develop, and potentially branching out to other concepts outside of computer security. The possibilities are endless and we're not closing any doors. Anyway, this algorithm has developed from a 256 bit encryption on up to 512, 1024, and finally graduating to 4096 bit. In addition to adding strength throughout the years, we've also decreased time. Timing how long it takes to do 100 MB\s, we started at a shameful 60+ seconds down to less than a second! That's about 150 MB\s! With the algorithm 99% done, we're approaching the point where we begin porting to other languages. Currently developed in C# .Net, plans are to rewrite the algorithm in unmanaged C++, Java, PHP, Objective-C and x86 Assembly (for the possibility of a hardware implementation). These languages ought to cover the majority of the market and allow almost any company to have this level of security in their own systems. We know there are many open source alternatives, but our goal has been to blow them out of the water and I believe we've succeeded so far. Over the next year this project is really going to take off, keep an eye out for updates.



Uploaded New Projects

clock July 24, 2010 19:03 by author coreyog

I finally got around to it, three new projects for you all: Circle Library, RunOnTop, and MyMathLib! Written from scratch, these projects of mine are now available, source code and all, for you all to use or play around with.

My Circle Library is a simple set of two classes that offer similar functionality to Rectangle and RectangleF except the classes are for our perfectly round friends instead. Granting you options to tell if circles are overlapping, if one fully encircles another, or if they contain a point, these classes allow for some simple 2D collision detection. Also, and I'm not sure where this can be applied, but given two circles, you can find the Minimal Enclosing Circle which is the smallest circle that completely contains both circles. That one took me awhile, but it's working great.

I developed RunOnTop to force other programs to start and remain always on top. It's a great little utility app for Calculator, Notepad, a window of your favorite browser (Chrome!), or whatever you need. I admit it is one of my lesser tested applications, but it does what I want it to do on my setup of Windows (with UAC turned completely off). UAC may not reduce functionality of this program, but I haven't tested so I don't know. The code is based around a few methods of the WinAPI if you want to discover how low-level C# can go.

MyMathLib was a project to teach myself about interpreters and actually make one. It translates human written algebraic expressions first to Reverse Polish Notation and eventually to a final solution. It handles most, if not all, of the mathematical operations you would run across in a high school algebra/trig class.

You can find these projects on the right under Pages. Take your time and meander through the code, or just download and use them for your own personal needs. If you find you have a great use that I may not have mentioned for some of these projects,  let me know in the comments.



Search

Digsby

AdSense

Sign in