Can a "pure" function reference a property? - c#

A pure function is one which given the same arguments, will always return the same result and will have no side effects.
So Sum(x,y) => x + y; is pure because it meets this criteria.
However, in a language like C# where you can have properties, this makes things more complicated...
class Summer
{
public int X { get; set; }
public int Y { get; set; }
public int Sum() => X + Y;
}
In the above, can Sum be considered to be pure? Can you make the argument that X and Y are still just parameters to the function?
Or would it be better if refactored to something like:
class Summer
{
public int X { get; set; }
public int Y { get; set; }
}
static class SummerExn
{
public static int Sum(this Summer s)
{
return s.X + s.Y;
}
}
In the extension method, s is a parameter so this meets the criteria for being pure I think, but realistically there is no practical difference since the underlying variables are the same. Would there be a technical reason this code is better, such as being more easily tested, faster, more memory efficient, easier to logically reason about etc. ?

Your example doesn't meet the definition you gave:
A pure function is one which given the same arguments, will always return the same result...
Every call is given the same arguments (none) yet obviously can return different results. Another definition from Wikipedia makes this a little more explicit:
The function return values are identical for identical arguments (no variation with local static variables, non-local variables...)
Properties are non-local variables.
And to be especially pedantic, not only is your example not a pure function, it's not a function at all. A function-like thing that's a non-static class member is called a method.

Related

Auto-property vs property with a field

Is there any difference between these two?
int a;
public int A
{
get => a;
set => a = value;
}
public int A { get; set; }
public int A { get; set; }
is the exact same as saying:
private int _a;
public int A
{
get => _a;
set => _a = value;
}
Auto-properties are simply syntactic sugar for a private field, and public getters and setters. It allows you to access and mutate a field (as a property) without the boilerplate of getter and setter methods. We must always encapsulate our data, and properties aim to speed up the process of writing that out
If this was java, you would have something like:
private int a;
public void setA(int a){
this.a = a;
}
public int getA(){
return a;
}
When creating classes in java, you have to by force of habit define your getters, setters, hash code, and to string methods. Of course, modern IDE's will literally generate the stock implementations of these for you, but mentally it becomes a given. If there is no special logic in any of these methods that we routinely create, why be forced to write it out? Auto-props aim to take away a bit of the hassle. It just a quality-of-life bit of syntax for cleaner looking code. It tells you upfront that you have the stock accessors and mutators out of the box
Its also quite modular, take a look at the documentation to see how you can make for things like private setters, use init for immutability post-obj construction, etc
Its almost always preferable to use public properties over public fields in C#, easiest way to remember is: private fields, properties for any access mod above that

Sort (Array array, System.Collections.IComparer? comparer) - parameter or implementation?

The Methode Array.Sort() has the following signature
public static void Sort (Array array, System.Collections.IComparer? comparer);
It looks like you need to pass an IComparer reference. But what is really needed is that array needs to implements IComparable, isn't it?
I see this syntax the first time. Is this common? How can I differentiate between a real parameter? Is there somewhere more information about this topic (in general)?
Important/Edit: ATM I'm reading a C# book and it says about Sort.Array (translated from German to English):
To the first parameter we pass the array to be sorted, in our case
arr. The second parameter is of type IComparer interface. Of course,
you can't pass an instance of type IComparer to the method call,
because interfaces are not instantiable. This is not how the type
specification of the second parameter should be understood. Instead,
the second parameter simply requires that the fist argument passed to
it be an object that implements the interface IComparer - whether the
object is of type DemoClass, Circle,
Basically he says that the second parameter is kind of a description for the first parameter. Is he correct or maybe that's just wrong and the source for my confusion?
https://openbook.rheinwerk-verlag.de/visual_csharp_2012/1997_04_008.html
I just implemented the following snippet. So this could be a way how to pass the second parameter, right?
Array.Sort(shapes, (a, b) => {
if (a.GetArea() < b.GetArea()) return -1;
else if (a.GetArea() > b.GetArea()) return 1;
return 0;
});
If you do not pass the comparer it will use the default comparer implementation for the Array items. But if you have a special comparer then you can pass your own custom Comparer to sort the elements.
Suppose you have a Class of Students (Array of Students), and your default Student comparer can be based on total marks. However, a maths teacher may want to sort the Students based on marks for the Maths only, in that case maths teacher can write his custom MathsRankComparer and pass it to the Sort method so that he will get the Students ordered by marks in Maths.
Similarly, English or Science teacher can pass the respective comparers to get their required ranking/ordering/sorting.
Hope this helps in understanding use of that overload.
Update: some examples to understand details.
public class Student: IComparable<Student>
{
public int ID { get; set; }
public string Name { get; set; }
public float TotalMarks { get; set; }
public float ScienceMarks { get; set; }
public float MathsMarks { get; set; }
public float EnglishMarks { get; set; }
public int CompareTo(Student other)
{
if (this.TotalMarks == other.TotalMarks)
return 0;
if (this.TotalMarks < other.TotalMarks)
return -1;
return 1;
}
}
public class MathsMarksBasedComparer : System.Collections.Generic.IComparer<Student>
{
public int Compare(Student a, Student b)
{
if (a.MathsMarks == b.MathsMarks)
return 0;
if (a.MathsMarks < b.MathsMarks)
return -1;
return 1;
}
}
public class EnglishMarksBasedComparer : System.Collections.Generic.IComparer<Student>
{
public int Compare(Student a, Student b)
{
if (a.EnglishMarks == b.EnglishMarks)
return 0;
if (a.EnglishMarks < b.EnglishMarks)
return -1;
return 1;
}
}
And finally, you can use them like this.
Student[] arr = new Student[100]; // Ignore this, you can use other styles of declaration
Array.Sort(arr, new EnglishMarksBasedComparer());
Array.Sort(arr, new MathsMarksBasedComparer());
Array.Sort(arr);
Basically he says that the second parameter is kind of a description for the first parameter. Is he correct or maybe that's just wrong and the source for my confusion?
It's not wrong it's just worded a bit confusingly.
The IComparer is a nullable type (defined by the questionmark at the end of IComparer). This states that the IComparer is optional/does not have to be passed. However as Mahesh Bongani already meantioned in his reply - internaly if you do not provide a comparer it takes the defualt comparer of the object.
So for this particular funtion if you would pass a Array with objects that do not implement a comparable the function wouldn't be able to sort the elements properly.
I have seen IComparer a few times and am unsure what implements it as standard - as far as lists, arrays and things go. I do know that numbers implement it and I think string does too.
You can though custom implement this inferface. If memory serves me correctly, it provides just one method (interface so you have to write logic yourself) that returns an int. -1 (<0) is lower ranked, +1(>0) is higher ranked, 0 is the same.

Difference between Expression-Bodied Properties and simple Getter Properties

After reading some source code of different c# project i noticed different ways of writing (almost) the same statement regarding public "getter" and private "setter" properties.
First way with only properties:
public int x { get; private set; }
Second way with expression-bodied properties:
private int _x;
public int x => _x;
I know that public int x { get; } is equivalent to
private readonly int __x;
public int x { get { return __x } }
So I understand the difference between expression-bodied and normal properties in the case of a single "getter".
What i do not understand is the difference when there is a private field that holds the referenced value. I thought that maybe the second one is faster because you have access to the field directly instead of a method call inside your class.
Is it just a stylistic difference or is one of the examples faster, more robust, etc?
You have two groups of constructs which are equivalent.
Group 1
When you don't need write access to the backing field outside the constructor, you can use any of these constructs:
private readonly int _x;
public int x => _x;
or
private readonly int _x;
public int x { get => _x; }
or
private readonly int _x;
public int x { get { return _x; } }
or
public int x { get; }
Group 2
When you need access to the backing field outside the constructor, you can use any of these constructs:
private int _x;
public int x => _x;
or
private int _x;
public int x { get => _x; }
or
private int _x;
public int x { get { return _x; } }
or
public int x { get; private set; }
You can expect all of the alternatives to be equally fast. In the last construct the compiler will inject a setter method (it will inject a backer field too, as for every automatic property). In the other cases you access the field directly. The injected setter will almost certainly be inlined by the jitter, which removes the performance penalty of a method call. Check this Q&A for details on JIT inlining.
The automatic property is certainly more concise, which makes your code neater, especially when you have many properties. But at the end of the day it comes down to personal preference (or your team's coding rules).
If you use a private backing field, You are encapsulating the information and creating more robust code. It also improves the readability in some cases.
There is also the fact that the value is stored safely in a field and so if you have logic within your getters and setters that needs to change in the future it is separated from the actual value store and makes changing that implementation easier in future
Note that there's even another possibility if you initialize the property in the constructor
public int X { get; }
This is a getter-only property introduced in C# 6.0. You can assign it in the constructor (and then never again)
public MyClass (int x) // Constructor
{
X = x;
}
or with an initializer
public int X { get; } = 100;
You should not care about speed for those things. Create an easy to read and robust code. The C# compiler or the Jitter (Just In Time compiler running when the application starts, and methods are called for the first time) will possibly inline the code and not even call the getter or the setter.
The difference between normal and expression-bodied properties, methods and constructors is only of syntactical nature. There is no difference in behavior. Both variants produce the same compiled IL code and therefore, there is no difference in speed.
public int X => _x; is simply a shorter syntax for public int X { get { return _x; } }. This is also called syntactic sugar.

Get Property Optimization when using loops

If I use loops in the get of a property, does this mean every time I call get on the property, it executes the loop? For eg, below, if I call CartViewModel.Total, does this mean it executes the loop inside SubTotal and Discount?
public class CartViewModel
{
public decimal SubTotal { get { return CartViewItems.Sum(c => c.Price); } }
public decimal Discount { get { return CartViewItems.Sum(c => Total-SubTotal); } }
public decimal Total { get { return SubTotal-Discount; } }
public List<CartViewItem> CartViewItems { get; set; }
}
public class CartViewItem
{
public decimal Price { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public float DiscountPercent {get; set;}
public decimal SubTotal { get { return Price*Quantity; } }
public decimal Total
{
get
{
return Convert.ToDecimal(((float)Price * (1 - (DiscountPercent / 100))
* Quantity));
}
}
}
Is there a way to optimize this?
Yes, every time you call the property, it will execute the loop.
Properties are really just syntactic sugar over method calls. Very nice syntactic sugar, but only sugar.
You might want to change CartViewModel to avoid exposing the list directly - instead, keep the list private, give some appropriate methods to mutate it (e.g. Add and Clear methods), probably make it implement IEnumerable<CartViewItem> itself, and keep track of the subtotal and discount as the list is mutated. That's assuming that CartViewItem is immutable, of course...
Alternatively (as John suggested), just make it more obvious that you're actually doing work, changing the properties to ComputeTotal(), ComputeDiscount() and ComputeSubTotal() methods.
I would recommend the "don't do that" approach.
Properties are meant for cases where the data being accessed are "almost like a field" in terms of performance and semantics. They are definitely not meant for cases where the property hides the fact that a more expensive operation is being performed.
Replace those properties with methods and see whether the calling code changes much. It will be clearer that you are doing something potentially expensive.
Depending on how often those are referenced, I might go further and inline the properties entirely. That might suggest some optimization in the callers.

Is there an equivalent of 'this' in C# for static members?

Is there an equivalent of this in C# for static members?
I like to use this to make my code more readable, but wondered if there was an equivalent for static members.
I suppose if you use this. to reinforce that you are referring to instance members, the equivalent in a static member would be to use ClassName.
But stylistically, why add code that doesn't change meaning?
edit to add various clarifications:
My last sentence above can be illustrated with these examples:
class Example1
{
public int J { get; set; }
public Example1()
{
J = 0;
}
// These two methods have *exactly* the same CIL
public int InstanceMethodLong()
{
return this.J;
}
public int InstanceMethodShort()
{
return J;
}
}
The this. in InstanceMethodLong does not change the meaning as compared with InstanceMethodShort.
Statically:
class Example2
{
public static int K { get; set; }
static Example2()
{
K = 0;
}
// These two methods have *exactly* the same CIL
public int StaticMethodLong()
{
return Example2.K;
}
public int StaticMethodShort()
{
return K;
}
The Example2. in StaticMethodLong does not change the meaning as compared with StaticMethodShort.
In both these cases, adding the qualifier results in the same CIL, the same behaviour, and is more source to write, read, and understand. Stylistically - and I will happily accept that this is a question of code style - I see no reason for it to be there.
With underscore prefixes the situation is slightly different:
class Example3
{
int _j;
public int J
{
get { return _j; }
set
{
_j = value;
// and do something else,
// to justify not using an auto-property
}
}
public Example3()
{
J = 0;
}
public int MethodWithParameter(int j)
{
// Now there is a *difference* between
return j;
// and
return _j;
}
}
Here, in MethodWithParameter, there is a difference between referring to _j and j - so we are deliberately and explicitly expressing different meaning. It's true that the compiler doesn't care what we call our variable names, but it does care what variables we are referring to! So in the body of MethodWithParameter, using or not using an underscore isn't just stylistic, it's semantic. Which isn't the particular issue we're addressing in this question.
As a static member is not meant to belong to any particular instance (as this refers to an instance of an object, with different settings possible per instance), what you would instead want to do is use ClassName.Member instead of this.Member.
public class Orange
{
public static string Tastes = "sweet";
public static string FoodType(){
return "fruit";
}
}
Would be called by:
Console.WriteLine(Orange.Tastes);
Same goes for static methods, as well:
Console.WriteLine(Orange.FoodType()).
Please note this is a contrived example for demonstration only. :)
You may able to use the class name to reference other static properties.
Your code becomes a bit more resistant to copy/paste but that's not always a bad thing.
Unfortunately no, there is no this for static methods. To help differentiate static members from class members I prefix it with the class name.
class Test {
static Regex TextRegex = new Regex(...);
public static bool TestString(string input) {
return Test.TextRegex.IsMatch(input);
}
}
I like "this" as well to realsie from the first look where the state is changing. You may want to consider type's name for static members in this case.

Categories