I've read a few threads related to the question by I'm still not sure what's better for the current situation. I have two simple classes:
File:
string name;
long size;
Folder:
string name;
IList<File> files;
IList<Folder> folders;
If I want to implement a method which calculates the contents size of a folder, should I implement it as an instance or as a static member. The implementation needs a Folder object as a sole parameter and it does not change any state of the variable so I'm thinking of making it static but I'm not sure if this is the right step.
You can make a comparison with something that describe your problem.
Calculate something when i give you a parameter.
The first thing that comes up in my mind and do a similar thing is Math.Pow which is a static method.
If you want to do Folder.Size(folder); than you can make it static.
If the method is inside Folder the problem is different.
Calculate something when i have something
The first thing that i think is Count (although this is a property), this is not static because this calculate something that is unique for every class.
If you want to do Folder.Size or Folder.Size() than, non static is your way to go.
Conclusion: Use static when a method don't belong to a class.
in this case no, since the size needs a Folder object and you must instantiate one, then add a method like CalculateSize() or GetSize() inside the class itself.
The most typical, OOP-ish, way to go here is an instance method. You shouldn't pass any parameters in but use this instead.
Using a static method within the Folder class itself would be counter-intuitive and possibly break encapsulation principles. The reason is, your method primarily operates on a specific Folder instance, and no decoupling of the funcionality away from the Folder class seems to be necessary in such a trivial case. The only valid case would be to support returning a fallback value, such as 0, in case a null reference would be passed in. However, in most cases being tolerant to such inputs causes problems later in the program's control flow.
You don't have to go full OOP and just do it with static.
Related
I use static methods for things I really MEANT to be static. I use ReSharper for better code quality. Sometimes ReSharper suggests that a method can be made static.
When I got the following class:
public class WhatEverClass {
private string DoSomethingFancy(string input)
{
string fancyStuff;
// Fancy Stuff here
return fancyStuff;
}
public WhatEverClass() {
string awesome=DoSomethingFancy("some fancy string");
}
}
ReSharper might say "DoSomethingFancy can be made static".
I know it could be made static, but is there a good reason to really do this? Or should I just ignore these suggestions?
By defining a method static, so a procedure that computes something, you manifest an intent to a consumer of your API about statelessness of your function.
When we use static function, we do not expect it saves a state of computation or some computed internal value somewhere in it's internal static private variables, so the next call to that function may have different result even with the same parameters passed during the first call.
In short: whenever you see a function that just executes an action over parameter and not preserve some state, it is a good candidate for making it static.
If your method doesn't need to say or change the state of an instanciated object, then it should be static.
The usual notion is , if you are not creating an instance of anything, you could declare it static. As to where it should be used, ReSharper gives you suggestions based on standard programming practices. However, i take 'standard programming practices' with a grain of salt. Its a matter of personal programming preference for some. Here is a detailed reference on the topic :
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
Because you will invoke the WhatEverClass() method from outside the class by creating WhatEverClass instance. So the value for every instance will be different, because the variable is local, and will be created every time you create an instance of the class.
But if you want to keep the same value for all instances, then you can make it static so it will be created once in a memory and all instances will use it.
Beware the consequences of making a method static!
By making your method static, you make it that much harder for consumers to stub out your implementation of the algorithm and replace it with one of their own (obviously if the method is private you have no such worries).
Consumers of your static method have your implementation baked in to their code - they cannot use dependency injection to resolve a specific instance of your algorithm (without a bit of work). This makes their system that much harder to test, and in general lends itself to a less extensible code base.
If the method DoSomethingFancy does not use anything in the object WhatEverClass then it should, in my book, be made static since it does not in fact have anything to do with the object in which it is used.
I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.
I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.
Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?
Hope this makes sense, and my question isn't too basic !
Many thanks
You need to think about static variables as belonging to the class, not to instances of the class.
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.
Best practice is to avoid public static. In OOP, class is meant to hide its members. Static is actually not a member of the instance but of the type.
Static comes handy if you are implementing singleton pattern. But then again they need to be made private and accessible through a public property.
You need to read Static Classes and Static Class Members (C# Programming Guide).
Well I can't conclusively say that one is better, because they serve different purposes.
Are you familiar with OOP? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.
C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).
In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?
The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)
However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)
For the sake of no further complicating things, I'll stop here. Let me know if you misunderstood anything.
Your choice depends on your architecture.
Static makes part of a Type, others make part of an instance of that type. If you want have some shared state (say) between different instances of the same type, use static. If you want that every instance have it's own value, independent from others, use instance fields.
In both cases, by the way, avoid to expose like a public fields, but use properties.
I completely agree with Mr Oded:
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance. And yes, it becomes a global resource, or even a global variable if you will.
But I think there's at least another (heavily edited) good point to be made here...
Using static members as global vars go against OOP
This means once you set a static member you can't pass it around as an object. The more you use static as global var, the more difficult it is for unit testing / mocking classes.
There is a solution for that, Singletons. But they should never come without warnings!
At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern. It's a not well known extension of Singleton pattern. It's so unknown in fact, if you google for it you won't find it with those keywords (toolbox pattern).
So plan ahead. Read more. Get to know about every option so you can decide better. Even get a book. Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.
In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that. This is for sure a principle that you will love to follow.
But despite some of the other answers I cannot say don't use static. Static is not the devil that you should avoid in any case. What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.
Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them. An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances. To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance. Especially if this factor changes in the lifetime of your program to affect the next calculation.
You need to ask a question to youself: why I need x to be static?
If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.
In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.
I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton
Lets say I have the following code
public static string GetXMLValue()
{
XDocument settingsFile = XDocument.Load("Settings.xml");
return settingsFile.Element("Settings").Element("GenericValue").Value;
}
It simply reads an XML Settings file and returns the GenericValue value. It can't be any simpler than that. Now my question is, would it provide any benifit (readability, performace, syntactically, maintainablitiy, etc.) to first place the return value in a string variable then return? Or is it best left the way it is?
To be honest, the simplicity of the methods makes it readable even in "one" line:
public static string GetXMLValue()
{
return XDocument
.Load("Settings.xml")
.Element("Settings")
.Element("GenericValue")
.Value;
}
There are a couple situations in which I see value in creating an auxiliary variable:
I want to assert something about it as a precondition (e.g. not empty string; a minimum/maximum length; etc.)
I am having trouble and I want to debug the value more easily.
Even in the absence of these, for such a nontrivial expression, I would create a local variable, to make the function more readable.
would it provide any benifit [...] to
first place the return value in a
string variable then return? Or is it
best left the way it is?
The function is so simple it just does not matter, so don't lose sleep about it. Once the function becomes more complex, you can always rethink this.
If for example you later need to run checks on the value before returning it, or want to log it for auditing reasons, a separate variable will make sense. Until then, leave it as it is.
As an aside:
What I find much more questionable is that you are reading an external resource (file) in a getter method. Invoking operations that can have side effects (such as reading a file) in a getter is bad style IMHO. That way for example every caller of the getter will have to handle IOExceptions from reading the file.
Consider changing this, for example by passing in the information via the constructor (either read the file from the constructor, or pass in an object that takes care of supplying the information). This will decouple your design, and simplify e.g. reuse and unit testing.
From a readability perspective, assigning the values to a variable and returning it would definitely help.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Properties vs Methods
When is it best to use a property or a method?
I have a class which is a logger. When I create this class I pass in a file name.
My file name for the log is fairly simple, basically it just gets the application path and then combines it with myapp.log.
Now instead of having the log file name lines in my method I want to create a new method to get this.
So my question is, since it's fairly simple, is creating a property a good idea instead of creating a method since there are no parameters.
Duplicate Properties vs Methods
Properties are typically used to store a state for an object. Method are typically used to perform an action on the object or return a result. Properties offer both getters and setters and can have different scope (at least in .NET 2.0). There is also some advantages to using a property vs methods for serialization or cloning and UI controls look for properties via reflection to display values.
Properties can be used to return simple values. Methods should always been used when fetching the value might incur any kind of performance hit. Simple linear operations can be fine in properties, though.
Ask yourself whether it's an aspect of your class (something it has) versus a behaviour of your class (something it does).
In your case, I'd suggest a property is the way to go.
I'd definitely go with the property. If you were doing something complex or computationally or time intensive, then you would go the method route. Properties can hide the fact that a complex operation is taking place, so I like to reserve properties for fast operations and ones that actually describe a property on the object. Simply: Methods "do" something, properties describe.
When you want to use it like a variable, you should go for a property. When you want it to be clear that this is a method, you should use a method.
As a property is a method, it depends on the semantic/design you want to communicate here.
Properties should be used to wrap instance variables or provide simple calculated fields. The rule of thumb that I use is if there is anything more that very light processing make it a method.
If you are not doing anything significant, use proerties.
In your case, a readonly property (get only) should be good.
Methods make sense when you are doing something other than returning reference to an internal member.
Properties are a design smell.
They are sometimes appropriate in library classes, where the author cannot know how the data will be used but must simply output the same value that was put in (e.g. the Key and Value properties of the KeyValuePair class.)
IMHO some uses of properties in library classes are bad. e.g. assigning to the InnerHTML property of a DOM element triggers parsing. This should probably be a method instead.
But in most application classes, you do know exactly how the value will be used, and it is not the class's responsibility to remind you what value you put in, only to use the data to do its job. Messages should exercise capabilities, not request information
And if the value you want is computed by the class (or if the class is a factory and the value is a newly-created object), using a method makes it more clear that there is computation involved.
If you are setting the log filename, then there is also the side effect of opening the file (which presumably may throw an exception?) That should probably be a method.
And if the filename is just part of the log message, you do not need a getter for the property, only a setter. But then you would have a write-only property. Some people find these confusing, so I avoid them.
So I would definitely go for the method.
The answer in the dupicate question is correct. MSDN has a very good article on the differences and when one should be used over an other. http://msdn.microsoft.com/en-us/library/ms229054.aspx
In my case I believe using the Property would be correct because it just returns the path of the exe + a file name combined.
If however I decided to pass a file name to get it to combine with the exe path, then I would use a method.
In C# you can refer to values in a class using the 'this' keyword.
class MyClass
{
private string foo;
public string MyMethod()
{
return this.foo;
}
}
While I presume the answer will likley be user preference, is it best practice to use the this keyword within a class for local values?
In the spirit of DRY, I would say this is not a particularly useful practice in general. Almost any use of this can be shortened to an equivalent expression by just removing the this.
One exception is if you have a local parameter which happens to have the same name as another class member; in that case you must distinguish between the two with this. But this is a situation you can easily avoid, by simply renaming the parameter.
I use the this keyword almost only when some member is hiding another, and when I need to pass the current class instance to a method for example:
class Employee
{
private string name;
private string address;
// Pass the current object instance to another class:
public decimal Salary
{
get { return SalaryInfo.CalculateSalary(this); }
}
public Employee(string name, string address)
{
// Inside this constructor, the name and address private fields
// are hidden by the paramters...
this.name = name;
this.address = address;
}
}
I would say it depends on personal preference for your own coding and on the team/company coding standards for your code at work. Personally, I try to keep both personal and "professional" coding standards the same--it reduces confusion, etc.
I prefer to use "this" on all class-level functions and variables. By using "this" you can immediately tell if the item is a class member or not. Also,I prefer to use "base" on members belonging to any base classes. It's not necessary, but it helps readability, esp if someone unfamiliar with your code is reading it.
I prefer this syntax. As the classes get larger and the functions get more complex, it is convenient to be able to read a variable name and know whether or not its an instance var without having to reference another part of the code.
Edit: I realize that if one is having trouble keeping track of variables, then it is probably time to refactor. This is fine in the abstract. So then to clarify: in the case where classes and their relationships aren't simple (and surely they exist) or in code where people have not refactored or followed good guidelines for keeping parameter names different from instance vars, I'll say (imho!) that using 'this' isn't a bad idea for clear code.
You're right - it's very much a preference thing. Of course, many companies enforce a set of coding style guidelines that either require this before any instance member, or require that it not appear. (Does anyone know what the Microsoft FxCop rules for the .NET framework are?)
Personally, I prefer to have this appear before any property, method or field that belongs to an instance. It makes it easier for me to distinguish where it belongs:
A member of an instance of the class (prefixed with this)
A static class member (which I prefix with the name of the class)
A local scope variable (no prefix)
It's more important to me to be able to read my code less ambiguously, than it is to save the 5 characters of this.. For instance, I immediately know that I need to dispose() all the local-scope items that were opened in this scope, and I won't confuse them with the instance-members that shouldn't be disposed. Heck, just for extra laziness points, I use this. as a quick way to access the intellisense list of member of the instance members.
In JavaScript, yes! In languages where it's not necessary, no. Some people do it to make the "memberness" visible to someone reading the code - but your IDE should be able to take care of that by highlighting it.
When VS 2010 comes out, my plan for world peace is to write an extension for the WPF code editor that displays this. in front of every reference to a member variable than doesn't already have that prefix. Then those who need that reminder will no longer need to type it, and those who don't like it can simply not install my extension and can freely delete any unnecessary this. prefixes they see.
I never use it. Mostly, it doesn't matter if a variable is a member or not. Keep your methods small enough that it's no problem to remember which variables are locals, and you won't mave so much trouble remembering which are members.
I use "_" as a prefix for member variables, as it is easy to ignore. But this means there will never be a collision with a local or parameter, so this. is not necessary.
My attitude may be "colored" by the fact that I use ReSharper, whose "color identifiers" mode makes it easier for me to see what's what.
I think that you should always include it if you are specifically referring to the class variable.
The reason for this is if you later on add in a local variable of the same name, you will need to rename all the class variables with this. so why not save your future self some time and hassle?