Tuesday, April 22, 2014

Why Don't You Use Factories?

After reading and applying traditional software design techniques taught by some of the best professional developers such as Edward Yourdon, Frederick Brooks, Martin Fowler; I thought that I was fairly talented at designing and writing software systems. However, if there is a single technique that I overlooked when designing/implementing software solutions it is the factory. Factories, have been around for quite a while but they have recently, within the last 5 years or so, become an important tool for me.
If you just started reading this and you know about dependency injection...this is not an argument that factories are better than dependency injection frameworks at all. The only argument that I can come up with that they are better than DI frameworks is that factories are a lot lighter weight and you may save some time not jumping through technical hoops that a DI framework will require.

What is a Constructor?

You may have been expecting at this point that I would start off by detailing what exactly a factory is, but in fact, I can't really explain factories unless I explain what a constructor is. I assume if you are reading this then you must, at some level, understand object oriented programming. If you do not, may I suggest a good book on the subject matter as listed below:
However, as much as you may understand how to write software in an object oriented manner, you may not actually use constructors that much and might not truly understand the concept of constructors.
Constructors are where we place logic that happens when an object is allocated into memory and where any member variables are initialized.
Dependencies are anything the object needs to complete its intended purpose. A dependency can be a simple variable such as an integer, float, or string that can represent things like file names, account codes, and index keys; or... it can be another object that the object depends on to complete its purpose such as an SDK/API wrapper or a data access layer object. In general, anytime you use the new keyword it should be in the constructors.

However most of the code I have worked on, and for the most part a great majority of the code that I have created over the years, very rarely use constructors for anything. So, if constructors are how we should be handling dependencies why do we hardly ever use them?

You Just Don't Get Dependencies

If you are not doing the majority of your object initiation inside of a constructor then you probably just don't get dependencies. Your code is most likely littered with innocent looking new statements everywhere and I know exactly where they are, they are used exactly before you need them. In fact, most developers don't even have the common courtesy to put them at the beginning of their overly bloated methods.


An example application that does not use dependencies:

namespace MyApplication
{
    public class MyClass
    {
        public MyClass()
        {
            //I hardly ever put anything here...
        }
        public void DoSomethingCool()
        {
            var appSettings = new Object();
            //Code.....
            //Explain how to use emailSDK...
            //........
            var emailSDK = new Object();
            emailSDK.ServerAddress = "...";
            emailSDK.UseEncryption = true;
            emailSDK.Init();
            //Code.....
            string fileName = "C:\\temp\inputFileName";
            //Code....
            var myObject = new Object();
            //Code...
            emailSDK.Send(...);
        }
    }
}

The ideal solution is that your dependencies are properties/members of the base class and that your dependencies are initialized inside of your constructor. Sometimes (but very rarely), it makes more sense to initiate objects directly inside a method. However,  most of the time it just leads to bad code.


Moving your dependencies to your constructor:

namespace MyApplication
{
    public class MyClass
    {
        public MyClass(string fileName)
        {
            //This is where I set up my object for use
            AppSettings = new Object();

            //Here is how we setup the email sdk....
            var EmailSdk = new Object();
            EmailSdk.ServerAddress = "...";
            EmailSdk.UseEncryption = true;
            EmailSdk.Init();

            FileName = "C:\\temp\\inputFileName.txt";
        }
        //Its really clear what this class needs in order to do its job....
        private string FileName { get; set; }
        private Object MyObject { get; set; }
        private Object EmailSdk { get; set; }
        private Object AppSettings { get; set; }
        //---------------------------------------------------------------------
        public void DoSomethingCool()
        {
            EmailSdk.Send();
            WriteToFile(FileName);
            //You get the point
        }
        public void DoSomethingElseCool()
        {
            EmailSdk.Send(AppSettings.RegionManager);
            WriteToFile(FileName);
        }
    }
}

