What reason is there for C# or Java having lambdas? - c#

What reason is there for C# or java having lambdas? Neither language is based around them, it appears to be another coding method to do the same thing that C# already did.
I'm not being confrontational, if there is a reason I would like to know the reason why. For the purpose of full disclosure I am a Java programmer with a C++ background with no lisp experience, I may just be missing the point.

There are common use-cases which require passing (or storing) a block of code to be executed later. The most common would be event listeners. Believe it or not, the following bit of code uses a lambda-ish construct in Java:
JButton button = new JButton("Push me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed!");
}
});
The anonymous inner-class is acting as a lambda, albeit an extremely verbose one. With a little bit of implicit conversion magic, we can write the following equivalent in Scala:
val button = new JButton("Push me!")
button.addActionListener { e =>
println("Pressed!")
}
C# makes this sort of thing fairly easy with delegates and (even better) lambdas.

I see lambdas in C# as a very convenient short-cut for doing delegates. Much more readable to have the code right there where it is being used rather than having to search elsewhere for the delegate definition.

Syntactic Sugar.
It provides a convenient and more-readable way to represent an idea, in this case a tiny throw-away method. Under the hood, the compiler expands that out to a delegate and method call, but it's the thing doing the work, not you.

Lambdas allow you write less verbose, more expressive code. For example, list comprehensions...
BTW, work is under way to explore the possibility of adding closures to Java - in the meantime it is necessary to use anonymous classes instead (ugly).

C# isn't going for purity to a particular school of language design (unlike Java, which was designed by the Smalltalkers as to be something of a pure OO language). C# is going for all-things-to-all-people, and it's pretty good at it. C# is based around gathering the best of the various styles of programming into one high-quality, well-supported language. That includes procedural, object-oriented, functional, dynamic, logic, etc. styles of programming. Obviously, so far it doesn't have much in the way of dynamic or logic styles of programming, but that is soon to come (dynamic programming coming with C# 4.0).

In case of C#, lambdas are used internally to implement LINQ. See the article The Evolution Of LINQ And Its Impact On The Design Of C#

Lambda's allow for more readable code in that they allow operations to be defined closer to the point of use rather than like the current C++ method of using function objects whose definition is sometimes far from the point of use. (This is not including some of the boost libraries). I think the key point from lambdas is that they allow more concise and easy to understand code.

They offer better security using the multi threading in Java by implying in many cases the "final" option. So you are not error prone for multitasking.

Related

How to prepare for a Java evaluation from a C# programmer's point of view?

