Click here to Skip to main content
15,886,755 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i read an article "Static classes considered bad practice" couple day ago. most of time i use static classed for utility function. so static class are consider bad code Is this correct, and if so, for what reasons?
Posted

Statics tend to be inflexible. You can't interface them, you can't override them, you can't control the timing of their construction, you can't use them well in generics. You can't really version them.

There are certainly uses of statics: constant values work great. You can make database connection or open any file resource in static block

So in general, not bad practice but use them wisely.

-KR
 
Share this answer
 
i agree with my previous speaker - "use them wisely".

Lets have a look the other way round: when is it appropriate to create a class?
please understand "class" as "construction-plan of objects". Understand "static class" as no-class or the opposite of class.
And understand object as a unit of Data togehter with its own functionality, to manipulate it. Other words: An object has a state, and can change it. Another basic concept: you can have several different objects of the same class.

So that is when you need a class: you want several objects of that class, and the object shall have different states.

To answer the question: if you have functionality, but no data, which is to store in several stated objects, then you don't need a class.

As sample for stated objects take FileInfo-class: each FileInfo contains its own data (information about a file), and its own functionality to manipulate it. And because there are many files on disc, it is required, that one can create many FileoInfos - the class-concept is required.

As sample for functionality, not associated to own data take the System.Math-static-class: It has no state: creating several Math-objects would make no sense at all. In difference to FileInfo each Math-Function gets the data it needs by arguments and returns a result - no state-data is to store.

so i see your static-usage as propably completely right: A static class is to store utility-functions. Of course you can still do something wrong, but in general "utility" are a concern which is meaningful placed within a static class.

The other way round, namely create an "utility-object" each time, whenever you need a function and destroy it afterwards would be - i call it: "brain-f***".
An object should have a state, and should be designed to change it several time. That is what the class-concept was invented for.

It is a mis-design, to apply the class-concepts to concerns, which do not need that.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900