Archive

Archive for November, 2008

Application architecture with design patterns

November 12, 2008 Leave a comment

 

A design pattern can solve many problems by providing a framework for building an application. Design patterns, which make the design process cleaner and more efficient, are especially well-suited for use in C# development because it is an object-oriented language. Existing design patterns make good templates for your objects, allowing you to build software faster. This article describes several popular design patterns you can use in your own applications, including the singleton, the decorator, the composite, and the state classes, which can improve the extensibility of your applications and the reuse of your objects.

As any seasoned object-oriented software developer knows, it is unthinkable to discuss software design and architecture without at least a rudimentary understanding of design patterns. Most, if not all, software applications, tools, and systems incorporate one or more design patterns. A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development. Additionally, patterns take into account design constraints and other factors that limit their applicability to the solution in general. Together, the classes, the communication and interconnections among those classes, and the contextual specifics define a pattern that provides a solution to any problem in object-oriented software design that presents characteristics and requirements matching those addressed by the pattern context.

Few developers have the luxury of writing only small programs. Modern software applications and systems are complex, comprising hundreds of thousands of lines of code, and I know of code bases that are even larger. Programming demands a lot more than simple mastery of tools and languages—corporate software development typically requires a great deal of flexibility in design and architecture to accommodate the ever-changing needs of clients and users at various stages of product development, and often after the product has been released. Such dynamics dictate that software design not be brittle. It should be able to accept changes without any undesirable ripple effect that would necessitate the reworking of other, potentially unrelated, subsystems. It is frustrating and counterproductive to add features and components to modules that were never designed for extensibility. Sooner or later, closed, inflexible designs break under the weight of changes. Design patterns assist in laying the foundation for a flexible architecture, which is the hallmark of every good object-oriented design.

Design patterns have been cataloged to address a variety of design problems, from small issues to large, architecture-level problems. In this article, I will describe some of the popular design patterns that I have found useful in my own projects. The article does not assume any prior knowledge of design patterns, although familiarity with concepts of object-oriented design will help. While any programming language that facilitates object-oriented development could be used to illustrate patterns.

C# and Design Patterns

C# is a modern programming language that promotes object-oriented software development by offering syntactic constructs and semantic support for concepts that map directly to notions in object-oriented design. This is in contrast to C++, which supports procedural as well as object-oriented (and generic) programming. Nonetheless, if you are a C++ programmer, getting up to speed with C# should be a snap—the learning curve for C++ programmers is flat. Even if you haven’t seen any C# code before, you should have no problem comprehending the example code in this article. In fact, I wouldn’t be surprised if you find the C# implementation of the design patterns cleaner, especially if you have used or coded the patterns before. Books and articles that discuss design patterns typically explain the problem and the context in great detail, followed by a formal description of the solution.

Let’s start with the simplest design pattern: Singleton.

Singleton

Anyone who has ever written an MFC application—no matter how small—knows what a singleton is. A singleton is the sole instance of some class. To use an MFC analogy, the global instance of the CWinApp-derived application class is the singleton. Of course, while it’s imperative that no additional instances of the application class be created, there really is nothing preventing you from creating additional instances. In situations like these, when you need to enforce singleton behavior for a specific class, a better alternative is to make the class itself responsible for ensuring that one and only one instance of the class can be created. Back in the MFC analogy, you see that the responsibility for keeping track of the solitary instance of the application class rests with the developers of the application. They must not inadvertently instantiate another application object.

It is most often the case that the singleton should also be globally accessible, and this is achieved by making the creation method public. However, unlike the scenario in which a global variable is instantiated as the singleton, this pattern prevents creation of any additional instances, while simultaneously allowing global access. Note that the class constructor is private—there is no way to circumvent the static method and directly create an instance of the class.

There are additional benefits, too. Specifically, this pattern can be extended to accommodate a variable number of instances of an object. For instance, let’s say you have an application with a dedicated worker thread that is dispatched whenever a particular task is required. In the interest of conserving system resources, you have implemented the thread as a singleton. At some point along the way, if you decide to scale up your application because the rate at which tasks arrive is too much for your singleton thread to handle, it will be fairly straightforward to increase the number of worker threads in the application because all the logic that creates the threads and grants access to them is confined to one class.

One other advantage to this pattern is that creation of the singleton can be delayed until it is actually needed.

A variable declared at global scope will be created on startup regardless of whether it is needed—it may very well be that the object isn’t always needed. C# doesn’t allow variables at global scope anyway, but it is possible to create an object on the heap at the outset of a method and not use it until much later, if at all. The Singleton pattern offers an elegant solution in such cases.
      Additionally, as an implementation vehicle, C# is superior to C++ for this design pattern in a subtle but important way. A C++-based implementation has to take into account some sticky issues related to lifetime management that are automatically taken care of by the C# runtime. This is a significant benefit, as all you need to do in the C# version is make sure you have a live reference to the singleton object for as long as it’s needed.

Strategy

Applications are often written so that the way they perform a particular task varies, depending on user input, the platform it’s running on, the environment it’s been deployed in, and so on. An example is asynchronous I/O on disk files: Win32® APIs under Windows NT® and Windows® 2000 support asynchronous I/O natively. However, that’s not the case with Windows 95 or Windows 98. An application that relies on asynchronous file I/O, therefore, has to execute two different algorithms, depending on the deployment platform—one that uses native Win32 APIs, and another that is built from scratch, perhaps using multiple threads. Clients of such a service will be oblivious to the fact that different algorithms are being executed; as far as they are concerned, the end result is the same and that’s all they care about.
Another example is downloading a file from some remote server on the Internet. An application that offers a file download service that accepts a URL as input needs to examine the URL, identify the protocol (FTP or HTTP, for example), and then create an object that can communicate with the remote server using that protocol. Note that depending on user input, a different algorithm (protocol) will be used. However, again, the end result is the same—a file is downloaded.

An interface is like a contract. It is a specification that inheriting classes must follow. More specifically, it defines method signatures but no implementations—the latter must be provided by the concrete classes that implement the interface. C# is clearly superior to C++ in this regard because C++ lacks native language support for interfaces. C++ programmers typically create interfaces by defining abstract classes with pure virtual methods. In C#, all interface members are public, and classes adhering to an interface must implement all methods in the interface.

Decorator

A client application often needs to augment the services provided by methods of some class, perhaps by inserting some preprocessing and post-processing tasks before and after the method calls, respectively. One way to accomplish this is to bracket each method invocation with calls to functions that achieve the desired effect. However, this approach is not only cumbersome, it also limits the framework’s extensibility. For instance, if distinct pre- and post-processing tasks were to be carried out for different clients, the application logic would be obscured by conditional statements, leading to a maintenance nightmare. The question, then, is how to enhance the functionality offered by a class in a manner that does not cause repercussions in client code. The Decorator pattern is just what’s needed.

The Decorator pattern thus allows dynamic and transparent addition and removal of responsibilities without affecting client code. It is particularly useful when a range of extensions or responsibilities can be applied to existing classes, and when defining subclasses to accommodate all those extensions is impractical.

Composite

The Composite pattern is useful when individual objects as well as aggregates of those objects are to be treated uniformly. An everyday example is enumerating the contents of a file folder. A folder may contain not only files, but subfolders as well. An application designed to recursively display the list of all files in some top-level folder can use a conditional statement to distinguish between files and directories, and traverse down the directory tree to display the names of files in the subfolders. A better approach is suggested by the Composite pattern. In this approach, every folder item, be it a file, a subfolder, a network printer, or a moniker for any directory element, is an instance of a class that conforms to an interface offering a method to display a user-friendly name of the element. In this case, the client application does not have to treat each element differently, thereby reducing the complexity of the application logic.

The implementation of Drawing.Draw uses the collection classes available in the System.Collections library. For more information on these and other libraries, check out the documentation in the .NET Framework SDK.

State

