Thinking in C# phần 5 - Pdf 20


342 Thinking in C# www.ThinkingIn.NET
.NET to program Windows Forms, it will place all the code relating to
constructing the user-interface into a method called InitializeComponent( );
this method may be hundreds of lines long, but it contains no control-flow
operators, so it’s length is irrelevant. On the other hand, the 15 lines of this leap
year calculation are about as complex as is acceptable:
//:c09:LeapYearCalc.cs
using System;

class LeapYearCalc {
static bool LeapYear(int year){
if (year % 4 != 0) {
return false;
} else {
if (year % 400 == 0) {
return true;
} else {
if (year % 100 == 0) {
return false;
} else {
return true;
}
}
}
}

public static void Test(int year, bool val){
if (val == LeapYear(year)) {
Console.WriteLine(
"{0} correctly calced as {1}", year, val);

stems from encapsulation, the logical organization of data and behavior with
restricted access. Coupling and cohesion are more precise terms to discuss the
benefits of encapsulation, but class interfaces, inheritance, the visibility
modifiers, and Properties – the purpose of all of these things is to hide a large
number of implementation details while simultaneously providing functionality
and extensibility.
Why do details need to be hidden? For the original programmer, details that are
out of sight are out of mind, and the programmer frees some amount of his or her
finite mental resources for work on the next issue. More importantly than this,
though, details need to be hidden so software can be tested, modified, and
extended. Programming is a task that is characterized by continuously
overcoming failure: a missed semicolon at the end of a line, a typo in a name, a
method that fails a unit test, a clumsy design, a customer who says “this isn’t
what I wanted.” So as a programmer you are always revisiting existing work,
whether it’s three minutes, three weeks, or three years old. Your productivity as a
professional programmer is not governed by how fast you can create, it is
governed by how fast you can fix. And the speed with which you can fix things is
influenced by the number of details that must be characterized as relevant or
irrelevant. Objects localize and isolate details.

344 Thinking in C# www.MindView.net
Coupling, cohesion,
and design trends
Coupling and cohesion, popularized by Ed Yourdon and Larry Constantine way
back in the 1970s, are still the best touchstones for determining whether a
method or type is built well or poorly. The most important software engineering
book of the 1990s was Design Patterns: Elements of Reusable Object-Oriented
Software (Addison-Wesley, 1995) by Erich Gamma, Richard Helm, Ralph
Johnson, and John Vlissides (the “Gang of Four”). What really set Design
Patterns apart is that it was based on an archaeological approach to design;

Any software project of more than a few hundred lines of code should be
organized by a principle. This principle is called the software’s architecture. The
word architecture is used in many ways in computing; software architecture is a
characteristic of code structure and data flows between those structures. There
are many proven software architectures; object-orientation was originally
developed to aid in simulation architectures but the benefits of objects are by no
means limited to simulations.
Many modern-day projects are complex enough that it is appropriate to
distinguish between the architecture of the overall systems and the architecture
of different subsystems. The most prevalent examples of this are Web-based
systems with rich clients, where the system as a whole is often an n-tier
architecture, but each tier is a significant project in itself with its own organizing
principle.
Where the aims of architecture are strategic and organizational, the aims of
software design are tactical and pragmatic. The purpose of software design is to
iteratively deliver client value as inexpensively as possible. The most important
word in that previous sentence is “iteratively.” You may fool yourself into
believing that design, tests, and refactoring are wastes of time on the current
iteration, but you can’t pretend that they are a waste of time if you accept that
whatever you’re working on is likely to be revisited every three months, especially
if you realize that if you don’t make things clear, they’re going to be going to be
calling you at 3 o’clock in the morning when the Hong Kong office says the
system has frozen
6
.
Software design decisions, which run the gamut from the parameters of a method
to the structure of a namespace, are best made by consideration of the principles
of coupling and cohesion. Coupling is the degree to which two software elements
are interdependent; cohesion is a reflection of a software element’s internal


and test-first programming.
4. Fill in the following Venn diagram comparing aspects of software
development with physical architecture.

Chapter 9: Coupling and Cohesion 347
Software
Development
Architecture
Shared

5. Write a one-page essay defending or refuting the statement “Software is
architecture.”
6. The hardware manufacturers are thrilled with your work with the robotic
party servant and want you to lead the development of all the robot's
behavioral software. What kind of architecture will you adopt? Why?
7. Evaluate your party servant system. Use everything that you have learned
to improve your design and implementation.


349
10: Collecting
Your Objects
It’s a fairly simple program that has only a fixed quantity of
objects with known lifetimes.
In general, your programs will always be creating new objects based on some
criteria that will be known only at the time the program is running. You won’t know
until run-time the quantity or even the exact type of the objects you need. To solve
the general programming problem, you need to be able to create any number of
objects, anytime, anywhere. So you can’t rely on creating a named reference to hold
each one of your objects:

The vector container class in C++ does know the type of objects it holds, but it has
a different drawback when compared with arrays in C#: the C++ vector’s
operator[] doesn’t do bounds checking, so you can run past the end
1
. In C#, you
get bounds checking regardless of whether you’re using an array or a container—
you’ll get an IndexOutOfRangeException if you exceed the bounds. As you’ll
learn in Chapter 11, this type of exception indicates a programmer error, and thus
you don’t need to check for it in your code. As an aside, the reason the C++ vector
doesn’t check bounds with every access is speed—in C# you have the performance
overhead of bounds checking all the time for both arrays and containers.
The other generic container classes that will be studied in this chapter,
ICollection, IList and IDictionary, all deal with objects as if they had no
specific type. That is, they treat them as type object, the root class of all classes in
C#. This works fine from one standpoint: you need to build only one container, and
any C# object will go into that container. This is the second place where an array is
superior to the generic containers: when you create an array, you create it to hold a
specific type. This means that you get compile-time type checking to prevent you
from putting the wrong type in, or mistaking the type that you’re extracting. Of
course, C# will prevent you from sending an inappropriate message to an object,
either at compile-time or at run-time. So it’s not much riskier one way or the other;
it’s just nicer if the compiler points it out to you, faster at run-time, and there’s less
likelihood that the end user will get surprised by an exception.
Typed generic classes (sometimes called “parameterized types” and sometimes just
“generics”) are not part of the initial .NET framework but will be. Unlike C++’s
templates or Java’s proposed extensions, Microsoft wishes to implement support
for “parametric polymorphism” within the Common Language Runtime itself. Don
Syme and Andrew Kennedy of Microsoft’s Cambridge (England) Research Lab
class Weeble {
} // A small mythical creature

public class ArraySize {
public static void Main() {
// Arrays of objects:
Weeble[] a; // Null reference
Weeble[] b = new Weeble[5]; // Null references
Weeble[,] c = new Weeble[2, 3]; //Rectangular array
Weeble[] d = new Weeble[4];
for (int index = 0; index < d.Length; index++)
d[index] = new Weeble();
// Aggregate initialization:

352 Thinking in C# www.MindView.net
Weeble[] e = {
new Weeble(), new Weeble(), new Weeble()
};
// Dynamic aggregate initialization:
a = new Weeble[] {
new Weeble(), new Weeble()
};
// Square dynamic aggregate initialization:
c = new Weeble[,] {
{ new Weeble(), new Weeble(), new Weeble()},
{ new Weeble(), new Weeble(), new Weeble()}
};

Console.WriteLine("a.Length=" + a.Length);
Console.WriteLine("b.Length = " + b.Length);

Console.WriteLine("h.Length = " + h.Length);
Console.WriteLine("i.Length = " + i.Length);
f = i;
Console.WriteLine("f.Length = " + f.Length);
f = new int[] { 1, 2};
Console.WriteLine("f.Length = " + f.Length);
}
} ///:~

Here’s the output from the program:
a.Length=2
b.Length = 5
c.Length = 6
c.Length[0] = 2
c.Length[1] = 3
b[0]=
b[1]=
b[2]=
b[3]=
b[4]=
d.Length = 4
d.Length = 4
a.Length = 4
g.Length = 5
g[0]=0
g[1]=0
g[2]=0
g[3]=0
g[4]=0
h.Length = 4

but you can also dynamically create the array you want to pass as the argument:
Hide(new Weeble[] { new Weeble(), new Weeble() });

In some situations this new syntax provides a more convenient way to write code.
Rectangular arrays are initialized using nested arrays. Although a rectangular array
is contiguous in memory, C#’s compiler will not allow you to ignore the
dimensions; you cannot cast a flat array into a rectangular array or initialize a
rectangular array in a “flat” manner.
The expression:
a = d;

shows how you can take a reference that’s attached to one array object and assign it
to another array object, just as you can do with any other type of object reference.
Now both a and d are pointing to the same array object on the heap.
The second part of ArraySize.cs shows that primitive arrays work just like object
arrays except that primitive arrays hold the primitive values directly.

Chapter 10: Collecting Your Objects 355
The Array class
In System.Collections, you’ll find the Array class, which has a variety of
interesting properties and methods. Array is defined as implementing
ICloneable, IList, ICollection, and IEnumerable. This is actually a pretty
sloppy declaration, as IList is declared as extending ICollection and
IEnumerable, while ICollection is itself declared as extending IEnumerable
(Figure 10-1)!
ICollection
IEnumerable
ICloneable
IList
Array

static string[,] famousCouples = new string[,]{
{ "George", "Martha"}, { "Napolean", "Josephine"},
{ "Westley","Buttercup"}
};

static Weeble[] weebleList = new Weeble[]{
new Weeble("Pilot"), new Weeble("Firefighter")
};

public static void Main() {
//Copying arrays
Weeble[] newList = new Weeble[weebleList.Length];
Array.Copy(weebleList, newList, weebleList.Length);
newList[0] = new Weeble("Nurse");
bool newReferences = newList[0] != weebleList[0];
Console.WriteLine("New references == "
+ newReferences);
//Copying a rectangular array works
string[,] newSquareArray =
new string[famousCouples.GetLength(0),
famousCouples.GetLength(1)];
Array.Copy(famousCouples, newSquareArray,
famousCouples.Length); Chapter 10: Collecting Your Objects 357
//In-place sorting
string[] sortedDays = new string[dayList.Length];
Array.Copy(dayList, sortedDays, dayList.Length);
Array.Sort(sortedDays);

}
}///:~

After declaring a Weeble class (this time with a Name property to make them easier
to distinguish), the ArrayStatics class declares several static arrays – dayList
and weebleList, which are both one-dimensional, and the square
famousCouples array.

358 Thinking in C# www.ThinkingIn.NET
Array.Copy( ) provides a fast way to copy an array (or a portion of it). The new
array contains all new references, so changing a value in your new list will not
change the value in your original, as would be the case if you did:
Weeble[] newList = weebleList;
newList[0] = new Weeble("Nurse");

Array.Copy( ) works with multidimensional arrays, too. The program uses the
GetLength(int) method to allocate sufficient storage for the new SquareArray,
but then uses the famousCouples.Length property to specify the size of the
copy. Although Copy( ) seems to “flatten” multidimensional arrays, using arrays of
different rank will throw a runtime RankException.
The static method Array.Sort( ) does an in-place sort of the array’s contents and
BinarySearch( ) provides an efficient search on a sorted array.
Array.Reverse( ) is self-explanatory, but Array.Clear( ) has the perhaps
surprising behavior of slicing across multidimensional arrays. In the program,
Array.Clear(famousCouples, 2, 3) treats the multidimensional
famousCouples array as a flat array, setting to null the values of indices [1,0],
[1,1], and [2,0].
Array element comparisons
How does Array.Sort( ) work? A problem with writing generic sorting code is that
sorting must perform comparisons based on the actual type of the object. Of course,

j = n2;
}
public override string ToString() {
return "[i = " + i + ", j = " + j + "]";
}

public int CompareTo(Object rv) {
int rvi = ((CompType)rv).i;
if (i > rvi)
return 1;
else if (i == rvi)
return 0;
else
return -1;
(i < rvi ? -1 : (i == rvi ? 0 : 1));
}

private static Random r = new Random();

private static void ArrayPrint(String s, Array a){
Console.Write(s);
foreach(Object o in a){
Console.Write(o + ",");
}
Console.WriteLine();
} 360 Thinking in C# www.MindView.net
public static void Main() {

using System;

class Sortable : IComparable {
int i;
internal Sortable(int i) {
this.i = i;
}

Chapter 10: Collecting Your Objects 361

public int CompareTo(Object o) {
try {
Sortable s = (Sortable) o;
return i = s.i;
} catch (InvalidCastException) {
throw new ArgumentException();
}
}
}

class SortingTester {
static TimeSpan TimedSort(IComparable[] s){
DateTime start = DateTime.Now;
Array.Sort(s);
TimeSpan duration = DateTime.Now - start;
return duration;
}
public static void Main() {
for (int times = 0; times < 10; times++) {
Sortable[] s = new Sortable[1000000];

we’ll abandon the keyboard and the monitor for voice and gesture input and
“augmented reality” glasses. Almost all the programming facts that hold today will
be as useless as the knowledge of how to do an oscillating sort with criss-cross
distribution. A programmer must never stand still.
Unsafe arrays
Despite the preceding discussion of the steady march of technical obsolescence, the
facts on the ground often agitate towards throwing away the benefits of safety and
abstraction and getting closer to the hardware in order to boost performance.
Often, the correct solution in this case will be to move out of C# altogether and into
C++, a language which will continue for some time to be the best for the creation of
device drivers and other close-to-the-metal components.
However, manipulating arrays can sometimes introduce bottlenecks in higher-level
applications, such as multimedia applications. In such situations, unsafe code may
be worthwhile. The basic impetus for using unsafe arrays is that you wish to
manipulate the array as a contiguous block of memory, foregoing bounds checking.
As a testbed for exploring performance with unsafe arrays, we’ll use a
transformation that actually has tremendous practical applications. Wavelet
transforms are fascinating and their utility has hardly been scratched. The simplest
transform is probably the two-dimensional Haar transform on a matrix of doubles.
The Haar transform converts a list of values into the list’s average and differences,
so the list {2, 4} is transformed into {3, 1} == {(2 + 4) / 2, ((2 + 4) / 2) – 2}. A two-
dimensional transform just transforms the rows and then the columns, so {{2,
4},{5,6}} becomes {{4.25, .75},{1.25, -0.25}}:

Chapter 10: Collecting Your Objects 363
24
56
31
5.5 0.5
4.25

minDimension = matrix.GetLength(1);
int levels =
(int) Math.Floor(Math.Log(minDimension, 2));
Transform2D(matrix, levels, t);
}

public void Transform2D(double[,] matrix,

364 Thinking in C# www.MindView.net
int steps, Transform tStrategy) {
for (int i = 0; i < steps; i++) {
tStrategy.HorizontalTransform(matrix);
tStrategy.VerticalTransform(matrix);
}
}

public void TestSpeed(Transform t) {
Random rand = new Random();
double[,] matrix = new double[2000,2000];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++) {
matrix[i,j] = rand.NextDouble();
}
DateTime start = DateTime.Now;
this.Transform2D(matrix, t);
TimeSpan dur = DateTime.Now - start;
Console.WriteLine(
"Transformation with {0} took {1} ",
t.GetType().Name, dur);
}


public void HorizontalTransform(double[,] matrix) {
int height = matrix.GetLength(0);
int width = matrix.GetLength(1);
double[] row = new double[width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
row[j] = matrix[i, j];
}
Transform(row);
for (int j = 0; j < width; j++) {
matrix[i,j] = row[j];
}
}
}

public void VerticalTransform(double[,] matrix) {
int height = matrix.GetLength(0);
int length = matrix.GetLength(1);
double[] colData = new double[height];
for (int col = 0; col < length; col++) {
for (int row = 0; row < height; row++) {
colData[row] = matrix[row, col];
}
Transform(colData);
for (int row = 0; row < height; row++) {
matrix[row, col] = colData[row];
}
}
}

dimension of the passed-in matrix and then using the Math.Log( ) function to
determine the base-2 magnitude of that dimension. Math.Floor( ) rounds that
magnitude down and the result is cast to the integer number of steps that will be
applied to the matrix. (Thus, an array with a minimum dimension of 4 would have
2 steps; an array with 1024 would have 9.)
The constructor then calls the second constructor, which takes the same
parameters as the first plus the number of times to apply the wavelet (this is a
separate constructor because during debugging a single wavelet step is much easier
to comprehend than a fully processed one, as Figure 10-4 illustrates)


Nhờ tải bản gốc
Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status