.NET Best Practices and Design Patterns Flashcards
Decorator Pattern
Increases complexity setting up the chain of decorators.
Supports the Open/Close Principle.
Decorated object is not the object.
Decorator in the .NET Framework
Stream classes use decorators.
BufferedStream and CryptoStream classes decorate a Stream.
Adapter Pattern
Translates one interface for a class into a compatible interface.
An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms.
Adapter Pattern Implementation
Find Commonality: Commonality is extracted to an interface
Encapsulate Differences: Incompatible classes are wrapped by an adapter
Client works with the adapter class
Adapter Pattern in the .NET Framework
DataAdapter classes convert the interfaces of ventor-specific database classes into an interface that works with the general DataSet class: SqlDataAdapter, OdbcDataAdapter, etc.
DataSet class in namespace System.Data.
Template Method Pattern
Defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses.
It lets one redefine certain steps of an algorithm without changing the algorith’s structure.
Template Method Pattern Implementation
Find Commonality: Common parts of the algorithm are factored into a base class.
Encapsulate Differences: Differences (customization points) are encapsulated in derived classes.
Allows the customization points to be seamlessly integrated.
Template Method Pattern in the .NET Framework
The sequence of events for a form is fixed. The details of the steps are customizable.
SOLID Principles
Single Responsibility Principle: A class should have only one reason to change
Open/Closed Principle: Classes should be open to extension and closed to modification
Liskov Substitution Principle: Derived classes should honor the base class’ contract Interface
Segregation Principle:
Dependency Inversion Principle:
Single Responsibility
Class should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
All its services should be narrowly aligned with that responsibility.
Open/Closed Principle (OCP)
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
Entities can allow their behaviour to be modified without altering its source code. This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn’t change when it is extended, and therefore needs no such effort.
Liskov Substitution
Derived classes must be substitutable for their base classes.
Derived classes must be consistent with the promises made by the base class’ contract. Derived classes add data, add behavir, but do not remove behavior.
Interface Segregation Principal (ISP)
Interfaces are owned by clients, not implementors.
No client should be forced to depend on methods it does not use. ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called role interfaces. ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy.
Dependency Inversion Principal
Details depend on abstraction.
Isolates business logic from data access logic. Allows us to write a strategy for data access, so it can be faked. Specific form of decoupling where conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed) for the purpose of rendering high-level modules independent of the low-level module implementation details. The principle states: A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions.
Role Object Pattern
Adapt an object to different client’s needs through transparently attached role objects, each one representing a role the object has to play in that client’s context.
The object manages its role set dynamically. By representing roles as individual objects, different contexts are kept separate and system configuration is simplified. Uses delegation to solve the problem of roles.
Which gives more run-time flexibility: composition or inheritance?
Composition
What tests can help determine correctness of inheritance?
N/A
Is it better to depent on wider or narrower interfaces?
Narrower
Repository Pattern
Separates the querying from the filtering.
Matches method -Returns Ienumerable -Passed a filter object Icriteria -Can handle the three standard return cases: None, One, Lots Add method Remove method SaveChanges method
Mock Object Pattern
TestInitialize attibute
N/A
ClassInitialize attribute
N/A
Mocking
Mock objects are simulated objects that mimic the behavior of real objects in controlled ways.
A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.
Mocking is a key technique in Test-Driven Development.
CRUD
Create, Read, Update and Delete
In computer programming, create, read, update and delete (CRUD) (Sometimes called SCRUD with an “S” for Search) are the four basic functions of persistent storage.[1] Sometimes CRUD is expanded with the words retrieve instead of read, modify instead of update, or destroy instead of delete. It is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information; often using computer-based forms and reports. The term was likely first popularized by James Martin in his 1983 book Managing the Data-base Environment.[2][3] The acronym may be extended to CRUDL to cover listing of large data sets which bring additional complexity such as pagination when the data sets are too large to hold easily in memory.
Transaction Script
Organizes business logic by procedures where each procedure handles a single request from the presentation.
Simple procedural model:
- Get data from UI
- Proces it with validations and calculations
- Store stuff in the database
- Reply with more data to the UI
Pros:
- Works well with simple applications.
Cons:
- Harder to implement complex logic.
- More logic leads to more Case statements in the one routine (dividing it into routines or modules helps).
- Duplication is more extensive (i.e. does not fit well into OO programming)
Most business applications can be thought of as a series of transactions. A transaction may view some information as organized in a particular way, another will make changes to it. Each interaction between a client system and a server system contains a certain amount of logic. In some cases this can be as simple as displaying information in the database. In others it may involve many steps of validations and calculations.
A Transaction Script organizes all this logic primarily as a single procedure, making calls directly to the database or through a thin database wrapper. Each transaction will have its own Transaction Script, although common subtasks can be broken into subprocedures.
Domain Model
An object model of the domain that incorporates both behavior and data.
At its worst business logic can be very complex. Rules and logic describe many different cases and slants of behavior, and it’s this complexity that objects were designed to work with. A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form.

