setting private properties of classes - performance

I have some very old code which uses reflection to set properties of objects, e.g something like this:
var properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
property.SetValue(obj, lookup[property.Name]);
}
I was thinking about replacing that code to make it faster. But because the above code also allows setting private properties of an object, I'm not sure what other options there exist.
Questions:
Am I correct, that compiled expressions (using System.Linq.Expressions) and generated code (using CodeDom / Microsoft.CSharp.CSharpCodeProvider) cannot be used to set private properties?
Would that be possible using Reflection.Emit?
Would any of the mapping libraries (AutoMapper, ValueInjecter) help for this (I don't know what technology they use internally)?
Are there other options?

The open source framework Impromptu-Interface has a static method InvokeSet uses the DLR rather than reflection, and it will call private methods. It runs a little over 2 times faster than reflection in the unit speed test case, which looks similar to yours.
using ImpromptuInterface;
...
foreach(var property in properties){
ImpromptuInterface.InvokeSet(obj, property.Name, lookup[property.Name]);
}

Related

p5.js - When to declare variables using var vs this.varName

I'm still figuring out how to use p5.js. In regular java you have to declare each variable using its data type, ex. int foo = 0.
In p5, I know you can just use var foo but you can also declare variables using this.foo. If someone could clarify when is the proper time to use var and when i can use this, that would be very helpful.
For example, if I want to declare a variable inside a method, should i use var foo = thing or could I declare it using this.foo = thing? What should I use when declaring global variables or when referring to objects passed into methods?
Thanks!
First of all, p5 is not a language, it is a Javascript library, you are coding in Javascript, not p5.
Coming to your question, if you want to use some function as a data type, similar to a class in java, and want all the "instances" of that to have their own different variables, you use this. If they are just variables you use in someway but don't need to be specific for each instance, or if the function is not a constructor function and is not to be used as a data type, you will just use var then.
Again, there is no class stuff in javascript, you will have to write what is called a constructor function in order to "simulate" a java class, but be aware that a constructor function should not return anything. Here is an example of car class in java:
class car {
int speed = ___;
String model = ___;
static int numOfWheels = ___;
}
This is what it will look like in javascript (a constructor function):
function car() {
this.speed = ____;
this.model = ____;
var numOfWheels = ___;
}
If you declare a variable without this, it can be roughly compared to a static variable in a java class in the sense that it will be constant among all the instances.
So basically, at least in most cases, you will use this.varName usually inside constructor functions, i.e., functions that you will use to construct objects.
What should I use when declaring global variables or when referring to objects passed into methods?
Global variables will almost always be var something = something. When referring to objects passed into functions, just use the dot notation to refer to its properties like passedObject.someProperty
I would recommend you to learn Javascript before jumping into p5 directly, here are some resources that I found useful when I started learning Javascript-
w3 School
JavaScript Info Website
TheNewBoston

Why should functions used for creating a Predicate be defined as static?

While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.
Consider the following Apple class for example :
public class Apple {
private String color;
private int weight;
private static final int SMALL_APPLE_MAX_WEIGHT = 150;
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public static boolean isGreenApple(Apple apple) {
return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
}
public boolean isBigApple() {
return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
}
}
I can now create a new predicate as follows :
Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;
As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?
For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.
So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.
Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.
static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.
This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.
But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.
Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.
I think, there are examples, like
Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;
which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.
What I am more interested in knowing is why are all examples on predicates shown using static methods?
The reference appears on the Class as no additional argument is required.
Any specific reason for not using instance methods?
For non-static methods that would make sense. In the case of
Predicate<Apple> isBigApple = Apple::isBigApple;
Predicate needs a argument so it takes this. An example of a non-method call would be something like
List<Apple> bigApples = new ArrayList<>();
apples.stream().filter(Apple::isBigApple).forEach(bigApple::add);

nashorn replace Java.type with binding

To invoke Java from JS you can use Java.type. Is there a way to bind a java class in the Bindings?
So replace:
scriptEngine.eval("Java.type('my.own.AwesomeObj')");
with something like:
Bindings bindings = new SimpleBindings();
bindings.put("AwesomeObj", my.own.AwesomeObj.class);
scriptEngine.setBindings(bingings, ScriptContext.GLOBAL_SCOPE);
I am working on a framework where I want to make a lot of classes available for the js scripts, and preferably not use a string concatenation and an eval. Currently it throws an exception with message: AwesomeObj is not a function, what makes sense.
Nashorn distinguishes a type from a java.lang.Class instance, just like Java does (in Java language, my.own.AwesomeObj is a type, while my.own.AwesomeObj.class is an instance of java.lang.Class. You can use a type to access static members, or as a constructor. You can't use a Class object for that purpose. The bad news is, you can't directly obtain the object that Nashorn uses for representing types; it's an instance of jdk.internal.dynalink.beans.StaticClass and it lives in a restricted package. However, you can evaluate it in script with
engine.eval("Java.type('my.own.AwesomeObj')");
and put the result of that in the bindings. Incidentally, within Nashorn, if you put the Class object into bindings under name AwesomeObjClass, you can use the synthetic property .static to obtain the type, e.g.:
var AwesomeObj = AwesomeObjClass.static;
In this sense, .static on a Class object is the dual of .class on a type object (.static obviously doesn't exist in Java, where types aren't reified as runtime objects).
var stringType = Java.type("java.lang.String");
var stringClass = stringType.class
print(stringClass instanceof java.lang.Class); // true
print(stringType === stringClass.static); // true
Hope this helps.
since Java 9 you can use jdk.dynalink.beans.StaticClass.forClass as it is not internal anymore:
Bindings bindings = engine.createBindings();
bindings.put("AwesomeObj", StaticClass.forClass(my.own.AwesomeObj.class));
then you can utilize the binding in the JS code with :
var awesome = new AwesomeObj();
In your top-level script of your framework do:
var AwesomeObj = Java.type("my.own.AwesomeObj");

Using #BeanProperty or Create Set & Get methods using scala

In scala Using #BeanProperty or Create Set & Get methods which is the right way
In functional programming and Scala in general you should always prefer immutable objects. But if you need to change the object state, then i would stick to (g|s)etters. Cause in this case you can without changing the internal state of the object return a new object with modified state.
class MyClass(val name) {
def setName(newName: String) = new MyClass(newName)
}
This way preserves immutability and gives you setters: setName(String) and getters: obj.name
#BeanPropery is used when you need high level of interoperability with some Java code, it helps you quickly generate (g|s)etters for your code, but it has some constraints cause you cannot give the names to this methods which you would like.
Although i recomend to use case classes with copy method:
case class Person(name: String, age)
val me = Person("Alex", 23) // create an object
val afterBD = me.copy(age = 24)
The same semantics, but purely functional approach without any mutable internal state.
And as for Spring framework in Scala. I've never work with it (thank God =)), but there is a good post on this topic

What's so great about Func<> delegate?

Sorry if this is basic but I was trying to pick up on .Net 3.5.
Question: Is there anything great about Func<> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc<> with the exact 5 overloads and even more.
eg: public delegate TResult MyFunc<TResult>() and a combo of various overloads...
The thought came up as I was trying to understand Func<> delegates and hit upon the following scenario:
Func<int,int> myDelegate = (y) => IsComposite(10);
This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?
So am I justified in saying that Func<> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func<>" delegates to suit our own needs?
Thanks,
The greatness lies in establishing shared language for better communication.
Instead of defining your own delegate types for the same thing (delegate explosion), use the ones provided by the framework. Anyone reading your code instantly grasps what you are trying to accomplish.. minimizes the time to 'what is this piece of code actually doing?'
So as soon as I see a
Action = some method that just does something and returns no output
Comparison = some method that compares two objects of the same type and returns an int to indicate order
Converter = transforms Obj A into equivalent Obj B
EventHandler = response/handler to an event raised by some object given some input in the form of an event argument
Func = some method that takes some parameters, computes something and returns a result
Predicate = evaluate input object against some criteria and return pass/fail status as bool
I don't have to dig deeper than that unless it is my immediate area of concern. So if you feel the delegate you need fits one of these needs, use them before rolling your own.
Disclaimer: Personally I like this move by the language designers.
Counter-argument : Sometimes defining your delegate may help communicate intent better. e.g. System.Threading.ThreadStart over System.Action. So it’s a judgment call in the end.
The Func family of delegates (and their return-type-less cousins, Action) are not any greater than anything else you'd find in the .NET framework. They're just there for re-use so you don't have to redefine them. They have type parameters to keep things generic. E.g., a Func<T0,bool> is the same as a System.Predicate<T> delegate. They were originally designed for LINQ.
You should be able to just use the built-in Func delegate for any value-returning method that accepts up to 4 arguments instead of defining your own delegate for such a purpose unless you want the name to reflect your intention, which is cool.
Cases where you would absolutely need to define your delegate types include methods that accept more than 4 arguments, methods with out, ref, or params parameters, or recursive method signatures (e.g., delegate Foo Foo(Foo f)).
In addition to Marxidad's correct answer:
It's worth being aware of Func's related family, the Action delegates. Again, these are types overloaded by the number of type parameters, but declared to return void.
If you want to use Func/Action in a .NET 2.0 project but with a simple route to upgrading later on, you can cut and paste the declarations from my version comparison page. If you declare them in the System namespace then you'll be able to upgrade just by removing the declarations later - but then you won't be able to (easily) build the same code in .NET 3.5 without removing the declarations.
Decoupling dependencies and unholy tie-ups is one singular thing that makes it great. Everything else one can debate and claim to be doable in some home-grown way.
I've been refactoring slightly more complex system with an old and heavy lib and got blocked on not being able to break compile time dependency - because of the named delegate lurking on "the other side". All assembly loading and reflection didn't help - compiler would refuse to just cast a delegate() {...} to object and whatever you do to pacify it would fail on the other side.
Delegate type comparison which is structural at compile time turns nominal after that (loading, invoking). That may seem OK while you are thinking in terms of "my darling lib is going to be used forever and by everyone" but it doesn't scale to even slightly more complex systems. Fun<> templates bring a degree of structural equivalence back into the world of nominal typing . That's the aspect you can't achieve by rolling out your own.
Example - converting:
class Session (
public delegate string CleanBody(); // tying you up and you don't see it :-)
public static void Execute(string name, string q, CleanBody body) ...
to:
public static void Execute(string name, string q, Func<string> body)
Allows completely independent code to do reflection invocation like:
Type type = Type.GetType("Bla.Session, FooSessionDll", true);
MethodInfo methodInfo = type.GetMethod("Execute");
Func<string> d = delegate() { .....} // see Ma - no tie-ups :-)
Object [] params = { "foo", "bar", d};
methodInfo.Invoke("Trial Execution :-)", params);
Existing code doesn't notice the difference, new code doesn't get dependence - peace on Earth :-)
One thing I like about delegates is that they let me declare methods within methods like so, this is handy when you want to reuse a piece of code but you only need it within that method. Since the purpose here is to limit the scope as much as possible Func<> comes in handy.
For example:
string FormatName(string pFirstName, string pLastName) {
Func<string, string> MakeFirstUpper = (pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
};
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
It's even easier and more handy when you can use inference, which you can if you create a helper function like so:
Func<T, TReturn> Lambda<T, TReturn>(Func<T, TReturn> pFunc) {
return pFunc;
}
Now I can rewrite my function without the Func<>:
string FormatName(string pFirstName, string pLastName) {
var MakeFirstUpper = Lambda((string pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
});
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
Here's the code to test the method:
Console.WriteLine(FormatName("luis", "perez"));
Though it is an old thread I had to add that func<> and action<> also help us use covariance and contra variance.
http://msdn.microsoft.com/en-us/library/dd465122.aspx

Resources