Every developer has implemented a finite state machine at least once. You can’t avoid them—they are everywhere, and not just limited to the world of software development. It’s no wonder that literature on the design and implementation of deterministic finite automata is also readily available. A popular design for finite state machines is based on table lookup. A table maps all possible inputs for each state to transitions that would lead the machine to perhaps a different state. Needless to say, while this design is simpler, it is unable to accommodate changes without significant modifications to the existing implementation. A better alternative is the solution offered by the State design pattern.

To summarize, the State design pattern helps localize state-specific behavior to classes that implement concrete states, which promotes reuse and extensibility. This removes the need for conditional statements that would otherwise be scattered throughout the code, making life difficult for maintenance programmers, who vastly outnumber implementers in the real world.

– Pull – MSDN

Advertisements
Categories: Architecture

Lorenzo the magnificent

November 8, 2008 Leave a comment

 

A portrait of Lorenzo de’ Medici by Girolamo Macchietti.

Born : January 1, 1449(1449-01-01)

Died : April 9, 1492 (aged 43)

Spouse(s) : Clarice Orsini
                  Philippina of Savoy

Children : Lucrezia de’ Medici
               Piero di Lorenzo de’ Medici
               Maddalena di Lorenzo de’ Medici
               Giovanni de’ Medici
               Luisa de’ Medici
               Contessina de’ Medici
               Giuliano di Lorenzo de’ Medici

 

Lorenzo de’ Medici (January 1, 1449 – 9 April 1492) was an Italian statesman and de facto ruler of the Florentine Republic during the Italian Renaissance. Known as Lorenzo the Magnificent (Lorenzo il Magnifico) by contemporary Florentines, he was a diplomat, politician and patron of scholars, artists, and poets. His life coincided with the high point of the early Italian Renaissance; his death marked the end of the Golden Age of Florence. The fragile peace he helped maintain between the various Italian states collapsed with his death; two years later the French invasion of 1494 began and led to nearly 400 years of foreign occupation of the Italian peninsula.

Childhood:

His grandfather, Cosimo de Medici, became the first of the Medici to combine running the Medici bank with leading the Republic in both government and philanthropy, spending an enormous portion of his fortune (he was one of the wealthiest men in all of Europe) on art and public works. Lorenzo’s father, Piero ‘the Gouty’ de’ Medici, was also at the center of Florentine life, and extremely active as a patron and collector. His mother Lucrezia Tornabuoni was also a dilettante poet and friend to figures like Luigi Pulci and Agnolo Poliziano.

He was considered the brightest of the five children. He was tutored by Gentile Becchi, a diplomat. He partook in jousting, hawking, hunting, and breeding horses for the palio, a horse race in Siena. His own horse was named Morello.

Piero sent Lorenzo on many important diplomatic missions when he was still a youth. These included trips to Rome to meet with the pope and other important religious and political figures.

 

Lorenzo and politics

Bust of Lorenzo de’ Medici by Verocchio.

Lorenzo, groomed for power, assumed a leading role in the state upon the death of his father in 1469, when Lorenzo was twenty. Lorenzo had little success in running the bank, and its assets contracted seriously during the course of his lifetime.

Lorenzo, like his father and grandfather, ruled Florence indirectly, through surrogates in the city councils, through threats, payoffs, strategic marriages – all the tools of despotism, Although Florence flourished under Lorenzo’s rule, he effectively ruled as a despot and people had little freedom. It was inevitable that rival families should harbor resentments as to Medici dominance, and enemies of the Medici remained a factor in Florentine life long after Lorenzo’s passing.

On Easter Sunday, April 26, 1478, in an incident called the Pazzi Conspiracy, a group including members of the Pazzi family, backed by the Archbishop of Pisa and his patron Pope Sixtus IV, attacked Lorenzo and his co-ruler brother Giuliano in the cathedral of Florence. Lorenzo was stabbed but escaped; however the attackers managed to kill Giuliano. The conspiracy was brutally put down, with measures including the lynching of the archbishop.

