in

 

Colin Ramsay

  • Your Development Environment

    When I first started working in "the real world", I had a development environment which I'd describe as typical: average Dell computer and peripherals, one monitor, Windows XP with all my applications installed, including VS2003 and VS2005. I'm sure

    Last year, when I struck out on my own to start Plastiscenic, I knew I needed an upgrade. For starters, my XP install was grinding to a halt. But I was also concerned about the way all of my interests were intermingling - games, hobby stuff and professional stuff all on the same installation. That felt pretty bad to me, not least because Windows XP gets very sluggish after a few months with lots of programs installed.

    I purchased an Intel Q6600 with 4Gb of RAM, and a 10k RPM boot drive. That was stage one. I set up two monitors on a bigger desk with a lamp on it to reduce any strain on my eyes. I installed Vista 64 Business Edition, which I felt was a better match for the hardware than XP. The core setup was there, but there was still a key component missing.

    VMWare provided the answer. By creating a stripped down Windows XP installation I had a fast virtual machine to install development software on. I had another VM for SQL Server. These trim virtual machines could be backed up with ease, and moved offsite if need be. If my main machine died, I only had to reinstall a basic environment and VMWare Player to become productive again.

    In a larger team of developers, such virtualisation software provides even more options. An administrator could provide base images which can be served across a network, giving developers tailored environments within a few clicks. This is good for testing too - prepare images for a multitude of operating systems for pre-production testing of a desktop application.

    I believe virtualisation will become even more popular over the next few years, giving us more opportunities to create sandboxed environments which can be run at the click of the mouse. 

  • Design Dithering

    When you break out of the "new programmer" mindset and begin thinking in terms of organisation, patterns, and good design, I think there's a real danger of hitting a development wall. What actually is the correct way of implementing a shopping cart? Should you use a three or four tier application design? My outlook on this is pretty simple:

    It doesn't matter.

    The Domain Driven Design book teaches a lot of interesting stuff, some of which can contribute to a brain freeze. So many new concepts can mean that there are a lot of possible avenues of approach for any given problem. But in my eyes, one of the most valuable lessons that Eric Evans gives in that book is that refactoring is key. If I find myself struggling to adapt the right approach, I take the simplest route, safe in the knowledge that if I've done it wrong, my application will let me know, big time. If I'm following a loosely coupled design, no single refactoring should have a huge impact on the rest of the application.

    So if you find that you're struggling for a solution, take the simplest, quickest - even do a dirty hack! - and know that next week, if that decision comes back to bite you, you can just refactor it out.

  • Javascript Patterns & Practices

    My previous post on Javascript gave an insight into using the language in a more structured manner than you may have been used to in the past. I'm going to talk about a few more methods which I use a lot, and that help me keep my JS workable.

    Pattern

    Last time, I talked about the Object Literal pattern. If it helps, you can think about this as if it were a C# static class; you don't need to instantiate it, it can have state, but it is application-wide. I will typically use Object Literal as a kind of "manager", which controls what happens on a page, from a function which fires onload, to functions which get triggered on button clicks. 

    In other places, such as complex user interfaces, I will typically need "components", which wrap up a lot of functionality and may be used multiple times within a page. An example of this might be a date picker control. For these components, I need to hold state, and so I need the equivalent of a standard C# class.

    function DatePicker(date) {

    if(date) {
    this.initial = date;
    } else {
    this.initial = new Date();
    }

    this.show = function(date) {
    alert(this.initial);
    }
    }

    var startDatePicker = new DatePicker();
    var endDatePicker = new DatePicker(new Date('Jan 1, 2009'));

    startDatePicker.show();
    endDatePicker.show();

    In this example, startDatePicker gets instantiated with a default date, but endDatePicker gets a different date passed in its "constructor". You can see that both objects retain their own state when the show() functions get called and different dates are alerted.

    Practise

    You can do faux-namespaces in Javascript as well as faux-classes. I use them to package up related code and partition it, much as you might do with namespacing in other languages. There are a number of different ways of providing this functionality, and here's one which is incredibly simple:
    var NAMESPACE = {};
    NAMESPACE.utils = {};
    NAMESPACE.interface = {}; // other namespaces

    NAMESPACE.utils.fixIE = function() {
    // code
    }

    NAMESPACE.utils.fixIE();

    Other ways of organising your javascript code can be pulled directly from C# best-practises, such as one-class- per-file. Another beneficial approach is to avoid embedding your javascript code in your HTML. Code like this:

    <a href="/javascriptrequired.aspx" id="showPicker" onclick="showDatePicker();">Pick Date</a>

    Can often be easier to maintain when written "unobtrusively", with the following in a linked JS file:

    var document.getElementById('showPicker').onclick = showDatePicker;

    And now this in your HTML:

    <a href="/javascriptrequired.aspx" id="showPicker" &gtPick Date</a>

    This keeps your javascript confined to .js files and out of the HTML, which is generally a cleaner approach.

    Further Reading

    You can continue to develop well by unit testing your javascript and documenting it fully. You can also check it for errors and then compress it for deployment. Javascript is an important tool in your arsenal; use it well!

  • You Have Nothing To Fear From Javascript

    Building a web application consists of a number of discrete layers: server code, client code, HTML, and styling. If you cannot sit down with one of those layers and work on it, you are not fulfilling your role. If I hire a web developer, I don't expect them to tell me that they know little of Javascript, but unfortunately there seems to be a fear of that language, where people are happy to hide it away behind a facade of server-side code which autogenerates it.

    This is wrong. If you are working with Javascript, client side code, then you should be able to fully debug, understand, and tweak that code natively. Changing some C# code which you think will generate the right JS is such a horrific approach I can't believe anyone would advocate it. In order to have a robust application you need full control of all aspect, from top to bottom.

    Besides, Javascript is actually a great language, though much maligned over the years. As the web matured, Javascript was often responsible for scrolling banners, page errors, and other affronts to the user. But as people have documented its browser support and language tricks, Javascript has matured with its environment. Check out this structure in BLOCKED SCRIPT

    // Setup "static" structure
    var Application = function() {

    var _privateVar = 0;


    return {

    someFunction : function() {
    _privateVar = 5;

    }

    }
    }
    }();

    // Run the function
    Application.someFunction();

    Organised, readable Javascript! Whatever next! You can even have psuedo-namespaces, classes, anonymous functions, loads of great dynamic language features which allow you to come up with flexible and concise code. Generating your JS isn't just unwise, it means you're missing out on all the fun!

  • Working with Interfaces Part Three - Windsor

    Castle Windsor is an Inversion of Control container which uses interfaces as a key concept. When working in the manner I described in my previous articles on interfaces, you get a decoupled application but may end up with a lot of "wiring-up" - instantiating interface implementations then passing them into your classes.

    For example, a Controller may often demand an implementation of ILogger, IAuthenticationService, IRepository and IPaymentGateway, which would require a fair bit of code to wire up. Windsor removes the wire up burden from the developer. Using XML configuration, you can easily swap out one implementation for another:

    public interface ISport{}
    public class Football : ISport{}

    <component id="default.sport"
    service="ISport, WindsorTest"
    type="Football, WindsorTest"/>

    In this example, we use the component element to wire up the Football implementation for any usage of ISport. For Windsor to provide this ISport implementation to your consuming classes, the consumer needs to be in the container too:

    public class Consumer
    {
    // Parameter injection
    public ISport Sport{ get; set; }
    // Constructor injection
    public Consumer(ISport sport){}
    }

    <component id="some.consumer" type="Consumer, WindsorTest"/>

    So now Consumer will have the configured ISport passed to its constructor or the Sport parameter, depending on your preference. We could also have an ISport parameter on Consumer and Windsor would be able to set it with the configured implementation of ISport.

    Using a system like Windsor is a logical extension of the practises I've talked about before. It gives you the flexibility of interfaces without the burden of having to manually instantiate and pass through all of the implementations your classes may depend upon. When thinking about Domain Driven Design, you can use Windsor to provide Services to your application, allowing it to consume independent components and create one awesome whole. Full Windsor documentation can be found on the Castle website, and I've also written about Windsor on my personal blog.

  • Working with Interfaces Part Two - Decoupling

    In the first part of this mini-series I talked about the basic use of interfaces, which is to provide a contract for your developers to work to. In this part, I'm going to try and demonstrate how interfaces can be used to make your application more flexible. This is probably the most common type of tutorial on interfaces you'll see around the web, so forgive me for adding another.

    Here's an example of traditional style development, without interfaces:

    public class YoGenerator
    {
    	public string Generate()
    	{
    		return "yo!";
    	}
    }
    
    public class Greeter
    {
    	public void SaySomething()
    	{
    		YoGenerator yoGenerator = new YoGenerator();
    		
    		Console.WriteLine(yoGenerator.Generate());
    	}
    }
    
    public class Program
    {
    	public static void Main()
    	{
    		new Greeter().SaySomething();
    	}
    }

    So we've got a program that creates a new Greeter class and calls the SaySomething method on it. The Greeter class in turn calls a YoGenerator's Generate method to output "yo!" to the console. This should all be fairly straightforward so far and if not, well, you've got bigger worries than what an interface is for.

    So, the first step on making this a more useful application (I say that in the loosest terms, I'm not sure how much mileage you can get out of an app that says "yo!") is to refactor by extracting an interface from the YoGenerator class and make YoGenerator inherit it:

    public interface IGreetingGenerator
    {
    	string Generate();
    }
    
    public class YoGenerator : IGreetingGenerator
    {
    	public string Generate()
    	{
    		return "yo!";
    	}
    }

    In terms of what our app now does, nothing has changed. It still outputs "yo!" to the console and it still does it using the same mechanism. However, we can now make an additional change which opens up more options:

    public class Greeter
    {
    	public void SaySomething(IGreetingGenerator greetingGenerator)
    	{
    		Console.WriteLine(greetingGenerator.Generate());
    	}
    }
    

    That's a fairly big jump if you're not familiar with interfaces. We're saying that SaySomething now takes one parameter - an instance of a class which implements IGreetingGenerator. That's an important piece of information, because while you can't directly create a new instance of IGreetingGenerator, you can pass implementing classes round in this way. And because IGreetingGenerator defines a method Generate, we're able to call that on the instance we're passing in. The final piece of the puzzle involves supplying SaySomething with an instance of a class that implements IGreetingGenerator. And remember how we changed YoGenerator to implement IGreetingGenerator...?

    public class Program
    {
    	public static void Main()
    	{
    		new Greeter().SaySomething(new YoGenerator());
    	}
    }

    So we instantiate a new YoGenerator which is also typeof IGreetingGenerator, and pass that to SaySomething. In the process, we've extracted SaySomething's dependancy on YoGenerator... What does that mean for us? Well it means we can pass in new greeting generators to affect the behaviour of SaySomething, without actually having to change SaySomething's code:

    public class DrunkenGreetingGenerator : IGreetingGenerator
    {
    	public string Generate()
    	{
    		return "i lovzshh u mannn!!?!";
    	}
    }
    
    public class Program
    {
    	public static void Main()
    	{
    		new Greeter().SaySomething(new DrunkenGreetingGenerator());
    	}
    }

    With a bit of forward thinking we can make the Greeter class work independently of other classes - we've decoupled it from YoGenerator and given it freedom to work with any class that implements IGreetingGenerator.

  • Why ALT.NET?

    DISCLAIMER: This post was inspired by, and contains material from, a recent post on my personal blog entitled "Abandon ALT.NET".

    For a few months the term "ALT.NET" has been gaining traction on the blogs I read, starting from a post by David Laribee in April. From there it has taken off, with an ALT.NET Conference taking place this week. So it’s perhaps timely that Sam Gentile has written a post entitled "Goodbye CodeBetter and ALT.NET" which talks about the ALT.NET movement and some of the people surrounding it.

    I honestly don't get the point of ALT.NET. While I use and appreciate a lot of the technologies and ideas which they're pushing, I don't see the value in wrapping it with a new moniker. This very act is one of segregation, because it pigeonholes people and technologies away from everything else. As Sam says, "ALT.NET is a divisive thing. No matter what they tell you." Maybe this is a P.R. problem and maybe not. But perception is everything; not your perception but how other people perceive you.

    One of the numerous sources of that negative perception is the frequent use of the term "Mort" by ALT.NET bloggers. I strongly dislike this term, I mean come on, the damn thing is short for "mortal". That's a pretty clear proclaimation that the people who aren't "Morts" must be something more: not mere mortals, but Gods of their domain. Overseers of the lower developers who haven’t had the resources, or the guidance, to work with the fantastic array of non-Microsoft technologies that exist.

    You're not going to address that imbalance by putting all of the people that already subscribe to your notions in one place. I mean, think about it, DDD, BDD, MVC are things which will be known, in some form or another, to the majority of the ALT.NET Conference attendees.

    ALT.NETter A: so… heard of that new BDD business?
    ALT.NETter B: Yep.
    ALT.NETter A: Oh, well there’s this great new idea called DDD!
    ALT.NETter B: Yeah, right into that too.
    ALT.NETter A: Oh.

    And so on. But wouldn’t that conversation have been a whole lot more interesting if the second developer hadn’t heard of those ideas? Wouldn't it make more sense to talk to the people who are really in need of your ideas and your tools and your knowledge?

    A lot of people in the ALT.NET camp may not feel that they’re being divisive but really, by propagating this idea you’re creating a line in the sand, with the highly-knowledgable on one side and the masses on the other. You’re not encouraging dissemination of your information, you’re just creating another impenetrable gang of developers that is almost opaque to the guy on the ground.

    The solution? Not to rename or rebrand, or even sharpen your mission statement. Instead break away from ALT.NET, walk among those mortals and share more of your knowledge through the normal channels. It's not as glamorous, but it will be a lot healthier in the long run.

  • Working with Interfaces Part One - Contracts

    I hold my hands up - I am a programmer who doesn't have a computer science background. My education only skimmed programming and was totally bereft of any architectural considerations. I almost stumbled into my first programming job, and I such I realise I have a lot of to learn about that which I use to earn a crust.

    One of the things that took me a while to appreciate was the power of interfaces. I specifically remember a conversation I had with my boss in which I said, baffled, "so... they don't actually *do* anything then??". And this is kind of true, interfaces don't really "do" anything. Instead, they're an enabler for a couple of really useful techniques.

    Imagine you're creating a series of sub forms in a Windows application. They're each supposed to do a similar thing and should always have methods to LoadSettings and SaveSettings. Something like this:

    public class NamePrefs : Form
    {
    	public void LoadSettings(){}
    	public void SaveSettings(){}
    }

    However, a new developer jumps in to your project and is instructed to create a new preferences form. They come up with something like this:

    public class HeightPrefs : Form
    {
    	public void ExportConfigData(){}
    }

    For starters they've forgotten that the form needs to load up existing data and so hasn't implemented loading functionality. Secondly, they've called their save method something different to the save method in all your other preference forms. Interfaces can provide a possible solution:

    public interface IPreferencesForm
    {
    	void LoadSettings;
    	void SaveSettings;
    }

    This interface is specifying a contract which implementing classes can adhere. Our initial example would look like:

    public class NamePrefs : Form, IPreferencesForm
    {
    	....
    }

    If our second example also inherited from IPreferencesForm, that implementation would throw compiler errors as neither the LoadSettings or SaveSettings methods specified in the interface contract are present in the HeightPrefs class.

    Using interfaces only solves one part of the problem - you've got to make sure that people do actually inherit from them. That's an issue which can be solved by enforcing developer policies, or technically, by ensuring only classes which implement the correct interface will get loaded by your main program. However, when interfaces are used in this manner, they can improve consistancy and lead to improved discoverability in your code.

    Posted Oct 01 2007, 11:15 PM by cramsay with 5 comment(s)
    Filed under:
  • Coding C# in Style

    I admit it; I've got problems. I get itchy when my code isn't arranged in the right order, I get the shakes when I open a file and see code sprawling all over the place, I get nervous when my fields aren't prefixed with an underscore. So I work to my own personal style, strictly adhering to some key guidelines.

    Private Fields Are Underscored

    This helps me tell at a glance whether the variable I'm assigning to is class-level or method level. It provides a little bit of context and a reminder of where a variable belongs in a class - is a throwaway variable or could other methods be working with it?

    Tabs, Not Spaces

    This is probably the subject of a thousand flame-wars on forums and mailing lists across the internet, but I opt for tabs. I also work with Visual Studio's "View White Space" option switched on so I can check for excess tabs and line breaks more easily. I told you I had a problem.

    Regions Are Your Friend

    When I open a class file, I've usually got a purpose in mind, and seeing reams of code is a surefire way to make me dismay. On the other hand, opening a file which is organised using regions means I can quickly focus on the area I want to act upon. It also allows me to collapse the code I've been investigating back to an "overview" state using Visual Studio's CTRL+M, CTRL+O shortcut.

    Save Me, Resharper

    As with most Visual Studio operations, Resharper is there to help. In this case, JetBrains provided a great new feature for R#3 - the Type Members Layout options. By supplying an XML layout, you can tell R# to reorganise your code into a specific order within specific regions. I've uploaded my current Layout XML, which will reorganise your code in my style - fields, properties, constructors then methods - all within their own region. If only JetBrains could come up with something to enforce naming conventions and other coding styles!

    Conclusion

    I've heard people a number of times that it's better to enforce any coding style, even if your team doesn't agree with some aspects, than to not enforce anything at all. I totally agree with this statement - from C# to Javascript to CSS and SQL, if you make sure your developers work to a single standard you can be sure they can jump into a file and not be terrified. Ok, not be really terrified anyway. Let me know about the guidelines your company enforces and which tools, if any, you use to do so!

Copyright Los Techies 2007. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems