<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TheSegmentationFault</title>
	<atom:link href="http://thesegmentationfault.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://thesegmentationfault.com</link>
	<description>Website and blog of Andrew Thompson</description>
	<lastBuildDate>Thu, 07 Mar 2013 01:33:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>A guide to creating class libraries in c#: The Caesar Cipher part four</title>
		<link>http://thesegmentationfault.com/?p=371</link>
		<comments>http://thesegmentationfault.com/?p=371#comments</comments>
		<pubDate>Mon, 07 May 2012 19:49:06 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=371</guid>
		<description><![CDATA[So we can use our dll file in another project? Indeed. Start up a new console project (I loaded up another instance of visual studio) and call it CaesarTest. Now the important bit is to reference your newly created library. To do this, complete the following steps: Right click on references in the solution explorer and choose &#8220;Add reference&#8221; Click on browse Locate your dll file (Should be located in CaesarLib\bin\Debug\) and click ok So we can use it now? Yup, using our library is as simple as importing the namespace. Have a look at this simple program I put together to test the library This code produces the output: Is this secure? NO. The caesar cipher shown here is only used to demonstrate a very simple use case for creating a class library. It is easily broken and should NOT be used for any security purpose whatsoever. Summary So what did we learn about? We learnt what a class library is and why it is useful We learnt about the basic caesar cipher We learnt how to implement the caesar cipher as a class library And finally, we learnt how to bring an external library into a new project Thank you for following this tutorial, I hope it helped you in some way If anybody has any questions/feedback, please do not hesitate to contact me (You can use the contact buttons at the top of this page). Download The project files are available to download. Just use the button below.]]></description>
			<content:encoded><![CDATA[<h1>So we can use our dll file in another project?</h1>
<p>Indeed. Start up a new console project (I loaded up another instance of visual studio) and call it CaesarTest. Now the important bit is to reference your newly created library. To do this, complete the following steps:</p>
<ol>
<li>Right click on references in the solution explorer and choose &#8220;Add reference&#8221;<br />
<a href="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic02.jpg"><img src="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic02-292x300.jpg" alt="" title="Click add reference" width="292" height="300" class="aligncenter size-medium wp-image-372" /></a></li>
<li>Click on browse<br />
<a href="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic03.jpg"><img src="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic03-300x239.jpg" alt="" title="Click browse" width="300" height="239" class="aligncenter size-medium wp-image-375" /></a></li>
<li>Locate your dll file (Should be located in CaesarLib\bin\Debug\) and click ok<br />
<a href="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic04.jpg"><img src="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic04-300x240.jpg" alt="" title="Find the caesarlib dll and click ok" width="300" height="240" class="aligncenter size-medium wp-image-378" /></a></li>
</ol>
<h2>So we can use it now?</h2>
<p>Yup, using our library is as simple as importing the namespace. Have a look at this simple program I put together to test the library</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using CaesarLib;

namespace CaesarTest
{
    class Program
    {
        static void Main()
        {
            var caesar = new CaesarCipher(5);

            var plaintext = &quot;THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG&quot;;
            var ciphertext = caesar.Encrypt(plaintext);

            var decryptedPlaintext = caesar.Decrypt(ciphertext);

            Console.WriteLine(string.Format(&quot;Plaintext:  {0}&quot;, plaintext));
            Console.WriteLine(string.Format(&quot;Ciphertext: {0}&quot;, ciphertext));
            Console.WriteLine(string.Format(&quot;Decrypted:  {0}&quot;,decryptedPlaintext));
            Console.ReadKey(true);
        }
    }
}
</pre>
<p>This code produces the output:</p>
<pre class="brush: plain; title: ; notranslate">
Plaintext:  THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext: OCZ LPDXF WMJRI AJS EPHKN JQZM OCZ GVUT YJB
Decrypted:  THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
</pre>
<h2>Is this secure?</h2>
<p>NO. The caesar cipher shown here is only used to demonstrate a very simple use case for creating a class library. It is easily broken and should NOT be used for any security purpose whatsoever.</p>
<h2>Summary</h2>
<p>So what did we learn about?</p>
<ol>
<li>We learnt what a class library is and why it is useful</li>
<li>We learnt about the basic caesar cipher</li>
<li>We learnt how to implement the caesar cipher as a class library</li>
<li>And finally, we learnt how to bring an external library into a new project</li>
</ol>
<p>Thank you for following this tutorial, I hope it helped you in some way <img src='http://thesegmentationfault.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
If anybody has any questions/feedback, please do not hesitate to contact me (You can use the contact buttons at the top of this page).</p>
<h2>Download</h2>
<p>The project files are available to download. Just use the button below.</p>
<div id='wpdm_file_8' class='wpdm_file wpdm-only-button'>
<div class='cont'>
<div class='btn_outer'>
<div class='btn_outer_c'><a class='btn_left  has-counter' rel='8' title='Class libraries source code' href='http://thesegmentationfault.com/?wpdmact=process&#038;did=OC5ob3RsaW5r'  >Download Sourcecode</a><span class='btn_right counter'>100 downloads</span></div>
</div>
<div class='clear'></div>
</div>
</div>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=335">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=345">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=355">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=371">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=371</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A guide to creating class libraries in c#: The Caesar Cipher part three</title>
		<link>http://thesegmentationfault.com/?p=355</link>
		<comments>http://thesegmentationfault.com/?p=355#comments</comments>
		<pubDate>Mon, 07 May 2012 19:10:11 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=355</guid>
		<description><![CDATA[Finally it is code time The idea with a class library is that you define a bunch of public types, which are then available for use from any program that references the dll. We will call our class the &#8220;CaesarCipher&#8221; and it will have two simple methods, Encrypt(string plaintext) and Decrypt(string ciphertext). Have a look at the codelisting: Lets break it down&#8230;first the constructor Its pretty simple going. We initialise the _shiftValue variable, but we modulus by 26 to give us a number in the range of 0..25 so that we can easily apply it to the alphabet (If you didn&#8217;t know, the English alphabet has 26 letters ) Then we use String.Substring() to get the first part of our alphabet by grabbing the last bunch of characters (i.e. for a shift of 4, we would get WXYZ). Then we use Substring again to chop off these last few letters (with a shift of 4, we would end up with ABCDEFGHIJKLMNOPQRSTUV). The encrypt and decrypt methods are very similar. One thing to note is that we are converting all letters to upper case (so they are compatible with our alphabets) and ignoring all characters that are not letters. (indexOf returns -1 if the character is not found). The only difference between the two methods is that we swap the arrays around in the indexOf and Append calls. Just &#8220;swap the alphabets&#8221; to convert it to a decryption. So thats it? Yup. Build it and go to the output folder and you should find your DLL! As for how to use it? Well&#8230; that can only come in part 4]]></description>
			<content:encoded><![CDATA[<h1>Finally it is code time</h1>
<p>The idea with a class library is that you define a bunch of public types, which are then available for use from any program that references the dll. We will call our class the &#8220;CaesarCipher&#8221; and it will have two simple methods, Encrypt(string plaintext) and Decrypt(string ciphertext).</p>
<p>Have a look at the codelisting:</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Text;

namespace CaesarLib
{
    public class CaesarCipher
    {
        private readonly int _shiftValue;
        private readonly string _alphabet;
        private readonly string _shiftedAlphabet; 

        public CaesarCipher(int shiftValue)
        {
            _shiftValue = (shiftValue % 26) ;

            _alphabet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;

            var alphabetStart = _alphabet.Substring(26 - _shiftValue);
            var alphabetEnd =  _alphabet.Substring(0, 26 - _shiftValue);

            _shiftedAlphabet = string.Format(&quot;{0}{1}&quot;,alphabetStart,alphabetEnd);

        }

        public string Encrypt(string plaintext)
        {
            var stringBuilder = new StringBuilder();
            foreach(var character in plaintext.ToUpper())
            {
                var index = _alphabet.IndexOf(character);

                if (index != -1)
                {
                    stringBuilder.Append(_shiftedAlphabet[index]);
                }
                else
                {
                    stringBuilder.Append(character);
                }

            }

            return stringBuilder.ToString();
        }

        public string Decrypt(string ciphertext)
        {
            var stringBuilder = new StringBuilder();
            foreach (var character in ciphertext.ToUpper())
            {
                var index = _shiftedAlphabet.IndexOf(character);

                if (index != -1)
                {
                    stringBuilder.Append(_alphabet[index]);
                }
                else
                {
                    stringBuilder.Append(character);
                }

            }

            return stringBuilder.ToString();
        }
    }
}
</pre>
<h2>Lets break it down&#8230;first the constructor</h2>
<pre class="brush: csharp; first-line: 11; title: ; notranslate">
        public CaesarCipher(int shiftValue)
        {
            _shiftValue = (shiftValue % 26) ;

            _alphabet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;

            var alphabetStart = _alphabet.Substring(26 - _shiftValue);
            var alphabetEnd =  _alphabet.Substring(0, 26 - _shiftValue);

            _shiftedAlphabet = string.Format(&quot;{0}{1}&quot;,alphabetStart,alphabetEnd);

        }
</pre>
<p>Its pretty simple going. We initialise the _shiftValue variable, but we modulus by 26 to give us a number in the range of 0..25 so that we can easily apply it to the alphabet (If you didn&#8217;t know, the English alphabet has 26 letters <img src='http://thesegmentationfault.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  )</p>
<p>Then we use String.Substring() to get the first part of our alphabet by grabbing the last bunch of characters (i.e. for a shift of 4, we would get WXYZ). Then we use Substring again to chop off these last few letters (with a shift of 4, we would end up with ABCDEFGHIJKLMNOPQRSTUV).</p>
<p>The encrypt and decrypt methods are very similar. One thing to note is that we are converting all letters to upper case (so they are compatible with our alphabets) and ignoring all characters that are not letters. (indexOf returns -1 if the character is not found). The only difference between the two methods is that we swap the arrays around in the indexOf and Append calls.</p>
<pre class="brush: csharp; first-line: 24; title: ; notranslate">
        public string Encrypt(string plaintext)
        {
            var stringBuilder = new StringBuilder();
            foreach(var character in plaintext.ToUpper())
            {
                var index = _alphabet.IndexOf(character);

                if (index != -1)
                {
                    stringBuilder.Append(_shiftedAlphabet[index]);
                }
                else
                {
                    stringBuilder.Append(character);
                }

            }

            return stringBuilder.ToString();
        }
</pre>
<p>Just &#8220;swap the alphabets&#8221; to convert it to a decryption.</p>
<pre class="brush: csharp; first-line: 45; title: ; notranslate">
public string Decrypt(string ciphertext)
        {
            var stringBuilder = new StringBuilder();
            foreach (var character in ciphertext.ToUpper())
            {
                var index = _shiftedAlphabet.IndexOf(character);

                if (index != -1)
                {
                    stringBuilder.Append(_alphabet[index]);
                }
                else
                {
                    stringBuilder.Append(character);
                }

            }

            return stringBuilder.ToString();
        }
</pre>
<h2>So thats it?</h2>
<p>Yup. Build it and go to the output folder and you should find your DLL! As for how to use it? Well&#8230; that can only come in part 4</p>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=335">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=345">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=355">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=371">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=355</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A guide to creating class libraries in c#: The Caesar Cipher part two</title>
		<link>http://thesegmentationfault.com/?p=345</link>
		<comments>http://thesegmentationfault.com/?p=345#comments</comments>
		<pubDate>Mon, 07 May 2012 18:40:58 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=345</guid>
		<description><![CDATA[So what`s this caesar cipher thing? No. It is not a kind of salad. It is a very very simple encryption technique from ancient times. More specifically it is a kind of substitution cipher, and all that means is that it works by replacing each letter of the plaintext with something else, thus making the text unreadable (ciphertext). What do you mean plaintext and ciphertext? The time has come to define some simple cryptography lingo: plaintext : Some kind of message that you want to obscure and make unreadable using encryption. ciphertext : The message after it has been encrypted. This should be unreadable to anybody who does not possess the decryption key. key : A secret phrase or other information that is used to encrypt/decrypt plaintext/ciphertext. Ok, so show me how it works Its very simple. The algorithm works by swapping each character with another character. It chooses based on a simple table produced by shifting the alphabet by a certain amount. Check out the following example: SHIFT = 4 ABCDEFGHIJKLMNOPQRSTUVWXYZ WXYZABCDEFGHIJKLMNOPQRSTUV The idea is very simple. We have used the shift 4, which means we shift the bottom alphabet by 4 characters. So now it begins with WXYZ and ends with V. All we have done is move the last 4 characters to the start. Using these two alphabets to encrypt a plaintext is very simple. You match each character with the top row, and the corresponding character on the bottom row becomes part of the cipher text. Lets look at the following example. PLAINTEXT = SEGFAULT SHIFT = 4 ABCDEFGHIJKLMNOPQRSTUVWXYZ WXYZABCDEFGHIJKLMNOPQRSTUV S = O E = A G = C F = B A = W U = Q L = H T = P CIPHERTEXT = OACBWQHP Totally mixed up heh. To decrypt the plain text you just flip the alphabets and go through the process again, like this: CIPHERTEXT = OACBWQHP SHIFT = 4 WXYZABCDEFGHIJKLMNOPQRSTUV ABCDEFGHIJKLMNOPQRSTUVWXYZ O = S A = E C = G B = F W = A Q = U H = L P = T PLAINTEXT = SEGFAULT Thats simple enough. Where can I find more information? Wikipedia has a rather good article on this stuff. Have a look at the caesar ciphers more complex cousin, the Vigenére cipher too. This is all very well, but where is the code? In part 3 I will show you how to make this into a class library!]]></description>
			<content:encoded><![CDATA[<h1>So what`s this caesar cipher thing?</h1>
<p>No. It is not a kind of salad. It is a very very simple encryption technique from ancient times. More specifically it is a kind of substitution cipher, and all that means is that it works by replacing each letter of the plaintext with something else, thus making the text unreadable (ciphertext).</p>
<h2>What do you mean plaintext and ciphertext?</h2>
<p>The time has come to define some simple cryptography lingo:</p>
<ol>
<li>plaintext  : Some kind of message that you want to obscure and make unreadable using encryption.</li>
<li>ciphertext : The message after it has been encrypted. This should be unreadable to anybody who does not possess the decryption key.</li>
<li>key        : A secret phrase or other information that is used to encrypt/decrypt plaintext/ciphertext.</li>
</ol>
<h2>Ok, so show me how it works</h2>
<p>Its very simple. The algorithm works by swapping each character with another character. It chooses based on a simple table produced by shifting the alphabet by a certain amount. Check out the following example:</p>
<p><sourcecode></p>
<p>SHIFT = 4</p>
<p>ABCDEFGHIJKLMNOPQRSTUVWXYZ<br />
WXYZABCDEFGHIJKLMNOPQRSTUV</p>
<p></sourcecode></p>
<p>The idea is very simple. We have used the shift 4, which means we shift the bottom alphabet by 4 characters. So now it begins with WXYZ and ends with V. All we have done is move the last 4 characters to the start. Using these two alphabets to encrypt a plaintext is very simple. You match each character with the top row, and the corresponding character on the bottom row becomes part of the cipher text. Lets look at the following example.</p>
<p><sourcecode></p>
<p>PLAINTEXT = SEGFAULT<br />
SHIFT = 4</p>
<p>ABCDEFGHIJKLMNOPQRSTUVWXYZ<br />
WXYZABCDEFGHIJKLMNOPQRSTUV</p>
<p>S = O<br />
E = A<br />
G = C<br />
F = B<br />
A = W<br />
U = Q<br />
L = H<br />
T = P</p>
<p>CIPHERTEXT = OACBWQHP</p>
<p></sourcecode></p>
<p>Totally mixed up heh.<br />
To decrypt the plain text you just flip the alphabets and go through the process again, like this:</p>
<p><sourcecode></p>
<p>CIPHERTEXT = OACBWQHP<br />
SHIFT = 4</p>
<p>WXYZABCDEFGHIJKLMNOPQRSTUV<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZ</p>
<p>O = S<br />
A = E<br />
C = G<br />
B = F<br />
W = A<br />
Q = U<br />
H = L<br />
P = T</p>
<p>PLAINTEXT = SEGFAULT</p>
<p></sourcecode></p>
<h2>Thats simple enough. Where can I find more information?</h2>
<p><a href="http://en.wikipedia.org/wiki/Caesar_cipher">Wikipedia</a> has a rather good article on this stuff. Have a look at the caesar ciphers more complex cousin, the <a href="http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher">Vigenére</a> cipher too.</p>
<h2>This is all very well, but where is the code?</h2>
<p>In part 3 I will show you how to make this into a class library!</p>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=335">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=345">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=355">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=371">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=345</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A guide to creating class libraries in c#: The Caesar Cipher part one</title>
		<link>http://thesegmentationfault.com/?p=335</link>
		<comments>http://thesegmentationfault.com/?p=335#comments</comments>
		<pubDate>Mon, 07 May 2012 18:23:51 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=335</guid>
		<description><![CDATA[So what are these class library things? A class library is a way to bundle up all of the types in a project into a single file called a class library. The idea is that you can then give this DLL file (DLL stands for dynamic linked library) to other developers who can reference it in their own applications and make use of your types. But what use is that? So, suppose that I had made some kind of awesome library (such as a really bad cryptography library) and I wanted anybody who was daft enough to be able to use it, but I didn&#8217;t really want to distribute my source code and project files. Well in that case, I could just offer a download of my DLL file and other people would be able to use it! Sounds good, tell me more In this example I am going to show you how to build a simple class library with just one class in it, which implements the caesar cipher (More on that in part 2!) How do I get started? First of all, please note that I am using Microsoft Visual Studio 2010 Professional for this tutorial. I believe other IDEs will behave in a similar manner, but you may have to do a little bit of research to figure out how to start a class library project if you aren&#8217;t using MSVS 2010. With that said, when you start a project, you will want to select the right template. It can be found under &#8220;Visual C# >> Windows&#8221; and you need to click &#8220;Class Library&#8221; and enter a name for your project (I called mine &#8220;CaesarLib&#8221; and I suggest you do the same if you are following along) Here is a picture to help you find the correct template : When the project loads up, you will have a single Class1.cs file in your project explorer. I deleted that file to give myself a blank slate. I will later create one source file for each type I create. Show us some code man! In the next part I will talk about the caesar cipher and show you how to implement it.]]></description>
			<content:encoded><![CDATA[<h1>So what are these class library things?</h1>
<p>A class library is a way to bundle up all of the types in a project into a single file called a class library. The idea is that you can then give this DLL file (DLL stands for dynamic linked library) to other developers who can reference it in their own applications and make use of your types.</p>
<h2>But what use is that?</h2>
<p>So, suppose that I had made some kind of awesome library (such as a really bad cryptography library) and I wanted anybody who was daft enough to be able to use it, but I didn&#8217;t really want to distribute my source code and project files. Well in that case, I could just offer a download of my DLL file and other people would be able to use it!</p>
<h2>Sounds good, tell me more</h2>
<p>In this example I am going to show you how to build a simple class library with just one class in it, which implements the caesar cipher (More on that in part 2!)</p>
<h3>How do I get started?</h3>
<p>First of all, please note that I am using Microsoft Visual Studio 2010 Professional for this tutorial. I believe other IDEs will behave in a similar manner, but you may have to do a little bit of research to figure out how to start a class library project if you aren&#8217;t using MSVS 2010.<br />
With that said, when you start a project, you will want to select the right template. It can be found under &#8220;Visual C# >> Windows&#8221; and you need to click &#8220;Class Library&#8221; and enter a name for your project (I called mine &#8220;CaesarLib&#8221; and I suggest you do the same if you are following along)</p>
<p>Here is a picture to help you find the correct template :</p>
<p><a href="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic0.jpg"><img src="http://thesegmentationfault.com/wp-content/uploads/2012/05/pic0-300x210.jpg" alt="" title="Selecting the class library template in Visual Studio" width="300" height="210" class="aligncenter size-medium wp-image-339" /></a></p>
<p>When the project loads up, you will have a single Class1.cs file in your project explorer. I deleted that file to give myself a blank slate. I will later create one source file for each type I create.</p>
<h2>Show us some code man!</h2>
<p>In the next part I will talk about the caesar cipher and show you how to implement it.</p>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=335">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=345">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=355">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=371">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=335</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>One program, Four ways” – A beginners guide to abstraction and interfaces in C# is finished</title>
		<link>http://thesegmentationfault.com/?p=307</link>
		<comments>http://thesegmentationfault.com/?p=307#comments</comments>
		<pubDate>Mon, 30 Apr 2012 05:02:41 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=307</guid>
		<description><![CDATA[I have just finished writing my first tutorial on programming, so please be kind!]]></description>
			<content:encoded><![CDATA[<p>I have just finished writing my first tutorial on programming, so please be kind!</p>
<p style="text-align: center;">
<a class="small-btn" href="http://thesegmentationfault.com/?p=238"><span><img src="http://thesegmentationfault.com/wp-content/themes/cold/images/bullets/link.png" alt="" /> Click to see</span></a></p>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=307</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;One program, Four ways&#8221; &#8211; A beginner&#8217;s guide to abstraction and interfaces in C# (Part four)</title>
		<link>http://thesegmentationfault.com/?p=281</link>
		<comments>http://thesegmentationfault.com/?p=281#comments</comments>
		<pubDate>Mon, 30 Apr 2012 03:33:45 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=281</guid>
		<description><![CDATA[This is going to be about interfaces isn&#8217;t it? Heck yes! Interfaces are awesome. Lets take a look at an emerging pattern If you have a look at the string processing methods from part 2 and the string processing classes from part 3, you will notice something. All of the classes are about one method, which takes in a string and it gives back a string, and if you think about it, they kind of do the same job, but with a different output. I.E. THEY ALL PROCESS STRINGS! and from the outside, don&#8217;t really appear to be doing anything different. So why should we treat them differently? Answer: We shouldn&#8217;t! Let us unite all of our string processors under an interface Have a look at the following interface: So we have this interface, which is called IStringProcessor. It is time to bring all of our different string processing classes together, and give them one signature that works for all of them: Implementing the interface Implementing this interface in each of our 3 string handling classes will require a tiny bit of modification. Have a look at what I have done: And there we have it. All I have done is changed the signature of the method, and derived from the interface. That looks great, but what good does it do? Good question. By implementing the interface on each of our classes, we are giving the compiler a guarantee, and that guarantee goes like this &#8220;All of our classes that implement this interface will have a string processString(string input) method on them&#8221; This is huge, because we can now store objects using variables that are typed to IStringProcessor. This means that we don&#8217;t need to make our code dependant on any of our concrete classes because we can just make it dependant on the interface instead. Take a look at this new class I have added: Basically all this class does is store a list of stringProcessors and colors. And we can invoke the HandleString method and give it an input and when we do, it will go over each processor and display the result from each one. Notice how there is no reference to any of our string processing classes in this code. The only thing that this class cares about is that we are using IStringProcessors which is a type that all of our processors can be thought of as. This class gives us the ability to add a processor, using the AddProcessor method, but it calls for an IStringProcessor. How can we give it an IStringProcessor? You can&#8217;t instantiate interfaces&#8230;duh Indeed not. What it wants us to do is give it an object that fulfils IStringProcessor and we have 3 such classes. Check out the new program class: Now the fruits of our labour are beginning to ripen! Look at how much easier main is now. Sure it is still a bit of a middle-man, but the code is much clearer. Notice how on lines 17,18 and 19 the AddProcessor method happily accepts our concrete implementations of the IStringProcessor interface. The big advantage about that is we could have as many classes as we want that fulfil the IStringProcessor interface and the StringHandler class will automatically be compatible with them, with no modification. This means that we can continue expanding in a clean, none destructive way. A task for the reader I advise you to copy out this code and try this for yourself. Why not have a go at making your own string processor class. Here is how to do it: Make a new class, and implement the IStringProcessor interface Write the ProcessString method in your new class, so it fulfils the interface use the AddProcessor method of the handler object to add your processor to it, just like on lines 17, 18 and 19 Hang on a second buddy&#8230;You can&#8217;t combine processors in this version! Okay, you got me. You can&#8217;t combine processors with this version, but if you are smart about your design, you will see that there is a way to combine the processors that is way more elegant than what we were doing before. We simply write a new type of string processor, I call it the StringProcessorChain. Behold! : Using this type of string processor, we can chain multiple processors together and when we call ProcessString, it will go through each processor, and update the input with each one, and then return back the final result. Look at the new main method which makes use of this: The beauty of the interface in this case, is that even our StringProcessChain itself is an IStringProcessor and can thus be used with the StringHandler! Even though it does a more advanced form of string processing, combining a whole bunch of processors, it still fulfils the interface and therefore it can be treated just like a StringReverser or a StringVowelRemover. Summary Thank you for reading through this tutorial. I do hope you found time to follow my examples and have a bit of a play with them to see what results you can get. If I was you, I would try and do something cool. Imagine if you had a type of string processor that encrypted the string (:OOO HAX!). I think that would be pretty cool. Knowing how and when to refactor code and when to use interfaces is a huge part of object oriented design. I must stress though that it is not something that you will learn overnight and that it will take practice. Try and think of scenarios where the design would be bad, and then try and work out what you can do to make it better. Don&#8217;t be afraid to throw big chunks of code away if you think of a better way of doing it, it takes time to develop the intuition to solve and eventually avoid these problems. If you have any feedback on my tutorial, please do not hesitate to contact me! Kind regards, Andrew Thompson 2012 Download the project files The project files are available for download. They were produced in Microsoft Visual Studio 2010 Professional.]]></description>
			<content:encoded><![CDATA[<h1>This is going to be about interfaces isn&#8217;t it?</h1>
<p>Heck yes!<br />
Interfaces are awesome.</p>
<h2>Lets take a look at an emerging pattern</h2>
<p>If you have a look at the string processing methods from part 2 and the string processing classes from part 3, you will notice something. All of the classes are about one method, which takes in a string and it gives back a string, and if you think about it, they kind of do the same job, but with a different output. I.E. <strong>THEY ALL PROCESS STRINGS!</strong> and from the outside, don&#8217;t really appear to be doing anything different. So why should we treat them differently? Answer: We shouldn&#8217;t!</p>
<h2>Let us unite all of our string processors under an interface</h2>
<p>Have a look at the following interface:</p>
<pre class="brush: csharp; title: ; notranslate">
//IStringProcessor.cs

namespace Way_04
{
    public interface IStringProcessor
    {
        string ProcessString(string input);
    }
}
</pre>
<p>So we have this interface, which is called IStringProcessor. It is time to bring all of our different string processing classes together, and give them one signature that works for all of them:</p>
<pre class="brush: csharp; title: ; notranslate">
stringProcessString(string input)
</pre>
<h2>Implementing the interface</h2>
<p>Implementing this interface in each of our 3 string handling classes will require a tiny bit of modification. Have a look at what I have done:</p>
<pre class="brush: csharp; title: ; notranslate">
//StringToUpperMaker.cs

namespace Way_04
{
    public class StringToUpperMaker : IStringProcessor
    {
        public string ProcessString(string input)
        {
            return input.ToUpper();
        }
    }
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
//StringReverser.cs

namespace Way_04
{
    public class StringReverser : IStringProcessor
    {
        public string ProcessString(string input)
        {
            var output = &quot;&quot;;

            for (var index = input.Length - 1; index &gt;= 0; index--)
            {
                output += input[index];
            }

            return output;
        }
    }
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
//StringVowelRemover.cs

namespace Way_04
{
    public class StringVowelRemover : IStringProcessor
    {
        public string ProcessString(string input)
        {
            var output = &quot;&quot;;

            var vowels = new char[] { 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
            foreach (var character in input)
            {
                var vowelFound = false;
                foreach (var vowel in vowels)
                {
                    if (character == vowel)
                    {
                        vowelFound = true;
                        break;
                    }
                }
                if (!vowelFound)
                {
                    output += character;
                }
            }

            return output;
        }
    }
}
</pre>
<p>And there we have it. All I have done is changed the signature of the method, and derived from the interface.</p>
<h2>That looks great, but what good does it do?</h2>
<p>Good question. By implementing the interface on each of our classes, we are giving the compiler a guarantee, and that guarantee goes like this &#8220;All of our classes that implement this interface will have a string processString(string input) method on them&#8221;</p>
<p>This is huge, because we can now store objects using variables that are typed to IStringProcessor. This means that we don&#8217;t need to make our code dependant on any of our concrete classes because we can just make it dependant on the interface instead. Take a look at this new class I have added:</p>
<pre class="brush: csharp; title: ; notranslate">
//StringHandler.cs

using System;
using System.Collections.Generic;

namespace Way_04
{
    public class StringHandler
    {
        private readonly List&lt;IStringProcessor&gt; _processors;
        private readonly List&lt;ConsoleColor&gt; _colors;
        private readonly StringDisplayer _displayer;

        public StringHandler()
        {
            _processors = new List&lt;IStringProcessor&gt;();
            _colors = new List&lt;ConsoleColor&gt;();
            _displayer = new StringDisplayer();

        }

        public void AddProcessor(IStringProcessor processor, ConsoleColor color = ConsoleColor.Gray)
        {
            _processors.Add(processor);
            _colors.Add(color);
        }

        public void HandleString(string input)
        {
            for(var index = 0; index &lt; _processors.Count; index++)
            {
                var processor = _processors[index];
                var color = _colors[index];
                _displayer.DisplayString(processor.ProcessString(input),color);
            }
        }

    }
}
</pre>
<p>Basically all this class does is store a list of stringProcessors and colors. And we can invoke the HandleString method and give it an input and when we do, it will go over each processor and display the result from each one.<br />
Notice how there is no reference to any of our string processing classes in this code. The only thing that this class cares about is that we are using IStringProcessors which is a type that all of our processors can be thought of as. This class gives us the ability to add a processor, using the AddProcessor method, but it calls for an IStringProcessor.</p>
<h2>How can we give it an IStringProcessor? You can&#8217;t instantiate interfaces&#8230;duh</h2>
<p>Indeed not. What it wants us to do is give it an object that fulfils IStringProcessor and we have 3 such classes. Check out the new program class:</p>
<pre class="brush: csharp; title: ; notranslate">
//Program.cs

using System;
using System.Collections.Generic;

namespace Way_04
{
    class Program
    {
        static void Main()
        {
            Console.Write(&quot;Please type some text: &quot;);
            var input = Console.ReadLine();

            var handler = new StringHandler();

            handler.AddProcessor(new StringToUpperMaker());
            handler.AddProcessor(new StringReverser());
            handler.AddProcessor(new StringVowelRemover());

            handler.AddProcessor(new StringToUpperMaker(),ConsoleColor.Green);

            handler.HandleString(input);

            Console.ReadKey(true);

        }
    }
}
</pre>
<p>Now the fruits of our labour are beginning to ripen! Look at how much easier main is now. Sure it is still a bit of a middle-man, but the code is much clearer. Notice how on lines 17,18 and 19 the AddProcessor method happily accepts our <strong>concrete</strong> implementations of the IStringProcessor interface. The big advantage about that is we could have as many classes as we want that fulfil the IStringProcessor interface and the StringHandler class will automatically be compatible with them, with no modification. This means that we can continue expanding in a clean, none destructive way.</p>
<h2>A task for the reader</h2>
<p>I advise you to copy out this code and try this for yourself. Why not have a go at making your own string processor class. Here is how to do it:</p>
<ol>
<li>Make a new class, and implement the IStringProcessor interface</li>
<li>Write the ProcessString method in your new class, so it fulfils the interface</li>
<li>use the AddProcessor method of the handler object to add your processor to it, just like on lines 17, 18 and 19</li>
</ol>
<h2>Hang on a second buddy&#8230;You can&#8217;t combine processors in this version!</h2>
<p>Okay, you got me. You can&#8217;t combine processors with this version, but if you are smart about your design, you will see that there is a way to combine the processors that is way more elegant than what we were doing before. We simply write a new type of string processor, I call it the StringProcessorChain. Behold! :</p>
<pre class="brush: csharp; title: ; notranslate">
//StringProcessorChain.cs

using System.Collections.Generic;

namespace Way_04
{
    public class StringProcessorChain : IStringProcessor
    {
        private readonly List&lt;IStringProcessor&gt; _chain;

        public StringProcessorChain()
        {
            _chain = new List&lt;IStringProcessor&gt;();
        }

        public void AddProcessor(IStringProcessor processor)
        {
            _chain.Add(processor);
        }
        public string ProcessString(string input)
        {
            foreach(var processor in _chain)
            {
                input = processor.ProcessString(input);
            }

            return input;
        }
    }
}
</pre>
<p>Using this type of string processor, we can chain multiple processors together and when we call ProcessString, it will go through each processor, and update the input with each one, and then return back the final result. Look at the new main method which makes use of this:</p>
<pre class="brush: csharp; title: ; notranslate">
//Program.cs

using System;
using System.Collections.Generic;

namespace Way_04
{
    class Program
    {
        static void Main()
        {
            Console.Write(&quot;Please type some text: &quot;);
            var input = Console.ReadLine();

            var handler = new StringHandler();

            var chain = new StringProcessorChain();

            chain.AddProcessor(new StringReverser());
            chain.AddProcessor(new StringToUpperMaker());
            chain.AddProcessor(new StringVowelRemover());

            handler.AddProcessor(chain,ConsoleColor.Yellow);
            handler.HandleString(input);

            Console.ReadKey(true);

        }
    }
}
</pre>
<p>The beauty of the interface in this case, is that even our StringProcessChain itself is an IStringProcessor and can thus be used with the StringHandler! Even though it does a more advanced form of string processing, combining a whole bunch of processors, it still fulfils the interface and therefore it can be treated just like a StringReverser or a StringVowelRemover.</p>
<h1>Summary</h1>
<p>Thank you for reading through this tutorial. I do hope you found time to follow my examples and have a bit of a play with them to see what results you can get. If I was you, I would try and do something cool. Imagine if you had a type of string processor that encrypted the string (:OOO HAX!). I think that would be pretty cool.</p>
<p>Knowing how and when to refactor code and when to use interfaces is a huge part of object oriented design. I must stress though that it is not something that you will learn overnight and that it will take practice. Try and think of scenarios where the design would be bad, and then try and work out what you can do to make it better. Don&#8217;t be afraid to throw big chunks of code away if you think of a better way of doing it, it takes time to develop the intuition to solve and eventually avoid these problems.</p>
<p>If you have any feedback on my tutorial, please do not hesitate to contact me!</p>
<p>Kind regards,</p>
<p>Andrew Thompson 2012</p>
<h1>Download the project files</h1>
<p>The project files are available for download. They were produced in Microsoft Visual Studio 2010 Professional.</p>
<div id='wpdm_file_3' class='wpdm_file wpdm-only-button'>
<div class='cont'>
<div class='btn_outer'>
<div class='btn_outer_c'><a class='btn_left  has-counter' rel='3' title='One Program Four Ways' href='http://thesegmentationfault.com/?wpdmact=process&#038;did=My5ob3RsaW5r'  >Download Sourcecode</a><span class='btn_right counter'>71 downloads</span></div>
</div>
<div class='clear'></div>
</div>
</div>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=238">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=247">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=272">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=281">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=281</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;One program, Four ways&#8221; &#8211; A beginner&#8217;s guide to abstraction and interfaces in C# (Part three)</title>
		<link>http://thesegmentationfault.com/?p=272</link>
		<comments>http://thesegmentationfault.com/?p=272#comments</comments>
		<pubDate>Mon, 30 Apr 2012 02:54:58 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=272</guid>
		<description><![CDATA[So what&#8217;s next? So, in part two we refactored our program and de-cluttered our main method, and made our code a bit better and easier to read, but there were still a few problems. Our program class was still full of stuff which should be put elsewhere. Lets have a look at our objectives for the next version: De-clutter the whole program class. Lets get it as clean as we can Make classes for each of the string processing methods that we have now Make a class to handle the displaying of coloured strings to the screen Let us begin..:D This time around I have put each class into a file of its own. One class per file is how myself and most people usually work in C#. I have kept them all in the same namespace for simplicities sake. Moving the functionality from the methods to classes was a very simple job. The body of the methods didn&#8217;t need to change at all. Have a look at the following classes: And there we have it. Three instance classes which separate the functionality out and away from the Program class. It may seem a bit extreme to put them in their own class with only a single method, but it isn&#8217;t really, and it doesn&#8217;t take much extra work to do it, but the extra functionality afforded to you by doing it is immense. Now you are able to give your string processors their own sets of data to work with, and they are fully independant now. They are only dependant on themselves, but we haven&#8217;t lost any functionality. This can only be a good thing. I have thought about this, and I have extracted the two display methods from the program class and put them into their own class. Take a look: Now you may notice that this class contains BOTH of the display methods and you may be wondering why I didn&#8217;t make two classes for this? Well, if you think about the single responsibility principle, I think this class is okay, because the class as a whole still only has one responsibility if you think about it. Its responsibility is to display strings to the user and it uses two methods to fulfill this responsibility. Yup! And its all because we have taken all extraneous information out of it and put it somewhere else. Have a look: Much cleaner now, and because of that, it is actually easier to tell at a glance what it does. We are making good progress, but there are still some problems First of all, let us not forget the program that we started with back in part one, it consisted of just a main method with all of this stuff written inside of it. Sure it did the same thing, but if you needed to continue working on the code, would you prefer to improve this new version, or the original version? Which do you think would be easier to work with? I hope you picked this one. One of the problems with this version is that the StringDisplayer class has to rely on the Program class to feed it strings to display, but it shouldn&#8217;t have to really since the other classes all provide strings. It is like we have a middle-man that can be got rid of. Of course we could have each of the string generating classes inside of StringDisplayer, but that isn&#8217;t really a good idea either. For one thing it violates the single responsibility principle, because StringDisplayer should be concerned only with displaying strings and nothing more. Also it would be difficult to maintain as you added more string generating classes. Every time you added a new string generating class you would have to update the StringDisplayer class, and this is bad and it makes your code harder to manage. In the next part I will demonstrate how to use interfaces to take this to the next level.]]></description>
			<content:encoded><![CDATA[<h1>So what&#8217;s next?</h1>
<p>So, in part two we refactored our program and de-cluttered our main method, and made our code a bit better and easier to read, but there were still a few problems. Our program class was still full of stuff which should be put elsewhere. Lets have a look at our objectives for the next version:</p>
<ul>
<li>De-clutter the whole program class. Lets get it as clean as we can</li>
<li>Make classes for each of the string processing methods that we have now</li>
<li>Make a class to handle the displaying of coloured strings to the screen</li>
</ul>
<h2>Let us begin..:D</h2>
<p>This time around I have put each class into a file of its own. One class per file is how myself and most people usually work in C#. I have kept them all in the same namespace for simplicities sake. Moving the functionality from the methods to classes was a very simple job. The body of the methods didn&#8217;t need to change at all. Have a look at the following classes:</p>
<pre class="brush: csharp; title: ; notranslate">
//StringToUpperMaker.cs

namespace Way_03
{
    public class StringToUpperMaker
    {
        public string GetStringToUpper(string input)
        {
            return input.ToUpper();
        }
    }
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
//StringReverser.cs

namespace Way_03
{
    public class StringReverser
    {

        public string ReverseString(string input)
        {
            var output = &quot;&quot;;

            for (var index = input.Length - 1; index &gt;= 0; index--)
            {
                output += input[index];
            }

            return output;
        }

    }
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
//StringVowelRemover.cs

namespace Way_03
{
    public class StringVowelRemover
    {
        public string RemoveVowels(string input)
        {
            var output = &quot;&quot;;

            var vowels = new char[] { 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
            foreach (var character in input)
            {
                var vowelFound = false;
                foreach (var vowel in vowels)
                {
                    if (character == vowel)
                    {
                        vowelFound = true;
                        break;
                    }
                }
                if (!vowelFound)
                {
                    output += character;
                }
            }

            return output;
        }
    }
}
</pre>
<p>And there we have it. Three instance classes which separate the functionality out and away from the Program class. It may seem a bit extreme to put them in their own class with only a single method, but it isn&#8217;t really, and it doesn&#8217;t take much extra work to do it, but the extra functionality afforded to you by doing it is immense. Now you are able to give your string processors their own sets of data to work with, and they are fully independant now. They are only dependant on themselves, but we haven&#8217;t lost any functionality. This can only be a good thing.</p>
<h2> What about displaying the strings</h2>
<p>I have thought about this, and I have extracted the two display methods from the program class and put them into their own class. Take a look:</p>
<pre class="brush: csharp; title: ; notranslate">
//StringDisplayer.cs

using System;

namespace Way_03
{
    public class StringDisplayer
    {

        public void DisplayString(string input)
        {
            DisplayString(input, ConsoleColor.White);
        }

        public void DisplayString(string input, ConsoleColor color)
        {
            var tempColor = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.WriteLine(input);
            Console.ForegroundColor = tempColor;
        }
    }
}
</pre>
<p>Now you may notice that this class contains BOTH of the display methods and you may be wondering why I didn&#8217;t make two classes for this? Well, if you think about the single responsibility principle, I think this class is okay, because the class as a whole still only has one responsibility if you think about it. Its responsibility is to display strings to the user and it uses two methods to fulfill this responsibility.</p>
<h2>I bet the program class is much cleaner now</h2>
<p>Yup! And its all because we have taken all extraneous information out of it and put it somewhere else. Have a look:</p>
<pre class="brush: csharp; title: ; notranslate">

// Program.cs

using System;

namespace Way_03
{
    class Program
    {
        static void Main()
        {
            Console.Write(&quot;Please type some text: &quot;);
            var input = Console.ReadLine();

            var displayer = new StringDisplayer();
            var upperMaker = new StringToUpperMaker();
            var reverser = new StringReverser();
            var vowelRemover = new StringVowelRemover();

            displayer.DisplayString(upperMaker.GetStringToUpper(input));

            displayer.DisplayString(reverser.ReverseString(input));

            displayer.DisplayString(vowelRemover.RemoveVowels(input));

            displayer.DisplayString(upperMaker.GetStringToUpper(input),ConsoleColor.Green);

            Console.ReadKey(true);
        }
    }
}
</pre>
<p>Much cleaner now, and because of that, it is actually easier to tell at a glance what it does.</p>
<h2>We are making good progress, but there are still some problems</h2>
<p>First of all, let us not forget the program that we started with back in part one, it consisted of just a main method with all of this stuff written inside of it. Sure it did the same thing, but if you needed to continue working on the code, would you prefer to improve this new version, or the original version? Which do you think would be easier to work with? I hope you picked this one.<br />
One of the problems with this version is that the StringDisplayer class has to rely on the Program class to feed it strings to display, but it shouldn&#8217;t have to really since the other classes all provide strings. It is like we have a middle-man that can be got rid of. Of course we could have each of the string generating classes inside of StringDisplayer, but that isn&#8217;t really a good idea either. For one thing it violates the single responsibility principle, because StringDisplayer should be concerned only with displaying strings and nothing more. Also it would be difficult to maintain as you added more string generating classes. Every time you added a new string generating class you would have to update the StringDisplayer class, and this is bad and it makes your code harder to manage.</p>
<p>In the next part I will demonstrate how to use interfaces to take this to the next level.</p>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=238">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=247">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=272">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=281">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=272</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;One program, Four ways&#8221; &#8211; A beginner&#8217;s guide to abstraction and interfaces in C# (Part two)</title>
		<link>http://thesegmentationfault.com/?p=247</link>
		<comments>http://thesegmentationfault.com/?p=247#comments</comments>
		<pubDate>Mon, 30 Apr 2012 00:52:04 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=247</guid>
		<description><![CDATA[Shall we continue? In part one we set up a simple program and we illustrated some issues with the code. In this part I will introduce you to a slightly better version of the same program. Let us talk about what we are going to do. We have a couple of objectives: Get rid of all the clutter from main Seperate the string processing procedures into their own methods, to make them easier to combine Setup an easier way to display strings in different colours Lets make some methods Did you notice a pattern in the first program? We were dealing with a single string, and with each different type of output, all we were doing was outputting a single string. This is a good candidate for a method. We can write a bunch of methods that each take in a string and each return a string. For example: This is the simplest example of extracting it to a method. Sure it might seem a bit daft to extract a single line and put it in a method, but what you are doing is taking that responsibility away from main. Putting it in its own method allows you to update the method with new code, without breaking everything else that uses it, and also without cluttering anything that uses it. The idea here is to move the responsibility away from main, and be able to re-use this bit of code as much as possible. Lets have a look at another example: This is a better example, now we have a whole bunch of code which has been removed from the main method and put in its own little box. It has nearly the same signature as before, but it has a different name. The idea with methods is that somebody should be able to tell exactly what a method is for, and how to use it just by looking at the signature and not looking at the actual implementation, and we can see that our signature does this. If we look at just the signature we are able to work out exactly what the method does AND how to use it. Its self explanatory, and all methods should be like this. And finally the reverse string method! It does the same thing as before, but again it is factored out into its own method, and the signature of the method tells us exactly what it does and exactly how to use it! But what about the pretty colors! Don&#8217;t worry! This can be factored out too, but we have to do it slightly differently, as changing the colour doesn&#8217;t take in a string and it doesn&#8217;t need to return anything. What would be great is if we had a way of telling the console to display a string in a certain color, and then to reset the color back afterwards. It will be something that we can re-use over and over again. This method, if you look at its signature, takes an input and a colour and displays the input in the specified colour. It makes use of the ConsoleColor enum which is part of the BCL. Once it has displayed the string it then resets the colour to what it was before. As a way of demonstrating a good candidate for method overloading, we can create new version of this method, which defaults the colour to white: All it does is call the other version using the provided input, but with white as the parameter for the colour. Simple enough But wait! What happened to main!? Don&#8217;t worry, I saved the best bit until last. Using the code above we can effectively clean up the main method See how much cleaner that is now. It is now easier to follow the logic of what main is actually doing. It is more of an overview of logic rather than an explicit list of each and every step. It is also self documenting to a degree, and that is down to how the signatures for each method had been written. If the small parts are named well, then the whole will be much easier to read. Since we are now dealing with strings and black boxes (the methods), it is now easier to combine functionality. Now if the boss comes in and says &#8220;OMG WE NEED IT TO BE IN RED AND UPPERCASE&#8221;, we know we can easily do it with the following line: Simples! Full source code listing So there are still problems? You bet! The big problem we have here is how the Program class has so much clutter in it. It has 5 extra methods on it. A good tip to try and remember is to try and keep your classes as clean as possible and to try and give them only one responsibility. This is known as the SINGLE RESPONSIBILITY PRINCIPLE which is often referred to as SRP for short. In general, you will want to try and keep your Program class as simple as possible since its only responsibility is to start the application. Its responsibility isn&#8217;t really to display anything or perform any program logic. What would be great is if we were able to separate all of our logic into a set of classes. We will do this in part 3!]]></description>
			<content:encoded><![CDATA[<h1>Shall we continue?</h1>
<p>In part one we set up a simple program and we illustrated some issues with the code. In this part I will introduce you to a slightly better version of the same program. Let us talk about what we are going to do. We have a couple of objectives:</p>
<ul>
<li>Get rid of all the clutter from main</li>
<li>Seperate the string processing procedures into their own methods, to make them easier to combine</li>
<li>Setup an easier way to display strings in different colours</li>
</ul>
<h2>Lets make some methods</h2>
<p>Did you notice a pattern in the first program? We were dealing with a single string, and with each different type of output, all we were doing was outputting a single string. This is a good candidate for a method. We can write a bunch of methods that each take in a string and each return a string. For example:</p>
<pre class="brush: csharp; title: ; notranslate">
        static string GetStringInUpperCase(string input)
        {
            return input.ToUpper();
        }
</pre>
<p>This is the simplest example of extracting it to a method. Sure it might seem a bit daft to extract a single line and put it in a method, but what you are doing is taking that responsibility away from main. Putting it in its own method allows you to update the method with new code, without breaking everything else that uses it, and also without cluttering anything that uses it. The idea here is to move the responsibility away from main, and be able to re-use this bit of code as much as possible.<br />
Lets have a look at another example:</p>
<pre class="brush: csharp; title: ; notranslate">
        static string GetStringInReverse(string input)
        {
            var output = &quot;&quot;;

            for (var c = input.Length - 1; c &gt;= 0; c--)
            {
                output += input[c];
            }

            return output;
        }
</pre>
<p>This is a better example, now we have a whole bunch of code which has been removed from the main method and put in its own little box. It has nearly the same signature as before, but it has a different name. The idea with methods is that somebody should be able to tell exactly what a method is for, and how to use it just by looking at the signature and not looking at the actual implementation, and we can see that our signature does this.</p>
<pre class="brush: csharp; title: ; notranslate">
static string GetStringInReverse(string input)
</pre>
<p>If we look at just the signature we are able to work out exactly what the method does AND how to use it. Its self explanatory, and all methods should be like this.</p>
<pre class="brush: csharp; title: ; notranslate">
private static string GetStringWithoutVowels(string input)
        {
            var output = &quot;&quot;;

            var vowels = new char[] { 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
            foreach (var character in input)
            {
                var vowelFound = false;
                foreach (var vowel in vowels)
                {
                    if (character == vowel)
                    {
                        vowelFound = true;
                        break;
                    }
                }
                if (!vowelFound)
                {
                    output += character;
                }
            }

            return output;
        }
</pre>
<p>And finally the reverse string method! It does the same thing as before, but again it is factored out into its own method, and the signature of the method tells us exactly what it does and exactly how to use it!</p>
<h2>But what about the pretty colors! <img src='http://thesegmentationfault.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </h2>
<p>Don&#8217;t worry! This can be factored out too, but we have to do it slightly differently, as changing the colour doesn&#8217;t take in a string and it doesn&#8217;t need to return anything. What would be great is if we had a way of telling the console to display a string in a certain color, and then to reset the color back afterwards. It will be something that we can re-use over and over again.</p>
<pre class="brush: csharp; title: ; notranslate">
        private static void DisplayString(string input, ConsoleColor color)
        {
            var tempColor = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.WriteLine(input);
            Console.ForegroundColor = tempColor;
        }
</pre>
<p>This method, if you look at its signature, takes an input and a colour and displays the input in the specified colour. It makes use of the ConsoleColor enum which is part of the BCL. Once it has displayed the string it then resets the colour to what it was before.<br />
As a way of demonstrating a good candidate for method overloading, we can create new version of this method, which defaults the colour to white:</p>
<pre class="brush: csharp; title: ; notranslate">
        //Overloaded version of the display string which uses white as the default color
        private static void DisplayString(string input)
        {
            //Call the full version and give it white
            DisplayString(input,ConsoleColor.White);
        }
</pre>
<p>All it does is call the other version using the provided input, but with white as the parameter for the colour. Simple enough <img src='http://thesegmentationfault.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h2>But wait! What happened to main!?</h2>
<p>Don&#8217;t worry, I saved the best bit until last. Using the code above we can effectively clean up the main method <img src='http://thesegmentationfault.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: csharp; title: ; notranslate">
        static void Main()
        {
            Console.Write(&quot;Please type some text: &quot;);
            var input = Console.ReadLine();

            var upperCase = GetStringInUpperCase(input);
            var reversed = GetStringInReverse(input);
            var withoutVowels = GetStringWithoutVowels(input);

            DisplayString(upperCase);
            DisplayString(reversed);
            DisplayString(withoutVowels);

            DisplayString(upperCase,ConsoleColor.Green);

            Console.ReadKey(true);
        }
</pre>
<p>See how much cleaner that is now. It is now easier to follow the logic of what main is actually doing. It is more of an overview of logic rather than an explicit list of each and every step. It is also self documenting to a degree, and that is down to how the signatures for each method had been written. If the small parts are named well, then the whole will be much easier to read.<br />
Since we are now dealing with strings and black boxes (the methods), it is now easier to combine functionality. Now if the boss comes in and says &#8220;OMG WE NEED IT TO BE IN RED AND UPPERCASE&#8221;, we know we can easily do it with the following line:</p>
<pre class="brush: csharp; title: ; notranslate">
DisplayString(GetStringInReverse(upperCase),ConsoleColor.Red);
</pre>
<p>Simples!</p>
<h2>Full source code listing</h2>
<pre class="brush: csharp; title: ; notranslate">

using System;

namespace Way_02
{
    class Program
    {
        static void Main()
        {
            Console.Write(&quot;Please type some text: &quot;);
            var input = Console.ReadLine();

            var upperCase = GetStringInUpperCase(input);
            var reversed = GetStringInReverse(input);
            var withoutVowels = GetStringWithoutVowels(input);

            DisplayString(upperCase);
            DisplayString(reversed);
            DisplayString(withoutVowels);

            DisplayString(upperCase,ConsoleColor.Green);

            DisplayString(GetStringInReverse(upperCase),ConsoleColor.Red);

            Console.ReadKey(true);
        }

        //Overloaded version of the display string which uses white as the default color
        private static void DisplayString(string input)
        {
            //Call the full version and give it white
            DisplayString(input,ConsoleColor.White);
        }

        //Displays a string in a specified color
        private static void DisplayString(string input, ConsoleColor color)
        {
            var tempColor = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.WriteLine(input);
            Console.ForegroundColor = tempColor;
        }

        private static string GetStringWithoutVowels(string input)
        {
            var output = &quot;&quot;;

            var vowels = new char[] { 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
            foreach (var character in input)
            {
                var vowelFound = false;
                foreach (var vowel in vowels)
                {
                    if (character == vowel)
                    {
                        vowelFound = true;
                        break;
                    }
                }
                if (!vowelFound)
                {
                    output += character;
                }
            }

            return output;
        }

        static string GetStringInUpperCase(string input)
        {
            return input.ToUpper();
        }

        static string GetStringInReverse(string input)
        {
            var output = &quot;&quot;;

            for (var c = input.Length - 1; c &gt;= 0; c--)
            {
                output += input1;
            }

            return output;
        }
    }
}
</pre>
<h2>So there are still problems?</h2>
<p>You bet! The big problem we have here is how the Program class has so much clutter in it. It has 5 extra methods on it. A good tip to try and remember is to try and keep your classes as clean as possible and to try and give them only one responsibility. This is known as the <strong>SINGLE RESPONSIBILITY PRINCIPLE</strong> which is often referred to as <strong>SRP</strong> for short. In general, you will want to try and keep your Program class as simple as possible since its only responsibility is to start the application. Its responsibility isn&#8217;t really to display anything or perform any program logic. What would be great is if we were able to separate all of our logic into a set of classes. We will do this in part 3!</p>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=238">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=247">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=272">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=281">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=247</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;One program, Four ways&#8221; &#8211; A beginner&#8217;s guide to abstraction and interfaces in C# (Part one)</title>
		<link>http://thesegmentationfault.com/?p=238</link>
		<comments>http://thesegmentationfault.com/?p=238#comments</comments>
		<pubDate>Sun, 29 Apr 2012 23:52:58 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Tutorials & Guides]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=238</guid>
		<description><![CDATA[Introduction A few of the people I know who are currently learning C# and object oriented programming and design have been sharing with me their problems in getting their heads around object oriented design. I have decided to try and help by working up an example which shows a program written 4 ways; Starting out with bad design and illustrating the problems with the design, each iteration will be a more advanced version until I feel I am happy with the overall design. So lets begin! For myself, the process of learning how to write better code was an iterative one. When you are just starting out it is easy to code yourself into a corner with object oriented programming. You find yourself against a wall of problems. Over time you work out how to solve the problems and eventually you start avoiding the problems before they become a problem altogether. The example I am going to show has some problems. In this part of the tutorial I will show you the code for a simple program and illustrate some problems that it has. By problem, I mean some kind of problem in the design, and this is important to realise. Each of the four editions of the program will produce the same output, but they will work differently under the hood. The difference will be how easy it is to alter / expand / remove functionality in them, so when I say code has a problem, it means that it is difficult to change or expand the program, and changing the code it to a better design will make it easier to modify and expand it. This is the whole point of object oriented design. The process of changing the code in such a way to improve the design without changing the output is called refactoring. The program! I decided to keep the program in question very simple. All it does is take some input from the user, and then displays the input back to the user in a number of different ways. Check out the source code below:- When you run it, you get the following output: As you can see it is very simple, but it does have a couple of issues. Problem one: Adding functionality is tricky If we wanted to add more functionality to this program in order to show the input in another way (For example in a different colour or by swapping words around) then our only way would be to add additional code, like this: Of course, it isn&#8217;t too difficult to do it in this example, but this is just filling up our main method with lots of stuff that isn&#8217;t really relevant. Imagine that these bits of functionality are only small parts of a much larger program (A large program with lots of more important parts) and it becomes clear that adding functionality in this way is going to make things less manageable down the line. Problem two: Combining functionality Suppose that we wanted to have an extra line of output, but this time it displays the input text in reverse AND in capitals AND in green. Of course we can do this easily by adding extra lines to our program as follows: Ok so that works fine right? NO! Whilst the program displays the expected message, this way of coding is not a good idea. There is an important rule of programming that it is a good idea to live by, and it is DON&#8217;T REPEAT YOURSELF often abbreviated to DRY. Here we have repeated ourselves by writing three bits of functionality twice, and this is never a good idea, because we want both versions of the functionality to behave the same way, which means if we change one version we have to go back and change the other version too, and this is more difficult to manage. But the program works&#8230; Yep, but now suppose your boss comes in and says &#8220;Ok, so we need it to show in green, in lowercase, but not in reverse&#8221; or &#8220;we need it in reverse and uppercase, but not in green&#8221;. For each of these problems you have to write a big chunk of code and it can very easily become unmanageable. So what`s the solution then? The solution is to refactor the code and improve its design. We will look at that in part two.]]></description>
			<content:encoded><![CDATA[<h1>Introduction</h1>
<p>A few of the people I know who are currently learning C# and object oriented programming and design have been sharing with me their problems in getting their heads around object oriented design. I have decided to try and help by working up an example which shows a program written 4 ways; Starting out with bad design and illustrating the problems with the design, each iteration will be a more advanced version until I feel I am happy with the overall design.</p>
<h1>So lets begin!</h1>
<p>For myself, the process of learning how to write better code was an iterative one. When you are just starting out it is easy to code yourself into a corner with object oriented programming. You find yourself against a wall of problems. Over time you work out how to solve the problems and eventually you start avoiding the problems before they become a problem altogether.</p>
<p>The example I am going to show has some problems. In this part of the tutorial I will show you the code for a simple program and illustrate some problems that it has. By problem, I mean some kind of problem in the design, and this is important to realise. Each of the four editions of the program will produce the same output, but they will work differently under the hood. The difference will be how easy it is to alter / expand / remove functionality in them, so when I say code has a problem, it means that it is difficult to change or expand the program, and changing the code it to a better design will make it easier to modify and expand it. This is the whole point of object oriented design. The process of changing the code in such a way to improve the design without changing the output is called <strong>refactoring</strong>.</p>
<h1>The program!</h1>
<p>I decided to keep the program in question very simple. All it does is take some input from the user, and then displays the input back to the user in a number of different ways. Check out the source code below:-</p>
<pre class="brush: csharp; title: ; notranslate">
using System;

namespace Way_01
{
    class Program
    {
        static void Main()
        {
            Console.Write(&quot;Please type some text: &quot;);
            var input = Console.ReadLine();

            //Display the input, but in capital letters
            Console.WriteLine(input.ToUpper());

            //Display the input, but in reverse
            for(var i = input.Length-1; i &gt;= 0; i --)
            {
                Console.Write(input[i]);
            }
            Console.WriteLine();

            //Display the input, but without any vowels
            var vowels = new char[] {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
            foreach(var character in input)
            {
                var vowelFound = false;
                foreach (var vowel in vowels)
                {
                    if(character == vowel)
                    {
                        vowelFound = true;
                        break;
                    }
                }
                if (!vowelFound)
                {
                    Console.Write(character);
                }
            }

            Console.WriteLine();

            Console.ReadKey(true);

        }
    }
}
</pre>
<p>When you run it, you get the following output:</p>
<pre class="brush: plain; title: ; notranslate">
Please type some text: The quick brown fox jumps over the lazy dog
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
god yzal eht revo spmuj xof nworb kciuq ehT
Th qck brwn fx jmps vr th lzy dg
</pre>
<p>As you can see it is very simple, but it does have a couple of issues.</p>
<h2>Problem one: Adding functionality is tricky</h2>
<p>If we wanted to add more functionality to this program in order to show the input in another way (For example in a different colour or by swapping words around) then our only way would be to add additional code, like this:</p>
<pre class="brush: csharp; first-line: 43; title: ; notranslate">
            //Adding functionality - Display the input in green

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(input);
            Console.ForegroundColor = ConsoleColor.White;
</pre>
<p>Of course, it isn&#8217;t too difficult to do it in this example, but this is just filling up our main method with lots of stuff that isn&#8217;t really relevant. Imagine that these bits of functionality are only small parts of a much larger program (A large program with lots of more important parts) and it becomes clear that adding functionality in this way is going to make things less manageable down the line.</p>
<h2>Problem two: Combining functionality</h2>
<p>Suppose that we wanted to have an extra line of output, but this time it displays the input text in reverse AND in capitals AND in green. Of course we can do this easily by adding extra lines to our program as follows:</p>
<pre class="brush: csharp; first-line: 51; title: ; notranslate">

            //Display the input, but in reverse AND in green AND in capitals
            Console.ForegroundColor = ConsoleColor.Green;
            for (var i = input.Length - 1; i &gt;= 0; i--)
            {
                Console.Write(input[i].ToString().ToUpper());
            }
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();
</pre>
<h3>Ok so that works fine right? NO!</h3>
<p>Whilst the program displays the expected message, this way of coding is not a good idea. There is an important rule of programming that it is a good idea to live by, and it is <strong>DON&#8217;T REPEAT YOURSELF</strong> often abbreviated to <strong>DRY</strong>. Here we have repeated ourselves by writing three bits of functionality twice, and this is never a good idea, because we want both versions of the functionality to behave the same way, which means if we change one version we have to go back and change the other version too, and this is more difficult to manage.</p>
<h3>But the program works&#8230;</h3>
<p>Yep, but now suppose your boss comes in and says &#8220;Ok, so we need it to show in green, in lowercase, but not in reverse&#8221; or &#8220;we need it in reverse and uppercase, but not in green&#8221;. For each of these problems you have to write a big chunk of code and it can very easily become unmanageable.</p>
<h2>So what`s the solution then?</h2>
<p>The solution is to refactor the code and improve its design. We will look at that in part two.</p>
<ul class="small-list small-go">
<li><a href="http://thesegmentationfault.com/?p=238">Part one</a></li>
<li><a href="http://thesegmentationfault.com/?p=247">Part two</a></li>
<li><a href="http://thesegmentationfault.com/?p=272">Part three</a></li>
<li><a href="http://thesegmentationfault.com/?p=281">Part four</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=238</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing syntax highlighting plugin :)</title>
		<link>http://thesegmentationfault.com/?p=234</link>
		<comments>http://thesegmentationfault.com/?p=234#comments</comments>
		<pubDate>Sun, 29 Apr 2012 22:59:05 +0000</pubDate>
		<dc:creator>segfault</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thesegmentationfault.com/?p=234</guid>
		<description><![CDATA[So I have decided to maybe write some programming tutorials/guides on this website. This post is just to test the use of a syntax highlighting shortcode that I have just installed. Fun!]]></description>
			<content:encoded><![CDATA[<p>So I have decided to maybe write some programming tutorials/guides on this website. This post is just to test the use of a syntax highlighting shortcode that I have just installed.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;

namespace Hello
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine(&quot;Hello TheSegmentationfault.com !!&quot;);
        }
    }
}
</pre>
<p>Fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://thesegmentationfault.com/?feed=rss2&#038;p=234</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
