[Mono-list] Suggestion: warning "member variable not initialized"
Maurizio Colucci
seguso.forever@tin.it
Sat, 7 Jun 2003 14:50:03 +0200
Hi,
Currently the Microsoft C# compiler gives an error if you forget to
initialize a readonly member variable (this can be done either in the
contructor or in the declaration itself.)
I already posted a wish for mcs about that, but:
What about extending this behavior to non-readonly member-variables?
(Maybe a warning instead of an error?)
RATIONALE:
I cannot think of a case where not initializing a member variable (in
the constructor or at declaration time) makes sense. So we would catch
a frequent semantic error without any drawback...
Someone could reply that there ARE indeed some cases when you don't
know an appropriate value for a member variable when the constructor
is called. Maybe the user must initialize it explicitely, after
construction.
e.g.
class C{
private int member_var;
public C(){
// I don't yet know how to initialize member_var. Only the
// user can do that, via the Init method.
}
public void Init(int m){
member_var=m;
}
}
But, on the other hand, the above is bad design:
If member_var is not always meaningful across the lifetime of class C,
then member_var should NOT have been declared as a member of C, in the
first place. In other words, C is a state machine with two states:
Initialized and NotInitialized, such that member_var only makes sense
in the Initialized state, and not in the other one.
Good design:
class C{
private abstract class State{}
private class Initialized: State{
public int member_var; // this variable only makes sense
// when C is in the Initialized state!
// therefore it is declared here,
// not inside C.
public Initialized(int m){
member_var = m;
}
}
private class NotInitialized: State{}
private int state = new NotInitialized();
public void Init(int m){
state = new Initialized(m);
}
}
In this latter example, member_var DOES NOT EXIST when it does make
sense. This avoid the risk that someone reads/writes it when it makes
no sense!
In the former case, there is a time when member_var exists but does
not make sense (and is not initialized). Error prone.
So by raising an error in the former case we would enforce good
design.
Any comments?