Saturday, May 9, 2009

An introduction to Microsoft .NET and Object Oriented Programming (OOP)

First proper techy post! :)

The purpose of this series of blog-post is going to be as follows:

  • To give beginners a few insights into how to program software using .NET programming languages (especially C#) and the .NET framework.
  • To help people understand why object orientated programming (OOP) is a powerful approach to software development.
  • To help people understand how OOP is supported by the .NET framework and the languages hich run inside the .NET CLR.
  • To provide some context about the run-time context of .NET applications, software architecture and design patterns and principles.
  • Some interesting coding scenarios and challenges.

To help me wrap my own head around the topics I'm going to blog about. Like they say - there's no better way to learn than to teach, right?

What this blog series will not deliver:

  • Comprehensive coverage of the entire .NET framework - sorry, but I don't want to still be blogging about IT on my 300th birthday.
  • DEEP coverage of object orientated programming practices... I'll try to provide useful examples, but I'm not going to go into the computer science behind every design pattern I introduce.
  • Authoritative advice for people who are already experienced software engineers. (There's already millions of sites out there for you folks!)
  • Guaranteed 100% rock solid "best practices" - I'm going to try to ensure that some of my practices will be at least "okay" and that others might even border on "good", but my advice is simply my advice... I'm not aiming to lay down "The Truth" in any singular, absolute or even expert way.

Some other stuff this blog series will contain now and then...

  • Audio discussions of various high level principles.
  • Video demonstrations of the principles outlined in the blog, including code walkthroughs and discussions of some of the design decisions behind the code.
  • Interviews from other members of the developer community - potentially including conference and/or user group demos and speeches.
  • Source code demonstrating the points I'm outlining in the blog.
  • Reviews of .NET programming books, training and other .NET resources (e.g. starter kits, CodePlex projects, tools & utilities)
  • References to good design practices for other platforms (e.g. SQL Server, BizTalk, WCF, etc)

So - that's the preliminaries done with. Now on to the meat of the matter!

Many people may hear a developer talk about the .NET framework and will tell them "Oh - that's all about web services, right?" If they repeat that question to a Microsoft marketing drone, they'll get applause! But for those of us working with software on a daily basis, the .NET framework is basically an abstraction layer that sits over the top of an operating system (Windows for those of you not using Mono or tinkering with the project formerly known as Rotor - more about those later!).

  • The .NET Framework provides a centralized set of visual controls, class libraries, object factories and more that allow developers to write applications without having to learn C++, COM and the Windows API - all of which are very difficult to work with, and prone to catastrophic errors when poor practices are used.
  • The .NET framework is extensible (many of the classes are not sealed, so are freely inheritable - especially many of the visual controls - great for custom control developers!) and probably one of the best documented software frameworks I've ever seen.
  • The .NET framework can be used to develop "ASP.NET" web applications (requiring Microsoft's IIS hosting platform), which render a mixture of server-side controls (i.e. their logic and rendering is all managed directly by ASP.NET) and native HTML controls. Server-side controls are rendered as native HTML in the stream sent to the client browser.
  • The .NET framework can be used to build standards compliant web services. Web services allow systems on different platforms to interoperate cleanly in a standards-based manner over the internet. If you've made a credit card payment online, odds are that the software that accepted the submission of your transaction and sent back an approval notice was a web service! Web services can be used for all sorts of things - ranging from social networking to weather reports, from stock market quotes to media streaming. The key point to understand here is that a web service won't display itself in a browser, but still uses HTTP (or HTTPS) as its communication protocol.
  • The .NET framework can be used to develop powerful, scalable enterprise applications that integrate cleanly not only with other Microsoft applications platform services (e.g. BizTalk, SQL Server, Exchange, SharePoint), but with other more generic toolsets as well (e.g. Websphere MQ, Oracle databases, Tibco's Enterprise Messaging Service, and so on).
  • The .NET framework can also be used to build, manage, automate and deploy rich Windows applications, including those using the new "Windows Presentation Foundation" interface controls introduced in Windows Vista and with the Microsoft Office business productivity suite.
  • The .NET compact framework (once described by Rory Blyth of .NET Rocks fame as "A wrapper around the System.NotImplementedException object") allows the development of mobile web applications, rich client mobile applications and even mobile games.
  • Finally, the .NET framework can be used to develop console applications and "lights out" services that run happily on Windows without the need for fancy GUIs.

What does all this mean to me? The power to get the job done, wherever the data, wherever the user.

Digging a little deeper... Microsoft's .NET platform has been designed explicitly to support object orientated programming and design (OOPD). COM and the Win32 API provided a rich framework of objects which could be manipulated using external code, but the pointer arithmetic was dangerous and you had to get that right with your base objects. If you inherited from flaky base objects, all of your inherited code would be at risk. This is one of the things that led to a lot of vulnerabilities in Microsoft's flagship Windows operating system over the late 90s and early years of the current decade. C++ is very powerful, but it also requires an INSANE degree of attention to detail.

So... what is all this object orientation stuff? How does it work? What does it do for me? The key points are as follows:

  • OOP allows developers to model real life THINGS based on the things they have in common. For example, mammals tend to have 4 limbs, 2 eyes - usually forward facing, two ears - typically capable of rendering hearing in a stereoscopic field, fur/hair/bristles, and teats to suckle their young on milk. However, it's possible to refine the definition of Mammal by breaking down additional definitions by genus, species, etc... in which the more specific refined models either override the base definition, or embellish it.
  • As an example of this form of embellishment, consider the felidae family, which contains most of the cats. The felidae family can be categorized into subfamilies such as pantherinae ("big cats" such as tigers, leopards, panthers and lions), acinonychinae (cheetahs), felinae (typically smaller cats) - each of which has distinguishing characteristics and behaviours.
  • The pantherinae are much larger and heavier than the other felidae subfamilies, for example. The cheetah has non-retractable claws and a super-flexible spinal column. Where the big cats are all capable of roaring, the cheetah "yips" and yowls. Cheetahs have longer tails than their cousins, but shorter body-length to leg-length ratios.
  • In the context of obejct orientated programming, a characteristic of a "Type" of thing is called an attribute of that thing, and the type itself is called a "Class". So in our feline example, "Felidae" would be a class of cats, in which the features common to all cats would be included as attributes. These would include the number of legs (4), type, number and distribution of teeth, stereoscopic vision, pivoting ears, good night vision, meat diet, and so on. The features specific to a "descendent" class of "pantherinae" would include higher maximum weight and length attributes than the class "felinae", a different list of preferred prey, and so on.
  • Howerver, cats don't only have attributes - they also have behaviours. Cats can stalk, run, leap, climb, eat, poop, and so on. There may be attributes that are specific to the behaviours of a specific class of felidae (e.g. Cheetahs have a higher maximum speed when running than other cats) which can be encapsulated (I'll get back to encapsulation in another blog) in the definition of their behaviours. In OOP these descriptions of behaviours are known as methods. This is because a software program executes a series of steps in a systematic order to model/perform the behaviour concerned.
  • So now we have the idea of a class that has methods and attributes. The attributes are qualitative or quantitative descriptors of a type's characteristics. The methods are the type's behaviours. However, this is only a model right now. We haven't created a specific cheetah, lion or manx cat yet. When we talk about object orientated programming, the key objective is to perform operations on objects which can be described as specific instances of a class.
  • Consider the cat you may or not have had when you were growing up. Let's arbitrarily call this cat "Fluffy". Fluffy is an instance of the felinae class. As a member of the felinae class, it knows how to do all the usual catty things (yawn, stretch, eat, sleep, schmooze for food, throw cat-litter out of the box, stalk balls of wool, upset mother) and it probably has the usual characteristics of a typical house cat. In OOP we define instances of a class as objects, and we have now arrived at what OOP is named for.
  • If I want to write a program to estimate the calories Fluffy burns each day, I would start by creating an instance of the felinae object called "Fluffy". If I knew Fluffy's schedule well enough I could then execute each of the methods on the Fluffy object to obtain a total for the amount of calories burned. Of course, the methods would have to return a calorific figure (which in itself is a specific "type" of information) after invokation, and would probably need to provide the method with a "time" value (or parameter) defining the amount of time spent by fluffy on each activity.
  • The type returned by a method and the types and parameter names (which are really just placeholders) passed to a method comprise its signature. You shouldn't be able to pass a dollar amount to the time parameter of fluffy's AnnoyMother method - it doesn't make sense. Likewise, returning Fluffy's name after calling the Yawn method won't help me figure out whether I need to put him on a diet or not - as such, it would be an invalid return type.
  • Type safety is one of the big pluses in the .NET framework. This means it will make sure you are passing the right kinds of types in and out of methods and throw a warning message (exception) if you try to pass something that doesn't make sense.

Now that I've got you that far, I'm going to call it quits for the night. Next time I'll start off with a discussion of some additional OOP concepts (encapsulation, obfuscation, polymorphism, inheritance and operator overloading) and might throw in some C# code demos to illustrate each of these concepts. This has been a very high level discussion for those who've never really grokked what OOP is all about. I'll start moving through the concepts more quickly in future posts.

No comments:

Post a Comment

Feel free to comment liberally and severally. Note that spam comments will be deleted, and if spam reaches critical mass I may restrict comments to authenticated users.