All of the dependency initiation logic that is placed directly at the method level instead of the constructor level are a major cause of method bloat. The second example above really demonstrates how small our methods become when the constructor is used to create objects rather than directly creating them as needed.
The side effect, when you really start to think using dependencies, is that you start solving your problems at the class level rather than the method level. If you do as I suggest in this article, then methods will be small and flexible and you will have more classes in your code then usual. That is, in my experience, a good thing because now you are thinking and writing code at a higher level.
There is much more information regarding dependencies then I care to cover in this article.

Factories Are Way Cooler Than Constructors

As cool as constructors are, factories are way way cooler. Interesting enough, once I started using factories to make better code it really taught me how to use constructors in a more constructive way.
Factories are basically constructors that are detached from the class they create. By using factories, a great deal of logic that is usually in the same class can be separated into different classes. Many times objects in your solution will contain similar dependencies. It is much easier to manage these dependencies by putting them into a common class. For instance, all Data Access Components could be using the same connection string.
This concept comes from industrial factories where products are put together at a common building (factory) so that the details of how they are constructed are not needed in order to begin to use the product. For instance, with a laptop you don't have to make the decision of what keyboard to purchase because it was placed/injected into your laptop at the factory and is not an external component like in desktop computers. This makes a laptop a much easier real life object to make use of then a desktop computer. I don't even need to plug it in...I flip up the screen and press the power button and I have a working computer.
In the same way, when I am writing a class suddenly things like file locations, dialog box methods, and application wide settings are just conveniently constructed and ready for me to use.

Factory Methods

Factory members are functions/methods that act as a constructor for an object. They are functions that return a fully functional ready to be used object. You do not necessarily need to put them inside of a special factory class. They can exist in a parent object that is not purely a factory class or it can be put inside of the object that it creates or in any object.


        public static AccountDataManager CreateAccountDataManager()
        {
            var adm = new AccountDataManager();
            adm.DataFileName = "Accounts.txt";
            return adm;
        }

Static Factory

Static factories may be the most common implementation of the factory pattern. The advantage of writing a static class with static factory methods, as shown below, is that it is a fairly easy approach and you don't have to think much about how to access the factories. You can simply call them like any other static function anywhere in you code without regard for initiating a new factory object.
For small projects this is a good approach because its easy for yourself and for other developers to understand. I also recommend that you become familiar with this approach because it is very common in existing frameworks and code in general. You will find it in both new and older code bases.


Declaring a single factory for the application:


namespace FactoryExample
{
    public static class AppFactory
    {
        public static AccountDataManager CreateAccountDataManager()
        {
            var adm = new AccountDataManager();
            adm.DataFileName = "Accounts.txt";
            return adm;
        }
        public static ContactDataManager ContactDataManager()
        {
            var cdm = new ContactDataManager();
            cdm.DataFileName = "Contacts.txt";
            return cdm;
        }
    }
}

Using the factory in your main program:


namespace FactoryExample
{
    class Program
    {      
        static void Main(string[] args)
        {
           var accountManager = AppFactory.CreateAccountDataManager();
           var account = new Account() { accountNumber = 23, Balance = 23.23M };
           accountManager.Create(account);

           var contactManager = AppFactory.CreateContactDataManager();
           var contact = new Contact() { CustomerId = 12, Name = "John Smith", Email = "jsmith200@yahoo.com" };
           contactManager.Create(contact);
        }
    }
}
Most of the time I actually create the main application as a separate class and create it in side of the "program" class using a factory method to create my application as I show below:

Declaring the factory method:


        public static FactoryExampleApp CreateApplication()
        {
            var app = new FactoryExampleApp();
            app.AccountDataManager = CreateAccountDataManager();
            app.ContactDataManager = CreateContactDataManager();
            return app;
        }

Usage of the factory:


namespace FactoryExample
{
    class Program
    {      
        static void Main(string[] args)
        {
            var app = AppFactory.CreateApplication();
            app.Run();
        }
    }
}

Single Factories or Multiple Factories

The above examples, mostly because its easier for me to write an example for, use a single factory for your entire program. I call that factory AppFactory in the above code.

Non-Static Factory

It might just be personal preference but I don't like static methods in my code. If I can help it, I will write the factories in non-static class and have them as common properties. The simplest approach, as shown below, will just require an extra new statement when you want to use the factory.

