Michael Stal Präsentiert: Effective C#
Michael Stal Präsentiert: Effective C#
Michael Stal
[email protected]
präsentiert
Effective C#
Werbeseite ☺
1
© by ppedv ag
Agenda
2
© by ppedv ag
.NET/C# Features
3
© by ppedv ag
Pattern Variations
Idioms
4
© by ppedv ag
ETM Idiom
5
© by ppedv ag
Client Code
try {
r = new ResourceHolder();
// use the resource here …
}
finally {
r.Dispose();
}
// Optimization:
6
© by ppedv ag
// Resource Allocation:
LargeObject large = new LargeObject(/* params */);
...
// Introduce weak reference:
WeakReference weak = new WeakReference(large);
...
// When object is not used anymore deallocate it:
large = null;
7
© by ppedv ag
Immutable Classes
8
© by ppedv ag
9
© by ppedv ag
Minimize Boxing/Unboxing
Boxing Unboxing
value 14 value 14
copy copy
10
© by ppedv ag
Use conversions:
int i = 42;
Console.Writeline(i); // i will be boxed
Console.Writeline(i.ToString()); // no boxing
11
© by ppedv ag
Equals
Operator==
12
© by ppedv ag
GetHashCode
13
© by ppedv ag
Overriding ToString()
Makes your class more pleasant to use
Helps to return all interesting information
Should by accompanied by documentation of ToString()
Example:
class Person {
int age;
string name;
public Person(string n, int a) { age = a; name = n; }
public override string ToString() {
return "Person " + name + " " + age;
}
}
Comparisons
Two interfaces
IComparable used to define natural ordering of a type
IComparer implements additional ordering: not shown in this
talk
IComparable contains only one method:
public int CompareTo(object rhs)
o1.CompareTo(o2) yields
0, if both objects are equal with respect to ordering
- 1, if o1 < o2
+1, if o1 > o2
14
© by ppedv ag
Example: IComparable
}
(c) 2005, Michael Stal
}
15
© by ppedv ag
16
© by ppedv ag
17
© by ppedv ag
18
© by ppedv ag
Master
Slave
mySlaves
Delegate subTask
splitWork computation of
callSlaves subtasks to slaves
combineResults
service
Slaves
class Slave {
private double m_result;
private double[] m_dList;
private int m_start;
private int m_end;
public Slave(double[] dList, int start, int end) {
m_start = start; m_end = end; m_dList = dList;
}
public double Result { get { return m_result; }}
public void DoIt() {
m_result = 0.0;
for (int i = m_start; i <= m_end; i++)
m_result += m_dList[i];
}
}
19
© by ppedv ag
Master
class Master {
public double CalculateSum(double[] dList, int start, int end) {
if (start > end ) throw new ArgumentException();
if (start == end) return dList[start];
int mid = (end - start) / 2;
Slave s1 = new Slave(dList, start, mid);
Slave s2 = new Slave(dList, mid+1, end);
Thread t1 = new Thread(new ThreadStart(s1.DoIt));
Thread t2 = new Thread(new ThreadStart(s2.DoIt));
t1.Start(); // start first slave
t2.Start(); // start second slave
t1.Join(); // wait for first slave
t2.Join(); // wait for second slave
return s1.Result + s2.Result; // combine results
}
Putting it together
class Manager {
static void Main(string[] args) {
double[] d = {1,2,3,4,5,6,7,8,9,10};
Console.WriteLine(new Master().CalculateSum(d, 0, 9));
}
}
20
© by ppedv ag
Singleton
Intent
ensure a class only ever has one instance, and provide a global point of
access to it
Applicability
when there must be exactly one instance of a class
Singleton
when sole instance should be extensible by subclassing
Structure method()
method()
static instance()
Consequences
reduced name space pollution static instance
Implementation
C#: declare constructor as protected to guard against multiple singleton
instances
21
© by ppedv ag
22
© by ppedv ag
Singleton - Threadsafe
Singleton – Threadsafe
Efficient solution:
class MyClass3b /* double checked locking */ {
private static MyClass3b m_Instance;
private MyClass3b() {}
public static MyClass3 Instance {
get {
if (null == m_Instance) {
lock(typeof(MyClass3b))
{
if (null == m_Instance)
m_Instance = new MyClass3b();
}
}
return m_Instance;
}
}
}
(c) 2005, Michael Stal
23
© by ppedv ag
Observer
Intent
Define a dependency between objects so that when one object
changes state then all its dependents are notified
Applicability
When a change to one object requires changing others
Decouple notifier from other objects
Structure Subject
observers Observer
attach()
while (e.hasMoreElements()) detach() update()
Observer o = (Observer) notify()
e.nextElement();
o.update(this));
ConcreteSubject ConcreteObserver
subject
getState() update()
state = newState;
setState()
notify();
(c) 2005, Michael Stal
Observer (cont’d)
Consequences
abstract coupling of subject and observer
object is responsible only for its own state Þ reusability
unexpected updates, update overhead
Implementation
push/pull model for notifications
change interests
Known Uses
Smalltalk MVC
MFC
MacApp, ET++
24
© by ppedv ag
Observer in C#
Observer in C# (cont‘d)
class ObserverDemo {
class Observer {
public Observer(Subject s) {
s.OnNotify += new Subject.Notify(TellMe);
}
public void TellMe() {}
}
25
© by ppedv ag
Summary
Books
26
© by ppedv ag
Juni 2006
November 2006
Februar 2007
27