In the aftermath of the Pazzi conspiracy and the punishment of the Pope’s supporters, the Medici and Florence suffered from the wrath of the Pope. He seized all the Medici assets he could find, excommunicated Lorenzo and the entire government of Florence, and ultimately put the city under interdict. When that had little effect, the Pope formed a military alliance with King Ferdinand I of Naples, whose son, Alfonso, Duke of Calabria launched an invasion.

Lorenzo rallied the citizens. However, with little help being provided by traditional Medici allies in Bologna and Milan (the latter being convulsed by power struggles among the Sforza), the war dragged on, and only diplomacy by Lorenzo, who personally traveled to Naples, resolved the crisis. This enabled him to secure constitutional changes that enhanced his power.

Thereafter, Lorenzo, like his grandfather Cosimo de’ Medici, pursued a policy of maintaining both peace and a balance of power between the northern Italian states and of keeping other states out of Italy.

Lorenzo kept good relations with Mehmed II of the Ottoman Empire, as the trade with Ottomans was a major source of wealth for the Medicis.

 

Lorenzo and the Renaissance

Lorenzo’s court included artists such as Piero and Antonio del Pollaiuolo, Andrea del Verrocchio, Leonardo da Vinci, Sandro Botticelli, Domenico Ghirlandaio, and Michelangelo Buonarroti who were involved in the 15th century Renaissance. Although he did not commission many works himself, he helped them secure commissions from other patrons. Michelangelo lived with Lorenzo and his family for several years, dining at the family table and attending meetings of the Neo-Platonic Academy.

Lorenzo was an artist himself, writing poetry in his native Tuscan. In his poetry he celebrates life even while—particularly in his later works—acknowledging with melancholy the fragility and instability of the human condition. Love, feasts and light dominate his verse.

Cosimo had started the collection of books which became the Medici Library (also called the Laurentian Library) and Lorenzo expanded it. Lorenzo’s agents retrieved from the East large numbers of classical works, and he employed a large workshop to copy his books and disseminate their content across Europe. He supported the development of humanism through his circle of scholarly friends who studied Greek philosophers, and attempted to merge the ideas of Plato with Christianity; among this group were the philosophers Marsilio Ficino and Giovanni Pico della Mirandola.

Later years

A posthumous portrait of Lorenzo by Giorgio Vasari

During his tenure, several branches of the family bank collapsed because of bad loans, and, in later years, he got into financial difficulties and resorted to mis-appropriating trust and state funds.

Toward the end of Lorenzo’s life, Florence came under the spell of Savonarola, who believed Christians had strayed too far into Greco-Roman culture. Lorenzo played a role in bringing Savonarola to Florence.

Lorenzo de’ Medici died during the night of April 8th/9th, 1492, at the long-time family villa of Careggi (Florentine reckoning considers days to begin at sunset, so his death date is the 9th in that reckoning). Savonarola visited Lorenzo on his death bed. The rumor that Savonarola damned Lorenzo on his deathbed has been refuted by Roberto Ridolfi in his book, Vita di Girolamo Savonarola. Letters written by witnesses to Lorenzo’s death report Lorenzo died a consoled man, on account of the blessing Savonarola gave him. As Lorenzo died, the tower of the church of Santa Reparata was allegedly struck by lightning. He and his brother Giuliano are buried in a chapel designed by Michelangelo, the New Sacristy; it is located adjacent to the north transept of the Church of San Lorenzo and is reached by passing through the main Capella di Medici; the chapel is ornamented with famous sculptures, and some of the original working drawings of Michelangelo can still be distinguished on two of the walls.

He died at the dawn of "The Age of Exploration"; Christopher Columbus would reach the "New World" only six months later. With his death, the center of the Renaissance shifted from Florence to Rome, where it would remain for the next century and beyond.

Marriage and children

Lorenzo married twice.

Lorenzo first married Clarice Orsini by proxy on February 7, 1469. She was a daughter of Giacomo Orsini, Lord of Monterotondo and Bracciano by his wife and cousin Maddalena Orsini. They had nine children:

Lucrezia di Lorenzo de’ Medici (August 4, 1470 – November, 1553). She married Giacomo Salviati. Their daughter Francesca Salviati was mother to Pope Leo XI.
Piero di Lorenzo de’ Medici (February 15, 1471 – December 28, 1503).
Twins born in March, 1472. Died shortly after birth.
Maddalena de’ Medici (July 25, 1473 – December, 1528). Married Franceschetto Cybo, an illegitimate son of Pope Innocent VIII.
Pope Leo X (born Giovanni de’ Medici; December 11, 1475 – December 1, 1521).
Luisa de’ Medici (1477 – 1488). She was betrothed to her cousin Giovanni de’ Medici il Popolano.
Contessina de’ Medici (1478 – 1515). Married Piero Ridolfi.
Giuliano di Lorenzo de’ Medici, Duke of Nemours (March 12, 1479 – March 17, 1516).
After Clarice’s death, he married Philippina (Philippa) of Savoy, daughter of Philip II, Duke of Savoy. The couple had no children.

Two of his sons later became powerful popes. His second son, Giovanni, became Pope Leo X, and his adopted son Giulio (who was the illegitimate son of his slain brother Giuliano) became Pope Clement VII.

His first son and his political heir, Piero ‘the Unfortunate’, squandered his father’s patrimony and brought down his father’s dynasty in Florence. Another Medici, his brother Giovanni, restored it, but it was only made wholly secure again on the accession of a distant relative from a branch line of the family, Cosimo I de’ Medici.

-Courtesy – wiki

Categories: Books, Miscellaneous

Office Politics

November 8, 2008 Leave a comment

Most IT failures are driven by hidden dynamics related to political, organizational, and cultural issues. IT failure rates remain high precisely because these factors are difficult to measure, quantify, understand, and manage.

In a recent Gartner Symposium session, analyst Tina Nunno spoke about the role of office politics in contributing to failed IT projects. From the description of Nunno’s session:

While technologies can be installed, configured and retired, the level of complexity is minimal in comparison to the complex political situations each and every CIO must face.

Ian Grant from Computer Weekly attended the session and blogged:

CIOs are competing with their colleagues in other areas of the business for control, resources, status and power. Any and all of these are potential flashpoints for the unwary CIO because the shifts in these areas indicate winners and losers, Nunno said.

Nunno recommended CIOs take a look at Machiavelli, whose The Prince, a handbook on how to acquire and hold power has been bedtime reading for leaders since Lorenzo the Magnificent, for whom it was written.

“IT is frequently in a difficult position because we cross the entire organization,” she said. This breadth of vision means CIOs often know better what is going on than their colleagues, and this can lead to jealousy and negative behavior, she said.

THE PROJECT FAILURES ANALYSIS

Politics is the hidden killer of the IT world and Nunno correctly asserts that CIOs should become more sensitive to political nuance. However, The Prince is hardly a model for creating healthy political environments where successful IT can thrive. Here’s Wikipedia’s comment on Machiavelli (emphasis added):

Whatever Machiavelli’s own intentions (and they remain a matter of heated debate), his name became synonymous with ruthless politics, deceit and the pursuit of power by any means.

CIOs should remember The Prince is a guidebook to individual survival and ascendancy; it’s not a tool for creating collaborative organizations, which success in today’s world demands. Read Machiavelli as a background guide to understanding political dynamics, but don’t rely on it to achieve successful IT projects.

To create successful projects, CIOs should:

  1. Decipher the political landscape. Yeah, read Machiavelli, but don’t take him too literally.
  2. Focus on collaboration rather than personal ascendancy. In other words, don’t back stab your peers, as Machiavelli might recommend.
  3. Teach the IT organization better execution skills. Folks in the IT organization already know how to manage servers; now help them learn to manage projects.
  4. Talk with internal customers. Ask the business folks what they need; don’t guess and make assumptions, which will probably be wrong.

These four points are critical to achieving successful IT projects. Examine most failures and you’ll find problems in many of these areas.

Categories: Miscellaneous

Clean install windows 7, Don’t upgrade…

November 5, 2008 1 comment

 

I’ve just been having a flick through Microsoft’s Windows 7 Application Quality Cookbook and I’m already certain that those deciding to upgrade to the OS from XP or Vista are going to be in for a world of hurt unless everything that’s installed is bang up to date come release day – and even then there’s room for problems.