Declaring the non static factory:
    public class NonStaticAppFactory
    {
        public FactoryExampleApp CreateApplication()
        {
            var app = new FactoryExampleApp();
            app.AccountDataManager = CreateAccountDataManager();
            app.ContactDataManager = CreateContactDataManager();
            return app;
        }
        public AccountDataManager CreateAccountDataManager()
        {
            var adm = new AccountDataManager();
            adm.DataFileName = "Accounts.txt";
            return adm;
        }
        public ContactDataManager CreateContactDataManager()
        {
            var cdm = new ContactDataManager();
            cdm.DataFileName = "Contacts.txt";
            return cdm;
        }
    }

Simple usage of the factory:

namespace FactoryExample
{
    class Program
    {      
        static void Main(string[] args)
        {
            var app = (new NonStaticAppFactory()).CreateApplication();
        }
    }
}
The only thing I will say about static methods are that they are in fact pure evil. So unless you know why they are evil, then you shouldn't use them at all. In fact, what where they thinking when they allowed them in OO languages?

With non-static classes you can also put the factory into a property on the base class and inherit from it when ever you want to access its factory methods.
Factories using a base class:

    public class MyBase
    {
        public NonStaticAppFactory Factory
        {
            get
            {
                return new NonStaticAppFactory();
            }
        }
    }
    public class MyCoolClass: MyBase
    {
        public void DoSomeCoolStuff()
        {
            var dataManager = Factory.CreateAccountDataManager();
            var account = dataManager.Read(123);
            var balance = account.Balance;
            Console.WriteLine(balance);
        }
    }

It should be obvious that there are several other ways to declare and use factories. Some would prefer having a single Create method and just pass either a string or Type instance into the method to distinguish what type of object should be created.

Factories are also good for...

  • Factories are also good for managing the technique used for creating objects. For instance we might want to return a single object every time the factory method is called (Singleton pattern).
  • They can be used to return an interface or purely abstract class instead of a hard object. This is really important because many designers prefer to use abstract classes to hide details instead of private member variables. 

When should you not use Factories?

  • Your object is going to be used with an existing SDK/API that expects a constructor and does not understand factory methods.
  • Heavy usage of factories would violate the conceptual integrity of the software solution. Simply put adding factories to an existing, well written application, that does not use factories could make your code less maintainable because it is not like the rest of the system. 
  • Usage of factories is not generally accepted by the programming team and using the technique will simply add confusion when others look at your code. A manager or peer some place or somewhere might begin to say “you don't play well with others.”
  • Some software systems, for one reason or another, do not lend themselves well to factories. For instance some SDKs, such as the Microsoft .NET DOM library, require child objects to be created by their parent objects. XmlElements must be created using an XmlDocument object. Trying to force the framework into your own factory pattern can prove to be difficult and you may be better off just using the DOM as it was intended instead of adding your own flavor of factories on top of it. 
  • You have a more elegant dependency injection framework or approach. 
  • Your program is very small and factories would not really help because there are not that many dependencies to begin with. In this case, I would argue that usage of constructors vs factories is pretty much a wash. If you know how to use factories then it is no more difficult to write factories then it is to write constructors.
  • If your solution uses inheritance heavily then factories would be hard to implement everywhere. Instead it could be used for returning higher level objects or for certain parts of your solution.

Wednesday, January 22, 2014

Working with Views in Sage 300 ERP ( Accpac )

In Sage 300 ERP views are used as a standard way of manipulating and retrieving data. You will also need to use views in order to execute some commands. Views in Sage 300 closely resemble MVC and MVVM patterns that have been used when simplifying user interfaces. Becoming familiar with these patterns may help you to understand how things work in Sage 300.
Views match up closely to what you see on the Sage 300 user interface. However, you may find that the names for certain fields are not the same as you see on your screen. Most fields in Sage 300 are abbreviated and some are named completely different from the label on the forms.

Why not use the database?

