…meie igapäevast IT’d anna meile igapäev…

2014-02-19

Bright sayings of bright people: programming quotes

Filed under: Programmeerimine — Sander @ 13:56:40
Tags: ,

While the last post had my own sayings, this one has some of my favorite programming quotes from others. Even the first part of the title is from the late Frederik Pohl.

  1. "Don’t just echo the code with comments – make every comment count."
  2. "Make sure comments and code agree."
  3. "Don’t comment bad code – rewrite it."
    "The Elements of Programming Style" by Kernighan and Plauger, 1974
  • "It’s important to communicate what the code should be doing.” – Joe Kunk
  • “It’s hard enough to find an error in your code when you’re looking for it; it’s even harder when you’ve assumed your code is error-free.” - Steve McConnell
  • “If debugging is the process of removing software bugs, then programming must be the process of putting them in. ” – Edsger Dijkstra
  • “Walking on water and developing software from a specification are easy if both are frozen.” - Edward V. Berard
  • “First, solve the problem. Then, write the code.” - John Johnson
  • “Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration.” - Stan Kelly-Bootle
  • “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” – unknown (attributed to John F. Woods, Rick Osborne, Martin Golding)
  • “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler
  • “Programs must be written for people to read, and only incidentally for machines to execute.” – Abelson/Sussman
  • “Computers are good at following instructions, but not at reading your mind. ” – Donald Knuth
  • “Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” – Rick Cook, The Wizardry Compiled
  • „Do unto the next developer as you would have them do unto you“ – Joe Kunk

2014-02-14

Quotes on programming

Filed under: Isiklikud,Programmeerimine — Sander @ 14:47:21
Tags: ,
  • There is nothing worse than a programmer who compiles the spec into the code, without asking “could the workflow be better?”, “could this be a bug in spec?” or even “does this make any sense whatsoever?”

  • Bad programmers tend to gravitate towards management. Too often they will become mediocre project managers, then bad department managers and finally horrible CTOs.

  • (on Robert Martin’s “Clean Code”) “Clean Code” doesn’t tell you how to write good code, nor maintainable code. Instead, it teaches you to write consultant code, or “cuckoo code”: you drop a nice shiny egg into the nest and fly away, leaving others to maintain the ugly monster that hatches.

  • Every programmer writes bad code sometimes. But when you have to ask "doesn’t he know better or is he trying to sabotage the project?", you’ve found a truly horrible coder.

  • If you are looking at your own code from two years ago and it looks fine, it doesn’t mean you were a good programmer two years ago. Quite the opposite, it means you haven’t grown as a programmer within these two years. You haven’t learned anything.

  • Code review is like a pair of pants. If you work at home, pants are optional. But if you are in public, you’d better make sure you have pants on, even if no one looks at you.

  • Too often the only reason teams use agile programming is to be able to say that they are using agile programming.

  • But what is there to love about the code? It is the same excitement that a poet gets from writing a poem, or a painter from painting. It is the act of creation, the “develop” part of the word “developer”. We write some lines of text, which abides to the certain rules, and suddenly ex nihilo! we have a website, a video player, a database engine or something else.

  • The point where I’m getting to is that you can be eager and write more code. Or you can be lazy and figure out a way to write less code. Being lazy is a good thing in a programmer. It forces us to find patterns and promotes code reuse. It makes us more effective. It makes us better.

  • A programmer should be smarter than his tools. Don’t expect the compiler to fix your bad code.

  • If the comment does not match the code, it is the comment that is correct and code that is wrong.

***

I’ll post these mostly so I would remember them and re-use when appropriate.

I think these quotes are mine, from various blog posts, presentations and discussions. If I have inadvertently picked up or rephrased someone else’s text, please let me know in the comments.

2013-09-26

T4 templates for Web.config/App.config AppSettings

Filed under: Programmeerimine — Sander @ 11:37:47
Tags: , , ,

I’ve written before about generic methods to access configuration values. As nice as such generics are, there is still one major issue – you’ll still have to use strings as configuration value keys. Which means there is a possibility to get an invalid key name by accident – or even worse, wrong value from the configuration. Such problems will often come out only after the project has been shipped.

One – and preferred – solution is to use Settings instead of AppSettings. These are strongly typed and can be accessed via keys (Properties.Settings.Default.SomeNiceSetting) – while the values are still in the configuration file (section <applicationSettings>).

Unfortunately, we cannot always use Settings, for several reasons.

So, I got fed up by having to memorize or copy the keys, do casting and so forth – and decided to figure out some better way to get the AppSettings values. After some other ideas, I ended up with two T4 templates.

