Everyone should know what I mean by Magic Numbers. Those no named numbers in code that live just to make you scratch your head and scream. I know I’ve come to despise seeing numbers without a variable name.
In XAML (and other interface languages) it seems to be easy to forget those simple rules for naming our values and to justify just why you set the margin to 4 vs 7 (Jing’s standard margin is 7). It’s this reason that I took some time to see how we could improve the readability of numbers in XAML.
Example XAML:
In Jing we try to stick with 3 different standard margins: 4, 7, and 14. We tend to use 7 the most and when we want to pack the most in small spaces we will use 4. Of course though we may want to change these in the future date to 5, 8, 15, and will have to dig through all our XAML and change them manually. Unfortunately not all of Jing’s XAML code has theses standards in place and you can find some elements with 15, 5, and other numbers for margins, because it “looks ok”. But as a WPF developer, stumbling on these numbers just make me think how random they are, and if they were meant to be those strange numbers I would not know and think they were set before the standards.
Alternatively I found we can refactor our XAML in the following way (and yes I said refactor UI)
4 7 14 <button></button> <button> Â Â Â Â Â Â Â Â </button>
It may be quite a few more lines than before, but I think it is better in two ways. The first is if we move the resources into App.xaml we can get access to the resources from any control inside the app, this makes it very easy for us to change these numbers at any time. The second is, in order to use Resources we have to change to the long form of defining margins, adding more lines of code but making it easier to understand. No longer do you have to remember the format combinations of Margin=”Left,Top,Right,Bottom”, but define them by name.
So just because it may not seem to be code because you may use the mouse to drag around boxes to make it visual, by using the same standards we hold on our logic code we can make UI easily manageable and understandable.
Mark Schall started at TechSmith as an intern during his first summer of graduate school and decided to continue working as a full-time employee while he finished his Masters of Computer Science degree at Michigan State University. He originally started out working on Jing and is now contributing to Camtasia Relay. He has been developing with WPF, Cocoa, MFC, and DirectShow at TechSmith. Mark enjoys spending his free time with his wife Julia and two dogs, Bella and Dolly.
The post Dev Corner – Magic Numbers In Designing appeared first on TechSmith Blogs.