If you are handy with SQL and know how to find the Sage 300 databases then you might be tempted to circumvent the SDK all together and go straight for accessing Sage via the database. Although this may be necessary in some situations, I recommend that you save this as a last resort for several reason.

The business logic will be bypassed

There is actually a lot going on behind the scenes when you are using the application. If you go straight to the database then the business logic can be bypassed. This can mean that you will have to recalculate calculated fields, updated other tables based on your changed values, and/or write your own data validation routines.
I would like to point out that this can be a problem with any application that you work with. It is typically poor practice to go straight to the database when an SDK is available. Again, if its the only way we can accomplish the task then it is acceptable.

You might corrupt the database

Sage 300 does things a little differently then standard SQL, so you may inadvertently insert a value that it does not expect. For instance a numeric field can be stored as a string and if an extra space or a leading zero is not populated correctly then you can cause unexpected results.

Distribution can be a little more tricky

If you are writing triggers, stored procedures etc. then you could make distributing your application a little difficult. For small one off solutions this might be a valid tradeoff. However, if you are distributing to several users then it can become a problem. What if you have credential problems? What if they revert to an old version of the database?

Using Views

Please refer to the previous example where we connected to Sage 300 and retrieved the current version information if you need help getting started. Instead of retrieving a version, this time we will retrieve all the data in the view. The code is as follows:

using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example2
{
    class Program
    {
        static void Main(string[] args)
        {
            //Connect to the sample company
            var accpacSession = new AccpacSession();
            accpacSession.Init("", "XY", "XY1000", "61A");
            accpacSession.Open("ADMIN", "ADMIN", "SAMINC", DateTime.Now, 0, String.Empty);

            //Open the db link. This should be the Company link type and not the system. 
            var dbLink = accpacSession.OpenDBLink(tagDBLinkTypeEnum.DBLINK_COMPANY, tagDBLinkFlagsEnum.DBLINK_FLG_READONLY);

            AccpacView view;
            int result = dbLink.OpenView("AR0024", out view);

            //This just says find all records. We pass it an empty string for the search expression
            view.Browse(String.Empty, true);
            
            while (view.Fetch())
            {
                string id = view.Fields.FieldByName["IDCUST"].get_Value().ToString();
                string name = view.Fields.FieldByName["NAMECUST"].get_Value().ToString();
                string phone = view.Fields.FieldByName["TEXTPHON1"].get_Value().ToString();
                Console.WriteLine("{0}\t{1}\t{2}\t", id, name, phone);
            }

            //Strange things will happen if you do not close both the view and the db link.
            view.Close();
            dbLink.Close();
            
            //Always close the session when you are done.
            accpacSession.Close(); 
        }
    }
}
The above example shows a very simple use case were we just want to retrieve a few fields and display them. Although you can supply filter information and let the SDK filter your data, I find it useful to grab the entire view and manipulate it using LINQ or custom code. I still use the SDK to filter data if the dataset is to large. I can, for instance, only grab records that have been modified today.
You may also find it useful to refer to the Sage 300 Data Dictionary for a reference to what fields are in what view.

Thursday, December 19, 2013

Getting Started with Accpac Programming

Recently I have accepted a new position at Kerr Consulting that specializes in integrating ERP and other financial software packages such as Quick Books with existing software. Most of our work is related to Sage products and I have been specifically tasked with becoming an expert at Sage 300 ERP (Accpac) programming.


A Simple Example

I find it difficult to find simple examples when getting started programming any new platform. So I will start out with a very basic example of how to simply connect to Accpac.

Dependencies

  • We are programming with the .NET Framework version 4.5 and MS Visual Studio 2012. There is no problem with downgrading to lower versions of .NET and Visual Studio.
  • We are using Sage 300 ERP 2012/ 6.1 for the example code. This must be installed on your system in order to write software for sage.
  • Additionally you will need to install the Sage 300 ERP SDK v2012 that should be provided for you. The installation is named SDK61A.exe in my system.

References

You must make a reference to the AccPac COM library in order to access the SDK in .NET. Under your project right click on References and click Add Reference… Then click on the COM tree node on the left hand side of the form. Check the item named ACCPAC COM API Object 1.0 and then click ok to finish adding the reference. You can see where I have added the reference to my project below:



The Code

After your reference is added to your project the below code can be used to connect to Accpac and retrieve the Application Version you are programming on.

namespace Example1
{
    class Program
    {
        static void Main(string[] args)
        {
            var accpacSession = new AccpacSession();

            //Initialize the session. You will need to pass another version instead of 61A.
            //for AppVersion. I am using 6.1A so I pass 61A here.
            accpacSession.Init("", "XY", "XY1000", "61A");

            //This is the default setup for SAMINC but it might be different on your system
            accpacSession.Open("ADMIN", "ADMIN", "SAMINC", DateTime.Now, 0, String.Empty);

            //Write out the Application Version. It should be 61A just as you passed to Init.
            Console.WriteLine(accpacSession.AppVersion);

            //Always close the session when you are done.
            accpacSession.Close(); 
        }
    }
}

Where to Get More Help


  • The best resource for SDK help is Stephen Smith’s blog. There is a ton of information there that you won’t find anywhere else including the Sage documentation.
  • There is also a wiki page for Sage 300 ERP that has a variety of examples. However, you will have to be a member of the developer network to view or updated it.




Thursday, April 18, 2013

I Knew a Programmer that Went Completely Insane

Not long ago one of our programmers just lost it and he lost it good. He walked into the manager’s office and began screaming strange things. If I didn't know him as well as I did I would have thought that he was on some kind of drug. But what had really happened was nothing short of a complete mental breakdown.

He was one of the hardest workers I had seen in the industry. He would frequently stay after hours to work on projects; He was always available when management needed someone to rush a job out over the weekend. During this time the Company was not making money and they needed the work done as quickly as possible, so any software that had to be rushed to a customer was automatically assigned to him. His willingness to push himself to get a job done is what they liked about him.

However, his productivity was not so great when he landed in a mental institution. I was the one that the company sent to visit him in the hospital to check on him after his breakdown. He asked me for a pen and a piece of paper so he could write a program down. "I think I still got it" he said, as he sat there in his hospital robe. He wrote two lines of code on the piece of paper and then began to weep uncontrollably. The company let him go after about three months in a hospital and a few threatening phone calls. He ranted about how he should be the CEO and that he was going to be the new face of the company.

 Later he spoke about how the effort he put into the company should have given him more respect and a better position. Despite being well treated and paid, for his hard work, he was still looked at as just a worker that produced well. He was never considered to be a key player in the company.

It may be hard to swallow but the extra effort and hours that you put into your job as a software developer does not usually amount to someone higher up thinking you should run the company. It has been my experience that good producers are more likely to be asked to continue to produce. If they moved you to a higher position and better pay then who would produce the software?

All too often we lose site of the human factors in software. It doesn't matter if management pushes people to overwork or if it was their own bright idea to get ahead. The result is always the same. People are just people. They are not machines that can produce day after day without some kind of human interaction. In the end everyone needs a life. 

Source

LIFE

Good Reading


Peopleware: Productive Projects and Teams (Second Edition)
This was required reading when I was going to school. It is an excellent book for both programmers and managers alike.


Death March (2nd Edition)
This is another great book on the human factor of software development. After reading this, I realized that I had been on several "death marches" myself.


Monday, April 15, 2013

Extension Methods

Extension methods in .NET are methods that can be attached to another class without changing that class. In .NET extending a class is not the same thing as inheriting from a class. Extension methods only serve as a syntax shortcut to add helper type methods to an existing type or class.

Using Extension Methods

In both C# and VB.NET you can write a static class with static members to create your own extension methods. Below is an example of an extension method called SplitByPipe that extends the system type String to support splitting the string by a pipe character.

   1:  public static class StringEx
   2:  {
   3:    public static string[] SplitByPipe(this String s)
   4:    {
   5:       return s.Split('|');
   6:    }
   7:  }
   1:  class Program
   2:  {
   3:    static void Main(string[] args)
   4:    {
   5:       string input = "string1|string2|string3";
   6:       var result = input.SplitByPipe();
   7:       Console.WriteLine(result[1]);
   8:    }
   9:  }