The cookbook is basically a big list of things that are likely to cause people problems when they shift to Windows 7. Here’s the top 11 listed in order of most likely to cause problems:

  • Internet Explorer 8 — User Agent String
  • Internet Explorer 8 — Data Execution Protection/NX
  • Removal of Windows Mail
  • Microsoft Message Queuing (MSMQ) — Removal of Windows 2000 Client Support Service
  • Compatibility — Operating System Versioning
  • Server Core — WoW64 Is Now an Optional Feature
  • User Interface — Enhanced Taskbar
  • Microsoft Message Queuing (MSMQ) — Improved Queue Handling
  • Windows Server — Terminal Services
  • User Interface — High DPI Awareness
  • Removal of WPDUSB.SYS Driver for Windows Portable Devices

I can see three of these issues being particularly painful to those who choose to upgrade from XP or Vista to Windows 7:

  • Internet Explorer 8 — Data Execution Protection/NX
    Basically, any add-on that’s not DEP/NX aware is likely to crash the browser. Any and every toolbar or add-on could cause problems, and there’s no guarantee that DEP/NX compatible versions will be available at Windows 7 launch. Anything obsolete or outdated that’s installed it likely to cause users problems.
    While for tech-heads that’s unlikely to be a total show-stopper, for your average Joe Sixpack user who relies on IE, this could cut them off from all sources of assistance and make them have to fall back on Microsoft support.
  • Compatibility — Operating System Versioning
    OS versioning is always a bug-bear. An app that’s otherwise 100% happy with the new OS can be crippled when it comes across an OS version that it’s not expecting.
    Again, not disastrous for a tech-savvy user, but could be a real show-stopper for Average Joe.
  • Removal of WPDUSB.SYS Driver for Windows Portable Devices
    This change to Windows 7 is another gotcha waiting for upgraders. Microsoft has replaced the Windows Vista USB driver stack (WPDUSB.SYS) for Windows Portable Devices with a generic WINUSB.SYS driver. This means that there could be issues surrounding hooking up to Windows Portable Devices using legacy drivers and applications.
    Depending on your device and vendor support, a shift to Windows 7 could mean having to replace the device.

Bottom line, these issues mean that doing an in-place upgrade of an OS could be traumatic no matter whether you are starting with XP or Vista. This means that the old rules apply – for the best experience possible, you will need to nuke your existing install and start fresh. You’ll also need to take care installing legacy drivers to make sure that you won’t be introducing problems.

Categories: Miscellaneous

Windows 7 to scale to 256 processors

November 2, 2008 Leave a comment

 

Microsoft has been hinting that even though it had no plans to make major changes to the Windows kernel, it did have a scheme up its sleeve to make Windows 7 and Windows & Server better suited to working on multicore / parallel systems. Now details are becoming clearer as to how Microsoft plans to do this.

Mark Russinovich, Technical Fellow in Microsoft’s Core OS division, explained in more detail how Microsoft has managed to do this in a video interview published on Microsoft’s Channel 9 Web site.

On more massively multiprocessor systems, Windows threads spin while waiting for the dispatcher lock. Once Cutler had been moved to work on Microsoft Red Dog (Windows Azure), another kernel developer, Arun Kishan, looked at this problem with a set of fresh eyes and found a solution, Russinovich said. By adding another state — so threads aren’t just running or waiting, but can be “pre-waiting,” as well — Windows will be better suited to running parallel, multithreaded applications running across manycore systems, Russinovich said.

Russinovich noted with the dispatcher-lock roadblock removed, a second set of locks became the new focus for folks working on the Windows kernel. The PFN database inside Windows, which contains information on all of the physical memory in the system, was becoming another scalability bottleneck when trying to get Windows to handle multithreaded apps on massively multicore machines. With Windows 7 and Windows Server 2008 R2 (Windows 7 Server), Microsoft again broke this lock down into finer grain locks, Russinovich said.

Categories: Miscellaneous