c# - Is there a "right" way to abstract out my code? -
i have been developing in c# around 12 months (from scratch, no previous dev experience apart little bit of php script hacking) , think have developed skills level can write app , perform function perfectly.
however, still little confused best coding practises, understand code bad:
class example1 { public static alert generatealert() { alert alertobject = new alert(); alertobject.alertdatetime = datetime.now; alertobject.alerthasrecords = false; return alertobject; } }
if example alertdatetime
requires more simple line datetime.now;
end bulking out massive function. not good!
however, cant see problem following 2 examples (i favour example 2)
class example2 { public static alert alertobject = new alert(); public static alert generatealert() { populatealertdate(); checkforalertrecords(); return alertobject; } private static void checkforalertrecords() { alertobject.alerthasrecords = false; } private static void populatealertdate() { alertobject.alertdatetime = datetime.now; } } class example3 { public static alert generatealert() { alert alertobject = new alert(); alertobject.alertdatetime = populatealertdate(); alertobject.alerthasrecords = checkforalertrecords(); return alertobject; } private static bool checkforalertrecords() { return false; } private static datetime populatealertdate() { return datetime.now; } }
is 1 example better other, , if why? or there different way of doing it?
your first example fine.
if, @ later time, alertdatetime
requires more complex function initialized, can refactor code example 3. until then, respect kiss (keep simple) , yagni principles.
note interface (the publicly available methods , signature) not change between examples 1 , 3. thing. means can move between styles without having modify code uses class.
example 2, however, has lot of problems:
the information hiding principle says should not expose publicly without reason. why store newly generated alert in publicly accessible "global variable"?
example 2 behaves differently: if call
generatealert
twice, return reference same alert object both times. (think happens if call once today , again tomorrow.)
as side note, naming of methods in example 3 can improved. try think of each method in isolation: populatealertdate()
not populate alert date. returns date can used populate alert date. name getdefaultalertdate()
might more appropriate.
Comments
Post a Comment