You can also extend generic methods. When you create a generic extension method you must add the type parameter, in this case T, to both the method name and the this parameter type name. See the below example:

   1:  public  class MyClass<T>
   2:  {
   3:    public T Value { get; set; }
   4:  }
   5:  public  static  class MyClassEx
   6:  {
   7:    public static void MyEx<T>(this MyClass<T> mc)
   8:    {
   9:       Console.WriteLine(mc.Value);
  10:    }
  11:  }

Limitations

The this reserved word before the first parameter of the string is required. It tells the compiler what class you are extending. The this keyword must also be the first parameter in the parameters list . You can add other parameters to the function but they can not have a this proceeding them.

The class and the method must both be declared static. This is a strange case where you are actually calling a static method but you usually call it using the instance of a class. If you want to call it as a static and not as an instance method than you must call it using the static class. In this case you would call StringEx.SplitByPipe(input).

You can not override a base method using an extension method. Although the compiler will not give an error, it will not work. Methods declared in the actual class will always take precedence and the custom extension will be ignored. However, if you have an extension method with the same name as a base method but different parameters, the extension method will be called and not the base method. The method signature has to be unique not the actual method name.

You can only override methods. C# does not provide any functionality to extend properties. The only alternative is to use the naming convention using methods: getMyProperty(...) and setMyProperty(...). That will not provide actual property syntax but it is standard naming when you can not use properties.

Your extension method's namespace must be included in order to show up. Just including the namespace of the base class will not import the namespace of the extension method. Extension methods are often included in a seperate assembly so you would first add the external assembly as a reference and then add the using statements to your codebase.

Why Use Extension Methods

While extension methods are in no way required to make a good .NET application they are very useful when it comes to writing utility type functions on an existing framework or even within your own code base. It is usually not considered best practice to inherit off of common and built in types like String and Integer. Doing so can make your code less portable and non-standard.

It is also worth mentioning that some classes in C# are sealed so you can not extend them using inheritance and you would have to explicitly declare them as partial in order to add to the class using a partial.

When Should You NOT Use Extension Methods

Extension methods can help you to avoid incrimenting a version number on a assembly by allowing modification to your class outside of its actual library. MyLibrary.dll might contain the core functionality while MyLibraryEx.dll would include extensions to that library. This can make sense when the extensions are not required in the core library and they logically fit together. However, if your only goal is to avoid recompiling an assembly than it is not a good idea. Multiple libraries that do not go together will only serve to complicate your references and make it difficult during deployment and troubleshooting.

If you are generating code using t4 or other scripting languages than a partial is more appropriate. A partial will give you more power and flexibility when you control the actual base class.

Inheritance may be more appropriate if the functionality fits more into the actual core requirements of your software and are always required. For instance if you have an animal super class and both feline and canine sub classes than it would make more sense to use inheritance instead of implementing feline and canine extension methods.

As with any programming feature, it can be overused and abused. If more of your solution is extension methods than other types of code than you may be overusing them. Generally my solutions only have a few extension methods that are used when I think the core framework should have implemented something or when it just makes the program easier to read.

What About Before Extension Methods

Before extension methods plain old static classes were used and the programmer would just pass an instance of the class into the static method. These are often called helper methods or helper classes. Helper methods are still in use even with the introduction of extension methods.

More Tips

  • You can implement more than one extension method type in one class. It is possible to extend both String and Integer within the same static class.
  • There is no naming convention enforced by the compiler. Extension classes do not have to end with Ex and the file does not have to end with Ex either.

Sources


More Resources


C#/.NET Little Wonders: Extension Methods Demystified


Updated: Generics can be extended. I removed it from the limitations.

Friday, April 12, 2013

Why You Shouldn't Use Privates Anymore