I've been offered to be dispensed of classes in computer science in college, as the teacher noticed I obviously knew the introduction to coding. I'm extremely fluent in C# and with most programming concepts, so the exam shouldn't be so hard. I can also code in other languages such as C++, C, Lua, PHP, VB, etc.
I'm not caring about passing or not, my point is rather that this exam will be my only grade for the term. Therefore I'd like to get it right.
Let's assume I have ~2 weeks to prepare, I'd like to know where to start from. I obviously don't need to learn any concept (i.e. what is a variable, how to use classes, what is inheritance, etc.), since these are the same in most languages (or in that case, C# and Java).
I'd assume I have to get familiar with the slight syntax changes (string -> String, bool -> boolean) and system differences (i.e. Scanner for input, imports vs usings).
I've found the following page for most syntax changes:
http://it.toolbox.com/blogs/codesharp/java-for-c-developers-21248
From what I know, the test will variables and values, basic operators, logical structures (i.e. if/else, for, while), functions and structs. As far as I can remember, classes aren't seen this term.
I was interested in knowing what tips the S/O community could give me. Thanks in advance!
Well, first it really depends on the difficulty of your exam. You could have an exam on general POO in java or on more specific points, like generics, Collections, Threads.
And a thing you need to see, it the way the inheritance works in java. Methods inheritance isn't really working the same way.
Resources :
A comparison of Microsoft's C# programming language to Sun Microsystems' Java programming language
This is just one of many examples, yet one of the biggest for me was creating getters/setters in Java compared to C#. C# has very nice shortcuts which you are probably use to.
Public string ExampleString { get; set; }
With Java you have to create methods instead.
private string _exampleString;
public string getExampleString()
{
return _exampleString;
}
public void setExampleString(string exampleString)
{
_exampleString = exampleString;
}
This is fundamentally the same way C# handles it, but you do not have the shortcut in Java. Ultimately to learn and get use to the differences your going to have to bite the bullet and write quite a few test programs. Especially if you need to know/understand Java UI, such as swing. Which I had to write my final project in swing when I took Java in school.
Code in Java? Sounds easy, but it is, basically try doing a few "basic" things in java, IE make a linked list, some data structures.
Try to code in Java, create something simple that you have already created in C# and than come to SO if you have any questions or queries and learn from the answers. I would suggest practicing would be of great help.
To get the feeling of programming in the language I would suggest Project Euler, which requires you to write solutions to smallish programming problems.
The best way to learn is to write programs, and you need to practice a lot to prepare.
If you are allowed to use eclipse or netbeans as part of the evaluation then the most important thing you could do is get used to using those tools. Either of those could have you coding productively in Java within the hour because they will advise you on syntax issues and give you lists of choices so you don't have to look things up so often.
For instance, what is the method to grab a sub-chunk of a string. If you have an object of class "String" and hit strObject.(ctrl-space) it will give you a list of all the methods on string along with the parameter numbers and types. Oh and it will give you all the docs for this method as well.
If not, I'd get used to the JDK description on the Java website, you'll be using it more than Java syntax itself.
As for the Syntax, Java is pretty straight-forward. If you are coding in a GUI it will probably just fix your syntax for you.
If it's an in-class written (non-code) test, you may have to get used to some little differences like public/protected/private/package indications (package is the trickiest).
Code some stuff, use Eclipse.
NB: Generics are hell in Java. Using a library that is "generified" correctly is simple, but coding generic classes and methods are often rather intense.

ExpandoObject (dynamics) my greatest friend or my new greatest foe?