First approach: string fields

 

  1. <#@ template debug="false" hostspecific="true" language="C#" #>
  2. <#@ assembly name="System.Configuration" #>
  3. <#@ assembly name="System.Core" #>
  4. <#@ import namespace="System.Configuration" #>
  5. <#@ import namespace="System.Linq" #>
  6. using System.Configuration;
  7.  
  8. namespace <your-namespace-here>
  9. {
  10.     public static class AppSettings {
  11.       <#
  12.     var configurationFileMap = new ExeConfigurationFileMap();
  13.     configurationFileMap.ExeConfigFilename = this.Host.ResolvePath("Web.config");
  14.     var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);
  15.     foreach(string key in configuration.AppSettings.Settings.AllKeys.Where(x => !x.Contains(":")))
  16.     { #>
  17.         public static readonly string <#= key #> = ConfigurationManager.AppSettings["<#= key #>"];
  18.     <#} #>
  19.     }
  20. }

This is my first approach – generate a static AppSettings class, which has readonly static string fields for all the AppSetting keys (note the !x.Contains(“!”) bit – that is to avoid the ASP.NET MVC keys).

This has both benefits and disadvantages over the second template – namely, you’ll get string values and will have to convert them to the required data type yourself. When someone messes up configuration (i.e. instead of “40” types in “4O” then obviously the cast to integer will fail), you have the option to fail gracefully – fall back to default value or such.

You can also combine this approach with generic methods linked above – i.e. use the t4 template to create constant strings for keys and send the now-hardcoded keys to generic method for appropriate handling.

Second approach: strongly typed properties

  1. <#@ template debug="false" hostspecific="true" language="C#" #>
  2. <#@ assembly name="System.Configuration" #>
  3. <#@ assembly name="System.Core" #>
  4. <#@ import namespace="System.Configuration" #>
  5. <#@ import namespace="System.Linq" #>
  6. <#@ import namespace="System.Globalization" #>
  7. using System.Configuration;
  8.  
  9. namespace <your-namespace-here>
  10. {
  11.     public static class AppSettings {
  12. <#
  13.     var configurationFileMap = new ExeConfigurationFileMap();
  14.     configurationFileMap.ExeConfigFilename = this.Host.ResolvePath("Web.config");
  15.     var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);
  16.     foreach(KeyValueConfigurationElement setting in configuration.AppSettings.Settings)
  17.     {
  18.         if (setting.Key.Contains(":")) //these are ASP.NET MVC keys
  19.             continue;
  20.  
  21.         string settingType;
  22.         int i; bool b; decimal d;
  23.         if (int.TryParse(setting.Value, out i))
  24.             settingType = "int";
  25.         else if (bool.TryParse(setting.Value, out b))
  26.             settingType = "bool";
  27.         else if (decimal.TryParse(setting.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
  28.             settingType = "decimal";
  29.         else { #>
  30.         public static string <#= setting.Key #> { get { return ConfigurationManager.AppSettings["<#= setting.Key #>"]; }}
  31. <# continue; } #>
  32.         public static <#= settingType #> <#= setting.Key #> { get { return <#= settingType #>.Parse(ConfigurationManager.AppSettings["<#= setting.Key #>"]); }}
  33. <# } #>
  34.     }
  35. }

Second approach tries to guess the appsetting type by trying to cast the value into several common types (int, boolean and decimal in the code above) and create the AppSettings class property in an already correct type.

This could be improved in several ways – for example, use TryParse() in non-string properties, use IConvertible and so forth. You probably need add your own types, too.

As an example, here is my test <appSettings>:

  1. <appSettings>
  2.     <add key="TestDecimal" value="6.02214129" />
  3.     <add key="TestBoolean" value="True" />
  4.     <add key="TestInt" value="420" />
  5.     <add key="TestString" value="Alea jacta est" />        
  6. </appSettings>

and output from the template:

public static class AppSettings {
    public static decimal TestDecimal { get { return decimal.Parse(ConfigurationManager.AppSettings["TestDecimal"]); }}
    public static bool TestBoolean { get { return bool.Parse(ConfigurationManager.AppSettings["TestBoolean"]); }}
    public static int TestInt { get { return int.Parse(ConfigurationManager.AppSettings["TestInt"]); }}
    public static string TestString { get { return ConfigurationManager.AppSettings["TestString"]; }}
}

You’ll have to add the AppSettings.tt template to the root folder of your application – or modify the this.Host.ResolvePath("Web.config") accordingly.

One thing that you have to note is that the configuration XML keys can have symbols that are not allowed in C# field/property names, such as the aforementioned colons in ASP.NET MVC keys. Best approach is probably to remove such symbols from field names, but not from the key names in return statements, as latter can handle just fine code such as ConfigurationManager.AppSettings["I:Really:Suck:At:Naming!"].

Another problem is that I was unable to get the template generation to auto-run when the Web.config changes. I tried to follow an old answer from Stack Overflow, but no dice. If you have any ideas/suggestions about this or other possible improvements, please post them to the comments – meanwhile you’ll just need to right-click on AppSettings.tt in Visual Studio and choose “Run custom tool” (if that option is missing, set in AppSettings.tt file properties “Custom Tool” to “TextTemplatingFileGenerator”).

Järgmine lehekülg »

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 68 other followers