For nearly half of my career I thought that hiding member variables and methods with private and protected was one of the best ways to write better code. You have probably been taught in school or have read several well written articles of why using private makes your code better.
In theory hiding the details of the class using a private can have the following benefits:

  • Reduces the complexity of the code by limiting communication between modules.
  • Hides implementation details so that you can focus on the what instead of the how.
  • Prevents access to dangerous variables that could unintentionally cause the class to break.
  • Reduces the scope of a member to just your class.

All though I have found that the above are true there are an equal amount of negative consequences for using private scoped members. The negative impact of this design choice, in my opinion are far worse than the actual positives involved. There are other ways to achieve the above goals without the usage of private members.

Limiting communication between modules is a concept that comes from a psychologist named George Miller.  Millers Law basically states that human beings on average can not handle more than 5 plus or minus 2 ideas, entities or objects at one time. I am always aware of this basic principle when designing both user interfaces and when coding.

It is not necessary to lock the inner workings of the class up so that no one can see whats going on inside. If you opened the hood of a car it wouldn't help for them to hide the spark plugs so you couldn't see how it works. Limiting communication between modules and hiding implementation details can be achieved by using either a purely abstract class or an interface.

Using interfaces to communicate between modules it turns out solves a-lot of the problems that private variables where solving. So the question is why do both? Well, it turns out that most developers have not been using interfaces for this purpose. It was not until Test Driven Development came along that private members have become the enemy.

The main reason that TDD hates private members is due to its negative impact on the test-ability of a class. TDD coders like to take a class and write test code that changes variables, and dependencies in order to run automatic scenarios to verify its functionality. If members and variables are private it only serves to make unit testing harder. Due to the fact that test-ability was not a key metric in traditional software engineering methodology, this was overlooked.

Preventing access to dangerous variables may save some headaches in some situations. However, I think that we should let the developers decide what they should or should not be accessed. If the developer is not accessing an interface and has access to the implementation than changing the wrong variable is not the responsibility of the original class creator.

In practice I have seen private variables cause entire classes to be re-written when all that was needed was an override of a single member variable or a trivial function. There is no doubt that the intent in those cases was to prevent developers from tinkering with things they shouldn't be. Why are we arbitrarily deciding what should or should not be "override-able" in our base classes?

If you really want to reduce the scope of a member variable than interfaces are the way to go. I don't care about the scope of a class member if it is not an interface. So let your interfaces handle communication and stop trying to force good developers from solve problems within your solutions.


Tuesday, April 9, 2013

Do I Need a Degree to Write Software?

Many people over the years have asked me if they need a degree in Computer Science to get a programming job. Technically a degree is in not required to be a programmer. However, I believe that the degree program that I completed was invaluable to my career.

Most all jobs I have applied for consider 5 years experience in the field as equivalent to a degree. I once thought that only programmers with degrees really have a well rounded background in in the fundamentals. But despite my belief in the core curriculum as minimum of skills required to be a good programmer, I have known good developers with no degree that knew all the fundamentals. I also have seen developers with excellent degrees that did not know the first thing about coding.

The real asset that you get from completing a degree in Computer Science is from the actual knowledge you acquire and the guidance you get from experienced professionals that have studied the subject at length. If you just learned how to dupe the professors and you never truly learned what they were teaching than it will most likely be found out in the interview process.

I could care less about the degree you have when I am involved in hiring developers. Would I care about is what you know. If you managed to get to the interview and you don't have a degree than it means I don't care. What I do care about is that you have the ability to write good code and you  have an understanding of everything from Computer Architecture to Software Engineering. You don't need to go to school to do that but it may help to have a structured learning environment.

There are some places that will not consider non-degree developers. I find that very rare in the industry. Once you have the experience, most places will not look at the degree or lack thereof. Having said that, not having a degree could limit your options and may mean that someone else with the same qualifications and experience gets the job and you don't.