Yes I know that it shouldn't be abused and that C# is primariy used as a static language. But seriously folks if you could just dirty up some code, in the python style, or create some dynamic do hicky, would you?
My mind is working overtime on this having spent a while loving the dynamics of python, is c# going over to the dark side through the back door?
Is the argument for static typing a dead one with this obvious addition?
Is the argument for less Unit testing a bit silly when we are all grown ups?
Or has the addition of dynamics ruined a strongly static typed and well designed language?
I lost the desire to use dynamic types when I started using type inference.
C# has expanded to including some aspects of dynamic typing, yes, but that doesn't mean that static typing is dead. It simply means that C# has added some tools that allow developers of all persuasions to solve all kinds of problems in many different ways.
I have a problem with the concept of one type system being "better" than another. That is like saying a hammer is better than a screwdriver. Without know the context of the task at hand it is impossible to make that determination! Dynamic typing is better than static typing for certain problems and situations and vice-versa. The superiority of the approach is entirely conditional on the problem at hand.
So to stick with my tool analogy, it is best to have a toolbox that contains hammers and screwdrivers and know how to use each efficiently. This will make you a better developer as you will be best equipped to solve any problem you face. C#'s new dynamic typing additions are simply an effort to help you by providing these tools in a single, convenient package.
Is the argument for static typing a
dead one with this obvious addition?
Is the argument for less Unit testing
a bit silly when we are all grown ups?
Or has the addition of dynamics ruined
a strongly static typed and well
designed language?
For a while, languages have been moving more and more into the domain of "statically typed when possible, dynamically typed when necessary". And with structural typing (statically checked duck typing) starting to work its way into mainstream languages, we might see languages evolve to the point where they're basically statically checked Python.
For what its worth, dynamically typed code is just as mindful of types as statically typed code. Idiomatic C# is still statically typed, and will remain that way for a long time to come.
As I understand it, the dynamic keyword was introduced more to facilitate interop and method invocation on unknown types at runtime rather than the kind of dynamic typing you find in languages like python.
Essentially, where you would previously have to call InvokeMember to call a method on an unknown type, you would instead create a dynamic object and just call the method, which would be resolved at runtime. The code becomes a great deal easier to read. Why would you want to call a method (or access a property) on an unknown type? Well, WPF does it all the time when you use databinding.
You also use it when you want to use an interop dll using weak binding, such as for example, if you wanted to write code that used office interop, but you wanted to support more than one version of office. I've had to do this before, and the code for it is horrendous. The dynamic keyword would make such code far easier to read and understand.
See this article for more info:
http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx
As far as i remember, type errors is about 5-10% of all found errors, so we have fewer errors for languages with static typing for free. Unit and regression tests is also a few smaller for static typing.
Dynamic typing is nice for OO languages. In case of FP language (and with HM type system especially) dynamic vs static typing don't impact your decisions of program design at large.
But there is moment where you want nice code performance and that moment will show dark side of dynamic types to you.
Yes.
No.
No.
Yes.
No.
Strong typing is still the best way to go for large projects. Not only does it make code completion (IntelliSense) much better, but it can tell you obvious problems at compile time. For example, say socket.Write takes a string. In C# you won't be able to run your program if you try to pass it a number, while in Python you would only find out about your bug when your program crashes.
On the other hand, it's easy to imagine how useful it would be to have a JSON parser that acts like an expando object, automatically growing the properties specified in the JSON.
To elaborate my point a bit, I think C# will mostly stay safe from the evils of dynamic typing, while still reaping its benefits. This is because the system still encourages types on everything, as opposed to other dynamic languages where types are entirely optional (or even just advisory). In C# you will be able to just "git 'er done" with duck typing, expando properties, and other dynamic typing goodness, but it will be well-marked with the dynamic keyword which helps you to keep it self-contained.

Dynamic code generation

I am currently developing an application where you can create "programs" with it without writing source code, just click&play if you like.
Now the question is how do I generate an executable program from my data model. There are many possibilities but I am not sure which one is the best for me. I need to generate assemblies with classes and namespace and everything which can be part of the application.
CodeDOM class: I heard of lots of limitations and bugs of this class. I need to create attributes on method parameters and return values. Is this supported?
Create C# source code programmatically and then call CompileAssemblyFromFile on it: This would work since I can generate any code I want and C# supports most CLR features. But wouldn't this be slow?
Use the reflection ILGenerator class: I think with this I can generate every possible .NET code. But I think this is much more complicated and error prone than the other approaches?
Are there other possible solutions?
EDIT:
The tool is general for developing applications, it is not restricted to a specific domain. I don't know if it can be considered a visual programming language. The user can create classes, methods, method calls, all kinds of expressions. It won't be very limitating because you should be able to do most things which are allowed in real programming languages.
At the moment lots of things must still be written by the user as text, but the goal at the end is, that nearly everything can be clicked together.
You my find it is rewarding to look at the Dynamic Language Runtime which is more or less designed for creating high-level languages based on .NET.
It's perhaps also worth looking at some of the previous Stack Overflow threads on Domain Specific Languages which contain some useful links to tools for working with DSLs, which sounds a little like what you are planning although I'm still not absolutely clear from the question what exactly your aim is.
Most things "click and play" should be simple enough just to stick some pre-defined building-block objects together (probably using interfaces on the boundaries). Meaning: you might not need to do dynamic code generation - just "fake it". For example, using property-bag objects (like DataTable etc, although that isn't my first choice) for values, etc.
Another option for dynamic evaluation is the Expression class; especially in .NET 4.0, this is hugely versatile, and allows compilation to a delegate.
Do the C# source generation and don't care about speed until it matters. The C# compiler is quite quick.
When I wrote a dynamic code generator, I relied heavily on System.Reflection.Emit.
Basically, you programatically create dynamic assemblies and add new types to them. These types are constructed using the Emit constructs (properties, events, fields, etc..). When it comes to implementing methods, you'll have to use an ILGenerator to pump out MSIL op-codes into your method. That sounds super scary, but you can use a couple of tools to help:
A pre-built sample implementation
ILDasm to inspect the op-codes of the sample implementation.
It depends on your requirements, CodeDOM would certainly be the best fit for a "program" stored it in a "data model".
However its unlikely that using option 2 will be in any way measurably slower in comparision with any other approach.
I would echo others in that 1) the compiler is quick, and 2) "Click and Play" things should be simple enough so that no single widget added to a pile of widgets can make it an illegal pile.
Good luck. I'm skeptical that you can achieve point (2) for anything but really toy-level programs.