Domain Object Model
Describes application’s business rules and special cases as a system of objects.
- Applies standard OO methods and patterns to manager the complexity in the problem domain.
- Conentrates on the problem and not on the data storage.
- Realized in the business entities and business proccesses of the application.
Pros:
- Uses standard OO techniques for handling increases domain complexity.
- Application code complexity increases no faster than domain complexity.
- ORM tools available to help create the mapping layer.
Cons:
- Developer cost in the complexity of a Domain Model
- Hard to see a “whole” process. Logic is distributed over multiple objects.
- Complexity of the data access layer. The richer the domain model, the more complex the mapping to the database.
- Data Mapper pattern helps here.
Table Module
A single instance that handles the business logic for all rows in a database table or view.
- An object that encapsulates an SQL query and related objects.
- A kind of middle ground.
- More use of objects than transaction script.
- Supplied in .NET by the DataSet/TableAdapter combination.
Pros:
- Many IDEs have direct support this pattern.
Cons:
- DataSet cannot express custom logic as part of the class.
- Serious logic must be external to the DataSet (i.e., separate classes and stored procedures)
- Weak support for navigating relationships.
- No support for inheritance/polymorphic behavior.
- Much duplication of queries and parameter-setting code.
One of the key messages of object orientation is bundling the data with the behavior that uses it. The traditional object-oriented approach is based on objects with identity, along the lines of Domain Model (116). Thus, if we have an Employee class, any instance of it corresponds to a particular employee. This scheme works well because once we have a reference to an employee, we can execute operations, follow relationships, and gather data on him.
One of the problems with Domain Model (116) is the interface with relational databases. In many ways this approach treats the relational database like a crazy aunt who’s shut up in an attic and whom nobody wants to talk about. As a result you often need considerable programmatic gymnastics to pull data in and out of the database, transforming between two different representations of the data.
A Table Module organizes domain logic with one class per table in the data-base, and a single instance of a class contains the various procedures that will act on the data. The primary distinction with Domain Model (116) is that, if you have many orders, a Domain Model (116) will have one order object per order while a Table Module will have one object to handle all orders.

Entity Framework
Code First
- Code Plain Old CLR Object (POCO) classes represent entities through Persistence Ignorance (PI)
- Easy database access: Developer inherits from DbContext
Database First
- Wizard generates an initial set of entity classes from a database.
- Entity classes derive from an EF-supported base class.
Model First
- Developer uses a designer to create entity classes
- Entity classes derive from an EF-supplied base class
Convention Over Configuration
Software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility.
The phrase essentially means a developer only needs to specify the exceptional aspects of the application, not the normal.
Mapping Objects to Databases
ConceptObjects in MemoryRows in Database One-to-one or one-to-many (parent-child) relationships Maintained via a collection in the parent Maintained b foreign key in the child Many-to-many relationships Maintained by a collection in each object Requires a “link table” Inheritance Easy and natural Not directly supported Polymorphism Easy and natural Not directly supported
One-to-Many Relationship Code
On the “many” side:
- Foreign key property
- ForeignKey attribute
- Scalar navigation property that returns the one ralted object
On the “one” side:
- ICollection<> navigation property
- Marking navigation property virtual makes the relationship lazy-loading
Data Mapper
Mappers move data between objects and a database while keeping them independent of each other and the mapper itself.
Objects and relational databases have different mechanisms for structuring data. Many parts of an object, such as collections and inheritance, aren’t present in relational databases. When you build an object model with a lot of business logic it’s valuable to use these mechanisms to better organize the data and the behavior that goes with it. Doing so leads to variant schemas; that is, the object schema and the relational schema don’t match up.
You still need to transfer data between the two schemas, and this data transfer becomes a complexity in its own right. If the in-memory objects know about the relational database structure, changes in one tend to ripple to the other.
The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn’t know even that there’s a database present; they need no SQL interface code, and certainly no knowledge of the database schema. (The database schema is always ignorant of the objects that use it.) Since it’s a form of Mapper (473), Data Mapper itself is even unknown to the domain layer.

