I had the following code:
protected void Initialize(){
this.Fonts.Initialize();
this.Screens.Initialize();
this.Menu.Initialize();
}
protected void Update(){
this.Screens.Update();
this.Menu.Update();
}
After writing this, I re-memorized the code:
protected void Initialize(){
this.CallMethod<INeedInitialization>(
(i) => { i.Initialize(); }
, this.Fonts, this.Screens, this.Menu
);
}
protected void Update(){
this.CallMethod<INeedUpdating>(
(i) => { i.Update(); }
, this.Screens, this.Menu
);
}
private void CallMethod<T>(Action<T> action, params T[] items){
items.ToList().ForEach(i => action(i));
}
Then I realized that there is a lot of reuse of type operations in my code base CallMethod<T>, so I will repeat factorization:
public static extensions{
public static void CallMethod<T>(this object obj, Action<T> action,
params T[] items){
items.ToList().ForEach(i => action(i));
}
}
Now I can get CallMethod<T>on all my objects, but somehow after that I feel that there is something fundamentally wrong in this code, and I canβt say why I think that this is not right.
Also, how can I put OR constraints on a generic method to accept only object types INeedUpdatingor INeedInitialize, rather than extending the base type Object?
Can anybody help?
Thank!
source
share