Related
This question already has answers here:
Exposing Member Objects As Properties or Methods in .NET
(7 answers)
Closed 9 years ago.
Which one is better to use when it come to return value for example
public int EmployeeAge
{
get{return intEmployeeAge};
}
And
public int EmployeeAge()
{
return intEmployeeAge;
}
Which one is better and why? And what is best programming practice to use when we have secnario like above ?
Properties are a useful way of expressing a feature of an object, allowing get/set in a common way that can be used by APIs like data-binding, reflection and serialization. So for simple values of the object, properties are handy. Properties can't take arguments, should not have significant side-effects*, and should return quickly and repeatably. Also, there is no such thing as an "extension property" (to mirror an extension method) nor a generic property.
(*=lazy loading etc isn't uncommon, however)
Methods (C# doesn't have functions) are better for expressing things that either change the state, or which have an expectation of taking some time and not necessarily being reproducible. They don't tend to work in binding / serialization etc.
Note that properties are actually just a special way of writing methods. There is little functional difference. It is all about expressing intent. The one thing you don't want to expose, however, is fields (the actual intEmployeeAge instance variable).
So I would have:
public int EmployeeAge { get{return intEmployeeAge}; }
or just (if on the Employee object):
public int Age { get{return intEmployeeAge}; }
Of course... then the question becomes "in what unit?" I assume that is years?
If all you need to do is return a value, use a property.
If you need to do something before returning a value, use a function.
Properties holds object data
Functions defines object behavior
Take a look at -> Property Usage Guidelines
Which one is better and why? And what is best programming practice to use when we have
secnario like above ?
I write in C# however I prefer to use Get/Set functions, for me it's just better way to express what I can get from object and how I can change it's state (and this methods are grouped by alphabet in Intelisense which is also nice). However, if team prefers other conventions it's not a problem but when I work on my own projects it's just easier to read API.
e.g
Obejct1 o = new Object1();
o.P1;
o.P2;
o.P3;
from looking to API you can't say what you change in a public API or what it a read only property, unless you use IDE that shows you a small icon showing actually what you can do.
Object1 o = new Object1();
o.GetP1();
o.SetP2();
o.SetP3();
One can easily find from API how data can be changed by type's clients.
A method returns values after work is completed and a value is the result of the work being done. I don't think this is what you are doing.
A property (accessor) is meant for returning variables, which seems to be what you're trying to achieve:
As per MSDN:
The accessor of a property contains
the executable statements associated
with getting (reading or computing) or
setting (writing) the property. The
accessor declarations can contain a
get accessor, a set accessor, or both.
The declarations take the following
forms:
public int EmployeeAge
{
get;
set;
}
Have a look here, as it gives a very good description on the uses of these.
Property is a way explore the internal data element of a class in a simple manner. We can implement a properties with the type-safe get and set method.Property is implicitly called using calling convention.Property works on compile and runtime.
Method is a block of code that contain a series of statements.Method is explicitly called.
Methods works on runtime.
I'm a little late to this party, but I'll just mention another surprising difference between a property and a parameterless "get" method. As #MarcGravell notes, lazy loading is a common pattern when using properties, but beware of the Heisenberg Watch Window gotcha!
I think this has a lot to do with the culture you are programming in. As I see it, the C# / .NET culture would prefer to use a property for this case.
My advice: Try to be consistent with the main libraries you are using.
BUT: Be wary of using properties (or functions that serve the same purpose, as in your example above), as they are often a sign of bad design. You want to tell your objects to do stuff, as opposed to asking them for information. Don't be religious about this, though, just be aware of this as a code smell.
This seems basic but Im finding this quite trivial. Simply how would you recommend setting a global variable with a static class (i.e. console-application)?
To give you a little more background the main method is calling some custom eventhandlers that I hope to get / set the variables.
Any ideas or suggestions you have is appreciated.
Simplest way is
public static Object MyGlobalVariable;
which creates a public static field. A little better is:
public static Object MyGlobalVariable { get; set; }
Which creates a public static property.
There are no global variables in C#. A variable is always locally-scoped. The fundamental unit of code is the class, and within a class you have fields, methods, and properties.
You can mimic a "global variable" by making a public static field or property in some class, but you shouldn't. C# makes this difficult for a very good reason; global variables are pure evil. They violate several good principles of OO design - encapsulation, loose coupling, and high cohesion, to name just a few.
I realize this is a beginner question, but I think it's because this is a beginner question that it's so important to be saying this. Now is the best time to start learning what tactics are actively discouraged or even dangerous in C#, and using a static field/property as a global variable is about six of them. There are legitimate uses for these constructs, but passing data around from place to place is not one of them.
If two different classes depend upon the same information, then pass the information from the source to the destination. This is usually done either through the constructor or as an argument to the method being called. You should always have one and only one instance that truly "owns" this information; making information "global" means that you can't reason about who or what might be depending on it at any given point in time.
Please consider this, and try to think about other ways you could share the information that you want to store in a global variable (i.e. by providing it as an argument to a constructor or method). If you're not sure, post an example of what you're trying to do and we'll help out.
Not 100% sure but you could try a singleton to hold your variables. Without knowing what you are trying to accomplish it's hard to recommend if this solution wouldn't bite you down the road.
http://www.yoda.arachsys.com/csharp/singleton.html
I admit I haven't grokked F# yet. But in the 30,000 foot descriptions, they keep talking about easy to test code that doesn't have mutable state. Is that the same as static methods?
Could I get the benefit of F# by writing some of my code in classes with all static methods?
I'm just looking for the short answer, I know whole books exist on the topic.
You could certainly write C# code immutably, but that's nothing to do with static functions. Immutability are things like having a struct or object that only "changes state" by making a copy of itself and having the copy be different.
Absolutely no, immutability has nothing to do with methods being static or instance. String, being an immutable class, has plenty of instance methods, which, in a very functional manner, return a new instance of String class, rather than modifying anything.
You could try to emulate F# by using functional decomposition, but this will still be pretty imperative code.
Apart from static, functional modules versus objects, you can attempt to get some of the benefits of F# by using C# 3 and lambdas, LINQ, etc. However, that doesn't go very far. What I find nice in F# is:
Inference everywhere
Auto-generalization (adds in type parameters so I don't have to sort it out manually)
Easy immutability
Easy mix between module and classes
Types like discriminated unions
Pattern matching
Nested functions (lightweight)
First class functions (no, C#'s named delegates don't count)
Everything's an expression
Easy function composition
So, you can try to do some of this in C#. Some of it is simply not supported and won't work. The rest gets very ugly, very fast.
So, if you go much off the beaten path of LINQ and the Enumerable extensions, you'll probably end up in a world of pain.
I beg to differ with all the other answers to date. Immutability and static methods may not be strictly technically related, but I have found that using F# has encouraged me to make C# methods static whenever I can.
The thinking is analogue, in that it is easier to handle an immutable object because you don't have to worry about it changing state. In the same way, you don't have to worry about state when using a static method (unless you use a global singleton or something...).
No, it's not the same as static methods. You don't have mutable state if you don't assign anything (locals, function arguments, static fields, instance fields) after it was initialized. You can get some of the benefits by designing your classes to be immutable.
No, the two concepts are unrelated. Static methods in C# can still modify incoming objects as normal, and other variables using ref or out.
IT's true. You aren't going to get the benefits of functional programming just by using more static functions in C#. Howver, if you were to look under the hood (using Reflector, for example) I understand a simple let statement is a static function. In other words,
//F#
let a = 2
is like a function in C#
//C#
static int a()
{
return 2;
}
I can understand the confusion.
Explanation pulled from Leon Bambrick's "F# Eye for the C# Guy presentation."
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?
I have a ASP.NET project, in which I have a method with 10 local variables. This method calls about 10 other methods. 3 of the called methods need all the variables. Is it considered good practice to turn all those variables into global members, and then they don't have to passed as parameters?
If you want to pass complex state around, package it in an object - i.e.
public class Foo {
public string Key {get;set;}
public decimal Quantity {get;set;}
// etc
}
And have the methods accept this object as an argument. Then you just create an instance of this and pass it along.
Global is a big no-no; ASP.NET is highly threaded - this would be a nightmare. Per-request state is possible, but a bit messy.
Do these variables relate to each other, either all of them or perhaps into a few groups? If so, encapsulate them into a type. So you might have half of your variables relating to a user, and half relating to a requested operation - and suddenly your method taking 10 variables only takes 2.
Making things global is almost always the wrong way to go.
create a structure instead and pass the structure instead of passing those 10 parameters
Eg :
public struct user
{
public string FirstName;
public string LastName;
public string zilionotherproperties;
public bool SearchByLastNameOnly;
public datetime date1;
}
Well, it depends entirely on what you mean by "global members".
If, considering you're writing an ASP.NET application, you mean session/application-based cache values, then it depends. There's performance implications so you should measure to see if it has any impact on your app.
If you mean static variables, then no. Static is per application, and will thus be for all users of your web application, not just one person. Thread static is not a good idea either as a single user may float between threads during his lifetime in the application.
If you have methods that truly do act upon a large number of variables, such as you mention, you can also consider designing a class that has the purpose of acting as a data container. Once populated, you can then pass the class to the functions that require the data instead of ten parameters.
I can not remember the exact example offhand, but in Microsoft's "Framework Design Guidelines" book, they explicitly describe a scenario like your as well as how they have followed the same approach in the .NET Framework.
Also, if you have the need to pass that many parameters, take a step back and make sure that the code in question does not need to be refactored. There are legitimate cases where a lot of data is needed by a method, but I use long method signatures as a sign that I need to look inside the method to make sure it is doing only what it needs to.
Just be sure to be conscious about boxing. If you are passing 10 ref types around, it comes down to personal preference.
However, if you are passing 10 value types, if you were to declare them as member variables within a class, they will be boxed, then they will have to be unboxed by the recipient.
If you leave them confined as local variables within the method stack(passing as parameters), they will remain purely on the stack, rather than being boxed to the heap.
For a purely mechanical refactoring, packaging the values together (as suggested) is probably the best solution.
However, you have a large series of dependent methods, each of which acts on common state (at least 10 values). It sounds like you should design a class to handle this operation.
The class would encapsulate the behavior and relevant state, rather than be a simple property bag (see Anemic Domain Model).