Posts tagged Development
SOLID Development Slides + Code
Jan 25th
You can download the code for Visual Studio 2010 Beta 2 zipped up and ready to go here.
Getting to SOLID
Dec 22nd
The acronym for SOLID has been making rounds for some time now. SOLID is a set of principles that will help you write code that is easier to understand, maintain, and simple.
Writing SOLID code is not easy and takes effort and craftsmanship. The road to SOLID is not a direct route and you’ll need practice to get there.
Don’t start with SOLID.
Solve the problem first. When you are first given requirements have a design discussion to outline responsibilities for classes or interfaces based on the requirements but keep the design loose. Consider SOLID in that design discussion but don’t spend all your time on it. Think about the requirement and how you’re going to implement it with code. Once you start coding the code will paint a picture; it’s too hard to paint the picture first.
Getting to SOLID Requires Iterations.
Not project level iterations. These are much smaller, could be several per day. As you make your tests pass you gain a better understanding of the solution and you can begin refactoring code. The other day, in one 15 minute pair programming session, the project architect and I removed about 25+ lines of code. Shortly there after I performed some major refactoring. The codes understandability improved and the tests continued to pass.
Find New Eyes
Sometimes you get stuck in how you’re thinking about a problem. In my pair programming example above the project architect was able to see things differently and helped me get past a hurdle. If you’re stuck, find a trusted colleague or just put the code away and do something else for a while. When you come back with new eyes you might be able to simplify the code.
SOLID is a set of Principles
SOLID is not a solution but a set of principles to help get you there. Keep them in mind and use them judiciously as you refactor new or old code.
A Post on Growth as a Developer
Oct 4th
My good friend and colleague David posted “Growing as a Developer” and highlights two key points that helped him grow as a developer. While he gives me some kudos for being one that influenced him, he also influenced me and gave me new perspectives to look at. I will miss being able to seek out his opinion in person, however, now that he has at least signed up to Twitter perhaps we won’t be that out of touch (*nudge*).
Give the post a read; it’s short and sweet and includes links to some books that every developer should read at any level in their career.
Exploring the TouchPanel API with the Zune HD & XNA 3.1
Sep 19th
While I have been fully enjoying my Zune HD experience I decided I should give apps a try after seeing the announcement about XNA Studio 3.1 and the XNA Extensions for the Zune HD. I have explored XNA a little prior to this but did not really dig into it. With my Zune HD in hand I decided it was time to take it for a spin.
Getting Started – What you need:
- Zune HD (16 or 32gb, I rock with the 32) + Cable
- Visual Studio 2008 / Visual C# + XNA Studio 3.1
- Zune HD Extensions
- Zune Software must be closed while running XNA Studio and debugging on your Zune hardware
Should you try to run software on your Zune without the extensions you will get an error message to the effect of “The XNA Framework runtime required by this game project is not available on ‘{YOUR ZUNE NAME HERE}’”. If you see this message, make sure you have the extensions installed and that your project targets XNA 3.1. This post on the XNA Creators Club forums helped me get started.
For some other background reading check out “Nazeeh’s Little Corner of the Web”, particularly his posts Anatomy of a Game Part 1 and “Hello World!” in XNA.
Exploring Microsoft.Xna.Framework.Input
As with all things framework, namespaces help us find things. The default XNA Project for the Zune does not give you too many pointers on where to find your input devices so I hopped over to object browser and found some interesting classes:
The documentation on the classes is pretty skim so I took a stab at some code and hacked this out:
protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); //Get the touches from the TouchPanel TouchCollection touches = TouchPanel.GetState(); if (TouchPanel.GetCapabilities().HasPressure) { foreach (TouchLocation item in touches) { squareManVector = item.Position; touchPressure = item.Pressure; } } base.Update(gameTime); }
There is a TouchCollectionEnumerator, however, I was looking for the simplest thing that could possibly work and this does the job. What I did was created a TouchCollection variable “touches” and call “GetState” on the TouchPanel class. That provides a TouchCollection which we can enumerate through to update the position and pressure. I’m not entirely sure the check for HasPressure is needed, but I was exploring the API and thought I would see what that provided.
A couple of variables in here may leave you wondering, so I will explain them real quick. squareManVector is a Vector2 which sets the position of my square man sprite:
who is aptly named squareManTexture. Yes I know, he is nothing fancy! In my first attempts just to learn I was looking for the basics, so I stuck him at a vector of 0,0. But, after discovering the touch API I decided to see if I could move him around.
Also note that for the Zune HD the “BackButton” is the button on the center of the device near the bottom. Based on the code above it becomes the de-facto exit button.
In the Draw method I have the following code:
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); string currentVector = string.Format("{0}.{1} : {2}", squareManVector.X.ToString(), squareManVector.Y.ToString(), touchPressure.ToString()); spriteBatch.DrawString(font, currentVector, new Vector2(50, 50), Color.Black); spriteBatch.Draw(squareManTexture, squareManVector, Color.White); spriteBatch.End(); base.Draw(gameTime); }
What is the end result you ask? When the game loads, squareMan is hanging out at the top left of the screen:
If you touch the screen he obediently moves:
But we can do more than touch…so let’s drag him around:
Note that while dragging the pressure sensitivity begins to display. Freaking sweet! I don’t think I have been this giddy about programming since I first started. Look forward to more articles on XNA programming as I dive into it with the Zune HD. I might even have to hook up my 360 with XNA Studio to give that a whirl!
Update 9/19/2009 @ 11:47PM CST
Because I’m still tinkering with it, here is how you can use an IEnumerator with the TouchPanel which is probably the more proper way to use it:
protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); IEnumerator<TouchLocation> touches = TouchPanel.GetState().GetEnumerator(); while (touches.MoveNext()) { squareManVector = touches.Current.Position; touchPressure = touches.Current.Pressure; } base.Update(gameTime); }
Enjoy!!
Dependency Injection Part 2: Microsoft’s Unity
Dec 26th
In my previous post on dependency injection I discussed a simple way to enable dependency injection using configuration and System.Activator. The method described would be sufficient for many cases but may not offer enough power for every situation. This time we will explore the use of an Inversion of Control container, namely Microsoft’s Unity Application Block.
Taking the "another tool in the tool box" approach let’s explore unity using our previous example of a system which requires multiple authentication methods.
I downloaded and installed Microsoft Enterprise Library 4.1 (October 2008) which you can download here. If you do not need the entire Enterprise Library (EL) then you can download the standalone Unity Application Block here. I highly recommend trying out the EL because it has a lot of very useful application blocks for common needs of enterprise developers.
The benefits of using a more powerful framework such as Unity are that you get additional features such as simplified object creation and lifetime management (can register objects as singletons) in addition to the other benefits of looser coupling and more flexibility. You can also use caching to store containers and then retrieve them when you need to access it again.
I will be using the same solution and project as my previous post and we will start by adding a reference to the Unity assembly. The first method I will use is to manually register types with the unity container. The second will be using configuration to specify the container’s configuration and types to use. The ultimate bench mark for me will be to determine which method uses the least amount of code and leaves us with the most flexibility to make changes.
Manually Building and Registering Objects with the Container
Following the guidance in "Setting Up the Unity Container" I came up with this code:
Module Module3 Sub Main() Dim container As Microsoft.Practices.Unity.IUnityContainer = _ New Microsoft.Practices.Unity.UnityContainer container.RegisterType(Of Authenticator.IAuthenticator, _ Authenticator.DatabaseAuthenticator)() Dim authenticator As Authenticator.IAuthenticator = _ container.Resolve(Of Authenticator.IAuthenticator)() Dim userName As String Dim password As String Dim user As Authenticator.User Console.WriteLine("Username: ") userName = Console.ReadLine Console.WriteLine("Password: ") password = Console.ReadLine Console.Clear() user = authenticator.Authenticate(userName, password) If user.IsAuthenticated Then Console.WriteLine(String.Format("User authenticated via {0}!", _ user.AuthenticationType)) Else Console.WriteLine("User authentication failed!") End If Console.ReadLine() End Sub End Module
This was a pretty basic setup and the learning curve was almost zero. I was already using a similar method to set up my own dependency injection and this was a very natural seeming approach. However, I am not entirely satisfied with this approach as it has constrained us to making code changes and recompiling to switch to a new implementation of IAuthenticator.
Now this was a very basic and simple example so I wouldn’t say this is a fault of Unity but more a fault of me just doing the bare minimum to create a container and add an object to it.
Configuring a Container Using Configuration Files
Let’s look at using Unity’s configuration schema.
The big disappointment I had so far is that there does not appear to be a visual configuration tool. I know, how sad, but I do like having those tools available as I think they can help reduce little mistakes you can make when editing XML. The broader EL configuration tool is very handy and now that I am used to the structures it creates for things like logging and validation it is very easy to use.
After reading "Entering Configuration Information" and some trial and error I developed Module4 which will use a configuration to define the container.
Module Module4 Sub Main() Dim container As Microsoft.Practices.Unity.IUnityContainer = _ New Microsoft.Practices.Unity.UnityContainer Dim section As _ Microsoft.Practices.Unity.Configuration.UnityConfigurationSection _ = CType(Configuration.ConfigurationManager.GetSection("unity"), _ Microsoft.Practices.Unity.Configuration.UnityConfigurationSection) section.Containers.Default.Configure(container) Dim authenticator As Authenticator.IAuthenticator = _ container.Resolve(Of Authenticator.IAuthenticator)() Dim userName As String Dim password As String Dim user As Authenticator.User Console.WriteLine("Username: ") userName = Console.ReadLine Console.WriteLine("Password: ") password = Console.ReadLine Console.Clear() user = authenticator.Authenticate(userName, password) If user.IsAuthenticated Then Console.WriteLine(String.Format("User authenticated via {0}!", _ user.AuthenticationType)) Else Console.WriteLine("User authentication failed!") End If Console.ReadLine() End Sub End Module
After adding the required configSection the unity configuration block looks like so:
<unity> <typeAliases> <!-- User-defined type aliases --> <typeAlias alias="IAuthenticator" type="Authenticator.IAuthenticator, Authenticator" /> </typeAliases> <containers> <container> <types> <!-- Type mapping using aliases defined above --> <type type="IAuthenticator" mapTo="CustomAuthenticator.XmlAuthenticator, CustomAuthenticator" /> </types> </container> </containers> </unity>
I used the alias feature to create an alias name for the IAuthenticator. This lets you reference it by alias rather than including the full type information every time you are mapping an instance of the type.
In this example I rewrote the same program I was using for my simple dependency injection to use the Unity Application Block. The code changes amounted to about 5 lines of code for the simple use of Unity and 6 to use configuration. The code to use unity was very plain and had no real branching logic in it so it could easily be abstracted to a helper class that would assist in creating the container and returning the instance to the caller.
The flexibility that you can gain by moving to a IOC framework such as Unity is very impressive. Overall I think this will be beneficial to use as a more robust way to enable dependency injection.
Next time I will cover a more real world example using Unity in the adapter pattern we use for our WCF service clients. The basic model is that our service client calls the service and then initializes an instance of a "IMessageAdapter" and calls its Transform method. The purpose of the adapter is to take the data in the services format and transform or adapt it to something else like a database, fixed length file, etc. We use this model because it allows us to fully reuse the client and only requires that we create a new implementation of the Interface.
Good Conversation, Good Practices, and People to Learn From
Dec 15th
I like finding people who have stumbled upon the same best practices I have. It makes me feel less lonely in the universe. Friday night before the St Louis Day of .NET I was able to attend the speakers dinner at Granite City Food and Brewery in Creve Coeur (great food by the way, Mediterranean Chicken was a good choice for a late dinner). At my table was Jim Chandler (speaker), Eric Brown (speaker), Jeff Fattic (Organizer & Speaker), Michelle Marcus (one of Jeff’s minions), and JD Wade (Speaker), .
As the evening moved on we started discussing work related things. The big topics were unit testing, source control, process, and good design.
On Source Control – I was amazed to hear that there are companies, big ones, who do not use this. I don’t think we use the best source control available at REJIS but we use it and it has saved us many times. The potential for damage is huge when that source code is what drives your businesses systems; you definitely want that stored somewhere safe. Yes someone can always mess with things in source control but that is why rollback was invented. If you don’t have it or aren’t using it, get source control. There are free, open source ones and ones you can pay for. Get one, use it, and follow best practices for using your particular source control software. And don’t forget to back it up regularly…
On Process – This one ties in with design (below) and source control. As Jeff Fattic put it, "no process is bad process". Everyone has a process even if it is bad. The key is finding a process that works for your team and using it. Having a bad process is not going to guarantee results. A good process gives you a much better chance of guaranteed results. You don’t have to pick an off-the-shelf process such as agile or any of it’s derivatives. Process should be the steps you go through to identify, document, design, construct, and maintain a system. In my opinion this should be something that is iterative and can handle change. Waterfall (big design up front) worked a few times in the 70s but it doesn’t now so rule that one out (the whole table agreed on this point).
On Good Design – The big joke that I wanted to use in my Oslo speech was asking if anyone who used UML had ever looked at what was finally developed to see if the UML and the system were in sync. No one in my morning session used UML. Only two in my afternoon did and they laughed at my joke.
I was an artist back in high school, before I got heavily into coding. When I started coding it was like art to me except I made the computer do something. I wrote neat programs and systems with not much aforethought and no drawings or diagrams. I had no training in software development, I just coded. It turns out that this is the majority of developers today. Developers just code; design is what someone else who has more time does.
I have seen the effects of insufficient design. I did not like those effects. I made it my quest to find out how to design good systems, what tools to use, and when to start. I argued with people about it and eventually demonstrated how good designs, good architecture, would save a lot of headaches later. It is not easy to keep UML diagrams that are not directly updated by changing code up-to-date. Designing extensible, maintainable, and scalable systems isn’t easy either but the up front work always pays off. Even if you just design systems on a whiteboard at least take a picture of it so you have something. If you want more on the subject read Steve McConnell’s Code Complete Second Edition.
On Unit Testing – Before Visual Studio 2008 I did not unit test. I had heard of things like NMock and other test frameworks but did not understand why it was necessary and it seemed like extra work. My tune changed quickly after I dove into what unit testing was about and I realized how much it would save me later. I am one of a few who actually use Unit Test projects in VS 2008 at REJIS. Everyone does functional tests and "screen" testing but not necessarily unit testing at the class level which is where mots of the problems happen.
Unit testing matters and good unit testing makes all the difference. I don’t think I write great unit tests but the ones I do write have saved me and have saved other developers from mistakes that would have went into production. Recently I found a unit test that was not sufficient and we had to correct something that was out in production. Mistakes happen. Unit testing minimizes those.
Eric asked a good question: If you have a class that mimics a basic calculator with four methods: add, subtract, multiply, and delete, how many tests should you write at a minimum? I think, after our discussion, the answer is at least 8. One to show how each method works and one to show how each can be broken. A good example for a "break it" test for the add method: Integer.MaxValue + 1 (Kudos to Jeff, he thought this one up). What should happen there? Now think about your own classes, don’t just test to make them work, test to make them break because sometimes those tests can be just as revealing.
Having dinner with such a group is great. It reminds me that I am not alone and that my opinions are well-founded. I don’t make a habit to constantly hang out with people who have the exact same opinions as me. I would never learn that way. When it comes to best practices I don’t think its bad to surround yourself with people who share the same views. Best practices are just that; things that you should be doing because they are proven to be successful and will give you a competitive edge. Here’s a few things you can do to get started:
- Even if you aren’t aspiring to be an architect study good architecture. Good architects need good developers who will stick to the architecture and make the system work within its defined boundaries. There are reasons for those boundaries and a good developer should understand those too.
- Learn the different source control systems and discover how they can compliment or affect your development process. Discuss them with your team.
- Have a good process that works for your team. It doesn’t have to be agile or scrum but do look at standard processes and take the parts that fit your culture.
- Test your code. You are not perfect and no one expects you to be. If you correct a huge problem before it is a problem you look much better than you look when you are trying to explain how that error wasn’t caught and is now costing your company or customers money. Trust me, I have been on both sides of this.
Here are some local personalities that have some things to say on best practices and keep their blogs flowing:
Jeff Fattic
Muljadi Budiman
JD Wade
Clint Edmonson
Denny Boynton
The Power of Naming
Dec 9th
Today I was walking down to the lunchroom to get some Christmas cake with one of my teammates and he was telling me about these services he wants to create for the application he is now project lead for. On the way up he said "Ok so you know how important names are so how about these…" and proceeded to name his services. The names sounded good but I starting thinking about one of them. He had called it the "ParcelUploadService". After a minute I said "You know, upload is real ‘computery’, how about ParcelStorageService?" His eyes got wide and he had that same look he gets when he talks about Silverlight and then he said "Oh I like that. I’m changing the name."
Later on we were talking and I said, "If you think about it, I don’t upload files to my file cabinet, I store them. So I think storage service is pretty good."
"That sounds like a blog post to me."
Here it is Dave. Now go start your blog I can link to it.
My Software Development Meme
Sep 8th
I saw this meme floating around the development community and thought it was a fun one. Clint Edmonson has called me on it so I’m going to give it a shot.
How old were you when you started programming?
My first experience with programming was on the Atari XE. I was around 8 or 9 when my dad and I went through the manual and followed the line by line instructions to build a program that displayed an American flag waving in the wind. I learned a lot about the Basic language and it kind of stuck with me. I didn’t do much programming after that unless you count the magic of format C: in Dos 6. Most of my computer experience during my teens was on the fix broken ones side.
What languages have you used since you started programming?
I haven’t strayed far from languages who have a lineage with basic. In college I started as a Computer Science major but I did not like the prospect of intensive math. I was exposed to C++ there which I enjoyed but was looking at switching to Management Information Systems. If you’ve read my bio then you’ll know during those college years I had a battle with cancer a few times that took me on some interesting paths. When it all settled I went back for my MIS degree where I spent time with VB 6, VB.NET, and SQL. I’ve also touched on PHP, Java Script, and even Java (which I now respect a lot more than I did a few years back).
What was your first professional programming gig?
My first gig probably isn’t as interesting as the path that got me there. When I worked for Lewis & Clark Library System I started as a PC technician. Most of my IT background through college was working for Internet providers and a few LAN gaming centers. At LCLS they had a lot of IT needs and I had a lot of jobs I could do. I bounced from a traveling PC tech to a server admin, security guy, and also the web master. After getting through my battle with cancer I had an opportunity to choose a path. We wanted to make our web site dynamic so I dove right in and started with ASP (we had Microsoft servers) and MS Access database on the back end. From there my journey into development really took off. I became the full time web master and eventually changed the title to Internet Application Developer.
If you knew then what you know now, would you have started programming?
I would have started sooner and studied more languages. I’ve been pretty vertical in my language market and would have liked to have been more multilingual. I would have also studied object oriented a lot more thoroughly to fully understand the concepts that drive it.
If there is one thing you learned along the way that you would tell new developers, what would it be?
Study development outside the context of a language if possible. I have been struggling to unhinge myself from language centric development into the broader realm of software design outside of a specific language. This is difficult to do when you’re grounded in a language.
What’s the most fun you’ve ever had … programming?
Those first experiences where you spend minutes or hours typing away and then tell the program to run and watch it work are the best. Once you get past that programming is still a lot of fun but the challenges change and so do the motivations. That feeling of watching it work is always there and I think that is the big draw for me. Programming is a lot like art. Prior to my development life I spent a lot of time writing and drawing. I don’t do as much of that with pen and paper, but I’d like to think of my development as an art form and it’s satisfying to see your work out in the field helping people do their job.
Who am I Calling Out?
The people I want to call out do not blog (that I know of). Which is too bad. I don’t want to end this meme but sadly I have to for now.