Class Table Inheritance
Represents an inheritance hierarchy of classes with one table for each class.
A very visible aspect of the object-relational mismatch is the fact that relational databases don’t support inheritance. You want database structures that map clearly to the objects and allow links anywhere in the inheritance structure. Class Table Inheritance supports this by using one database table per class in the inheritance structure.

Concrete Table Inheritance
Represents an inheritance hierarchy of classes with one table per concrete class in the hierarchy.
As any object purist will tell you, relational databases don’t support inherit-ance - a fact that complicates object-relational mapping. Thinking of tables from an object instance point of view, a sensible route is to take each object in memory and map it to a single database row. This implies Concrete Table Inher-itance, where there’s a table for each concrete class in the inheritance hierarchy.
I’ll confess to having had some difficulty naming this pattern. Most people think of it as leaf oriented since you usually have one table per leaf class in a hierarchy. Following that logic, I could call this pattern leaf table inheritance, and the term “leaf” is often used for this pattern. Strictly, however, a concrete class that isn’t a leaf usually gets a table as well, so I decided to go with the more correct, if less intuitive term.

Single Table Inheritance
Represents an inheritance hierarchy of classes as a single table that has columns for all the fields of the various classes.
Relational databases don’t support inheritance, so when mapping from objects to databases we have to consider how to represent our nice inheritance struc-tures in relational tables. When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables. Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.

How are parent-child relationships maintained in an object model?
Using foreign keys & collections
How are parent-child relationships maintained in a relational DB?
Using keys
Every table in the database should have exactly one corresponding Entity class
True or False?
False
Entity Framework guarantees fast code — no tuning required
True or False
False
INotifyPropertyChanged
.NET interface that notifies clients that a property value has changed.
Observer Pattern
Design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
Data Transfer Object Pattern
An object that carries data between processes in order to reduce the number of method calls.
When you’re working with a remote interface, such as Remote Facade (388), each call to it is expensive. As a result you need to reduce the number of calls, and that means that you need to transfer more data with each call. One way to do this is to use lots of parameters. However, this is often awkward to program - indeed, it’s often impossible with languages such as Java that return only a single value.
The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across the connection. Usually an assembler is used on the server side to transfer data between the DTO and any domain objects.
Many people in the Sun community use the term “Value Object” for this pattern. I use it to mean something else. See the discussion on page 487.

Convenience Extension Methods
- Return a singe object
- Avoids handling a collection of one
- Examples:
- MatchSingle
- MatchSingleOrDefault
DbContext Class
Represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit.
Trans entity updates, adds, and deletes.
DataSet Class
Represents an in-memory cache of data.
What is the purpose of the Observer Pattern?
To push change from central class to observer class, usually in the UI.
What .NET feature provides a direct implementation of the Observer pattern?
Events
The data-binding architecture primarily works with:
- Methods
- Properties
- Public Fields
B. Properties
Entity Framework
(choose all answers that apply)
- Makes the database look like a huge collection of objects
- Makes database administration skills completely redundant
- Attempts to generate accurately targeted queries
WCF
Windows Communication Foundation
A runtime and a set of APIs in the .NET Framework for building connected, service-oriented applications
Proxy Pattern
Class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Provides a surrogate or place holder for another object to control access to it.
Client programs to the interface.
MVC
An uncoupling pattern where the state of the presentation is maintained in a separate control class.
Splits user interface interaction into three distinct roles.
Controller classes typically contain complex control logic.
- Complexity can be managed by implementing State and Observer patterns.

Separation of Concern
Process of breaking a computer program into distinct features that overlap in functionality as little as possible.
Store Data Model (SDM)
Description of the tables and columns in the database
Conceptual Data Model (CDM)
Description of the entities that the application chooses to work with.