Skip to main content

Posts

Showing posts with the label coding stories

Coding Stories - Properties with private getter

Today I had an interesting discussion with a colleague from another company. We started to talk about C# properties and how useful are in situations when you need to set or get the values of different object characteristics. Properties are perfect when you work with DTO - Data Transfers Object. For this case you don't need to have any kind of logic inside. Properties can be defined very simple: public class Foo { public string Name { get; set; } } Simple, I bet that you already knew this. When we went with discussion deeper, we talk about cases when you need to expose only the getter public and setter needs to be private. This can be useful when the value needs to be set only in ctor (constructor) or internally, during deserialization. public class Foo { public string Name { public get; private set; } } Good! Until now nothing special. But what about cases when the setter needs to be public and getter is...

Coding Stories - string.Format and enum as const

Looking over some code this days I found the fallowing things. 1. Odd way of using string.Format The fallowing code is extracted from an application: Trace.WriteLine(string.Format("{0}{1}{2}{3}{4}{5}{6}", "Generating ", count, " strings of size ", stringSize, " took ", duration, " milliseconds.")); Trace.WriteLine(string.Format("{0}{1}{2}", "Only ", strings.Count, " strings were generated due to uniqueness constraint.")); As we can see, ‘string.Format’ is overused. The code is not only hard to read and maintain, but the arguments are used everywhere, even when part of the string are constant. Even the spaces around words are fully missing from the format. The above code should look something like this: Trace.WriteLine(string.Format("Generation {0} strings of size {1} tool {2} milliseconds.", count, stringSize, duration)); T...