Why does Java not use the out parameter in its language syntax while c# does?

While I am not a huge fan of using the out parameter in c# I would like to know why Java chose not to include it in its language syntax. Is there any special reason or maybe its because a person can simply pass an object as a parameter type?
Probably because the designers didn't feel the need to allow for multiple ways of returning objects.
The same question can be asked about delegates, generic, etc.
But the fact of the matter is that the C# designers learned from Java's mistakes/inconveniences, which is why many I've spoken to feel C# is the nicer language to work with.
Java was designed to be a very simple language, with a very simple syntax - a kind of "Spartan OO programming language" in contrast to C++ with its abundance of features that hardly anyone knows and understands completely (including compiler implementors).
Basically, features were omitted unless they were perceived to be absolutely necessary.
On one hand, the goal was achieved - there are very few areas in which Java's behavior is hard to understand or predict.
On the other hand, the missing features have to be worked around, which leads to Java's oft-maligned verbosity. The designers of C# tried to build on this experience.
However, I personally wouldn't count out parameters as a great loss.
The number 1 use case for out parameters is smooth interop with native code.
As Java does not prioritise smooth interop with native code, it doesn't especially need this feature.
There's no logical need for output or ref parameters. As they are available, they have become part of a common idiom in the CLR languages, the "TryXXX" idiom for a non-throwing version of a method. But that could have been done by returning a compound value type (a struct in C#) instead:
struct TryResult<T>
{
public T Result;
public bool Succeeded;
}
TryResult<int> Parse(string intString)
{
...
Having an out parameter basically allows for two return values from a method.
Java left this feature out to simplify it's syntax and remove the potential for misuse and programming errors.
In order to return more than one value you can have your method return an object or a collection of objects. So you don't necessarily require out parameters to return more than item from the method.
You make it sounds as though Java and C# were designed around the same time. Remember, Java is nearly 15 years old. The lack of out parameters (if you can call it a lack) is the least of its omissions.
C# has a much lower barrier to entry for random features. "Out" parameters are not that useful (and get abused), so they are not supported in Java. There were lots of features submitted under Project Coin for JDK7, but IIRC out parameters were not among them.
I feel like I must be missing something here, so I'm fully prepared to be downvoted into oblivion...
Doesn't Java support "out" parameters equally as much as C++? My C#-fu is not very strong, but I thought the out keyword was just a way of telling the compiler to allow objects to be changed inside the method. If I'm right, then both Java and C++ support this too, just without the explict (and IMHO nice distinction) of using a keyword. In C++, you can pass a pointer or a reference to the function and the function can modify the object in whatever way it wishes. Perhaps it would be more like C#'s implementation to pass in a pointer to a pointer and have the function allocate an object there, but whatever. In Java, you can achieve the former exactly the same as using references in C++, since every object is a reference in Java.
So, where's the error of my ways? There must be a reason no one has mentioned this yet. I look forward to learning what it is.

Surprises Moving from C++ to C#

I am a C++ programmer moving into C#. I worked with the language for a month now and understand many concepts.
What are some surprises I may get while moving from C++ to C#? I was warned about destructors not being executed as I intended. Recently I tried to do something with generics that would use T as the base class. That didn't work. I also had another problem but I'll chalk that up to inexperience in C#. I was also surprised that my app was eating RAM, then I figured out I needed to use .dispose in one function. (I thought it would clean up like a smart pointer)
What else may surprise me?
Please no language bashing. I doubt anyone will but just in case...
Fortunately, Microsoft have some of that info here: C# for C++ Developers.
The struct vs class differences is another biggie for C++ origins.
I think you've covered the main one. You should read up on garbage collection, understand why there are no destructors as such, figure out the IDisposable pattern (which kind of replaces destructors). I'd say that was the big one.
The only other thing I would say is to warn you the C# and the .Net Base Class Library are pretty big, to get the most out of it there is a lot to learn... Once you have covered the basics of garbage collection and the type system you'll want to look at LINQ, and you should take the time to explore the relevnt libraries / frameworks for your area (e.g. WPF, WCF, ASP.Net etc). But it's all good. I moved from C++ to C# and would never go back, I find it way more productive (I'm not bashing C++, I do still dable:-) )
Well, the languages are completely different as I'm sure you've realized if you've worked with C# for any time. You don't have a powerful macro or templating (I realize there are generics in C#) in C# as you do in C++. As far as memory, remember you aren't in a tightly controlled environment anymore. Expect to see a lot of memory usage in Task Manager and similar tools, this is normal. There are better, more fine-grained performance counters to see true memory usage. Also, you probably don't need to call dispose as much as you might think (by the way, check out "using" blocks if you haven't already).
Another clear one is the default constructor, in C# this does not create a new Foo object:
Foo myFoo;
You can't have anything like a "void pointer" unless you just think of that as being like having a reference of type object. As well, you need to think of Properties as syntactic sugar for methods and not public members as they look in C++ syntax.
Make sure you understand "out" and "ref" parameters.
Obviously this not a large list, just a few "pointers" (no pun intended).
This is a rather big topic. A few thoughts:
C# is garbage collected. Doesn't mean you can stop paying attention about resource allocation, but in general you don't have to worry nearly as much about the most common resource: memory.
In C# Everything is an object. There are no "primitive" datatypes, even an int is an object.
C# has generics, not templates. Templates are far richer and more complex than C#'s similarly syntaxed generics, but generics still provide nearly all of the practical utility of templates, without many of the headaches.
C# has interfaces and single inheritance. Where you might look to multiple inheritance in C++, instead look to using interfaces or a different design pattern (e.g. strategy).
C# has delegates instead of function pointers. A delegate is basically just a typed function pointer. The use of delegates and delegate-relatives (lambda expressions, events, predicates, etc.) is very powerful and worth putting significant effort into studying.
C# supports yield return. This is very fundamental to the C# way of doing things. The most common form of iterating over some set is to use foreach. It's worth understanding how IEnumerable and iterators work.
I've made pretty much the same change some months ago (before that I've made a change to Java - but I didn't really spend much time programming Java).
Here are some of the biggest traps I've come across:
Attribute vs. Variable vs. Setter
One of the biggest traps I was stepping into was knowing if you have to change an attribute or set a variable or use a setter to set some aspect of a class.
IList vs. List vs. other collections
Know the difference between IList, List and all the other collections (IMO you can't really do much with an IList).
Generics do have their own pitfalls
And if you plan to use a lot of generics, maybe reading this helps you avoiding some of my errors:
Check if a class is derived from a generic class
But in general I'd say that the change went pretty painlessly.
Differences in the object model. For example value and reference types are separate by definition, not by how they are instantiated. This has some surprises, e.g.
myWinForm.Size.Width = 100;
will not change the width, you need to create a new Size instance and assign it.
Some things that I have not seen mentioned that are not available in C++ and may be a bit surprising are attributes and reflection
Attributes as such do not give you full fledged AOP. However, they do allow you to solve a bunch of problems in a way that is very different to how you would solve them in C++.

Categories

Resources