If you do decide that school is just not for you than set yourself on a path to being a competent Software Professional by making your own learning plan.  Because you don't have to worry about classes that are not directly related to your profession you can focus all of your energy on Computer Science Subjects. The following is a minimum for a programmer to know:
  • Learn Assembly - Some developers sware that learning assembly first is the best way to be a good developer.  This is because all other languages just translate into binary and assembly is just a human readable form of binary.
  • Programming 101 - Pick up a bug on beginning programming in C#, VB.NET, Java or whatever language you want to use. I would suggest a strong type language for your first Language.
  • Object Oriented Programming - OO is everywhere right now and even if you don't like it you will need to at least understand it. I don't like how OO is mixed in to basic programming classes. A good book to start learning OO is The Object Oriented Thought Process.
  • Advanced Programming - Once you think you have mastered basic programming then move on to a more advanced book on the same language. Go past just basic for loops and variable assignments.
  • Data Structures - You need to implement your own data structures in order to write real world applications. Chances are that you will not actually write these data structures but you will use 3rd party implementations of hash tables, linked lists, stacks and tree structures etc. You don't want to learn this on the fly and it should be mastered before attempting more advanced programming subjects.
  • Computer Architecture - Learning what the underlying workings of a computer can help when programming. You don't need to be an electrical engineer but a basic knowledge of and gates, boolean logic, assembly language etc will help you down the road.
  • Client Server Architecture - Learn the ins and outs of how the web works. Even if you don't want to be a web developer, everything is online now days. You need to know how to call web services and hook into online api. Understand how TCPIP works and know "How the Web Works".
  • Object Oriented Design - Get a good book on pure object oriented design and become best friends with it. Take it to lunch and hang out with it when you get off of work. The reason is you will be using it everywhere in software. You can program with only a shallow understanding of OO but a deep knowledge will let you use 3rd party tools and api's to there max potential.
  • Traditional Software Engineering - Pick up an older book on software engineering and spend a good amount of time mastering the subject. Looking on the internet is probably not going to help here. Structured Design is a must read in my opinion. The software industry is really split three ways between companies who use no methodology, ones who use traditional approaches, and ones who use Agile processes.
  • Agile Development - Agile development is used heavily. Knowing what you are talking about in this area is important. Agile and traditional techniques but heads. Even if you think agile is the only way to do things its best to have a full understanding of the traditional techniques. This is because Agile is really takes a-lot from the lessons of traditional engineering.
  • Project Management - Even though you are a programmer and may never manage a project you need to know how software should be managed. Software Project Management is radically different from traditional Management. There is a range of techniques so don't just take one as law. The Mythical Man Month is an absolute must in my opinion. Also read books on agile project management.
  • Database Management - Although its helpful to learn SQL statements you need an academic book on the fundamental design of databases. This should teach you how to spot a bad database and how to fix it. It will help you make decisions on how to write your own tables etc. This is good as a last course because engineering plays into this.
  • User Experience - There are many books written on ui design and user experience. I would suggest reading several of them. In addition there are standards written by Microsoft and other large companies. Take advantage of millions of dollars worth of research and read what they have to say. There is nothing worse than a bad user interface to a software package. Even if you don't make user screens this can help you write better software.
  • Learn a core API/SDK - While you are trying to master other subjects make sure to learn a core industry api for what you want to develop. For me this is a user interface api such as winforms/ASP.NET or WPF. However, you may not be writing user interfaces maybe this means a graphical api like GTK or DirectX. Perhaps it means diving deeper into low level driver programming or mastering an SQL variant.
Mastering a subject takes more effort than just casual reading. Don't just read a book but study it. This means reading the same chapter over and over. Quizzing yourself on the subject. Learning does not take place within a short period of time. Read a book all the way and then spend a set amount of time really mastering what it says. Programming is learned by doing and not by reading. If the book has practice exams and exercises do them all. I can guarantee that the real world will have harder tests than the ones in your book.

While you are trying to master the art of programming you should be looking for an entry level position. If you can't find one than start your own open source project or even a project for money on your own. Even if you fail or get fired don't give up. I wrote my first program when I was 15 before I went to school. It is that experience that has helped me to get into the profession.

You should be looking to fulfill that 5 years of experience. Pay is not that important when you first start out. Experience matters, if you can get yourself in the door with a company than hold on until you feel you can get hired elsewhere.

related blogs:
do you need a degree for game dev