From what I gather, Gosu is simply C# for the JVM (which is a good thing). Is it true? What are some difference between Gosu and C# (Except the class library and the fact it runs on JVM) ?
We didn't build Gosu to be one language or the other for the JVM. Rather we built Gosu to be a useful language for the JVM. In addition, we recognized that Gosu needed to be familiar to the multitudes of existing programmers who are most comfortable with the imperative, object-oriented model. To achieve that we borrowed heavily from several languages e.g., Java, C#, EcmaScript, Ruby, and some others. The result, we think, is a language that is uniquely positioned on the JVM.
What is entirely unique about Gosu, however, is it's open type system.
Gosu's type system consists of a configurable number of type loaders. A type loader's primary responsibility is to resolve a type name in its domain and return an implementation of Gosu's IType interface. This is what is most unique about Gosu -- its type system is open to other domains to participate with first-class representation. I frequently use the term, DST (Domain Specific Type), to get across the idea. For instance, Gosu does not discriminate between a Gosu Class a Java Class or XML Type or what have you; they're all just types to Gosu's compiler. Check out the DynamicType example in the download to get a glimpse of the power and breadth the open type system provides. Essentially, the example demonstrates that C#'s "dynamic types where required" can simply be a new type loader domain in Gosu. Or check out the Ronin framework to see how easily the web and database domains can map seamlessly into Gosu.
It is important to understand that not all type loader domains in Gosu are required to produce bytecode. Those that do implement an interface for getting at the corresponding Java class. Those that don't provide call handlers and property accessors for reflective MethodInfo and PropertyInfo evaluation, respectively. Note all types provide TypeInfo, see IType.getTypeInfo(). For instance, the parser works against the TypeInfo, MethodInfo, etc. abstractions as the means for a level playing field between disparate types. At runtime, however, unless a type provides a Java bytecode class the MethodInfos and PropertyInfos also are responsible for handling calls.
No. If you look at the "notable differences" page (differences between Java and Gosu) you'll see a lot of things which are like C#, but also things which aren't in C# such as case-insensitivity and making semi-colons optional. There are also things which certainly aren't mentioned but which are part of C#:
Custom value types
Operator overloading
LINQ
Dynamic typing where required
I think it would be a mistake to regard Gosu as "C# for the JVM" rather than "a JVM language which mixes bits of Java, bits of C# and some bits from other languages too".
Related
I find the concept of metaclass fascinating, it treats classes as first class objects. You can assign a class to a variable, pass it to a method, and even create new classes at runtime. It seems that, every programming language that supports metaclasses are either dynamic typed languages(Smalltalk, Python, Ruby) or gradually typed languages(Objective C and Groovy both support static and dynamic typing). I have not seen a statically typed language that supports metaclasses.
Are static typing and metaclasses incompatible with each other? It does seem to me that, metaclass' functionalities require a certain degree of dynamism. I still wonder if it is technically possible for a static typed language like Java, C# and Kotlin to support metaclass and have classes as first class objects, or is it theoretically impossible?
Given that Python itself is implemented in C, and its objects can be "seen" and used in C through its API, the answer is "yes".
What may be harder in some languages is that objects belonging to a class hyerarchy were they have proper metaclasses, introspection, and runtime class creation may be a little tougher - requiring the code that implements such metaclasses to replicate part of the language runtime itself, or to call, at runtime, different code generation functions - at very least, one class could generate the source code with the declaration for the dynamically created classes, and iterate with the runtime to compile and load that code into the current process.
With C++, for example, where one can have full control of in-memory layout of data, maybe it is possible to emulate compiled classes with a lighter approach, that just fill in data-structures and redo the name-mangling part to attach class members.
If that would be something convenient, however, it is another question altogether. Maybe it is just better to leave metaclasses either for languages that support it out of the box, or, for languages were you are implementing a class system from scratch (like the Python runtime does using C).
Languages such as Java and PHP support reflection, which allows objects to provide metadata about themselves. Are there any legitimate use cases where you would need to be able to do something like ask an object what methods it has outside of the realm of reverse engineering? Are any of those use cases actually implemented today?
Reflection is used extensively in Java by frameworks which are leveraged at runtime to operate with other code dynamically. Without reflection, all links between code must be done at compile time (statically).
So, for example, any useful plug-in framework (OSGi, JSPF, JPF), leverages Reflection. Any injection framework (Spring, Guice, etc) leverages Reflection.
Any time you want to write a piece of code that will interact with another piece of code without having that piece of code available when compiling, Reflection is the way forward in Java.
However, this is best left to frameworks and should be encapsulated.
There certainly are good use cases. For example, obtaining developer-provided metadata. Java APIs are increasingly using annotations to provide info about methods/fields/classes and their use. Like input validation, binding to data representations... You could use these at compile-time to generate metadata descriptors and use those, but to do it at runtime would require reflection. Even if you used the metadata descriptors, they'd end up containing things like class, method and field names that'd need to be accessed via reflection.
Another use case: dynamic languages. Take Ruby... It allows you to check up-front whether an object would respond to a method name before trying to call that method. Something like that requires reflection.
Or how about when a class or method name must be provided from outside compiled code, like when selecting an implementation of some API. That's just gonna be a bit of text. Looking up what it resolves to comes down to reflection.
Frameworks like Spring or Hibernate make extensive use of reflection to inspect a class and see the annotations.
Frameworks for debugging, serialization, logging, testing...
I often find developers use the terms functional language and dynamic language together, and wonder why are they always being put together.
What are the differences between them? Can a language be both dynamic and functional? Do they complement each other? Why do we need them anyway?
I'm a C# programmer and don't yet understand this whole dynamic/functional thing (C# is going to have some dynamic features in ver 4. Will it also be functional? what's going on here?).
Thanks,
Abraham
To put it in a simple (but not accurate) answer
Dynamic languages are ones in which the Type (Name of the Class) is not as important as compared to its nemesis statically typed languages. A variable may have objects of different types assigned to it at any given point of time. Method invocations are resolved at run-time. This means you lose the benefits of static typing (compiler warnings) but simple methods turn generic - sort(list) works for a list of strings as well as list of ints. e.g. Ruby et. all
Functional languages value immutability. The programs are written in terms of bigger and bigger functions (usually bottom up). The concept of object state and mutability is frowned upon. A function in this context is self-sufficient (The term is Pure as per Wikipedia): everything it needs to produce output, lies in the input that it receives. It also produces no side-effects (unless it explicitly mentions it) and returns consistent output for a given input. This can lead to elegant code (see: fluent interfaces), where input data is pipelined through diff functions to produce the eventual output e.g. LISP et.all
However the boundaries are being muddied with languages picking up the best of all worlds... You could have a language which is both, one or neither.
e.g. predominantly static C# picking up lambda expressions in 3.0 and bringing in dynamic capabilities with 4.0
Dynamic typing, a type system, is orthogonal to 'functional', a programming paradigm.
Dynamic 'languages' are actually dynamically typed. This means that you don't have compile-time checking of your variable types.
Functional languages offer loads of support for e.g. lambda calculus - anonymous functions.
An example of a language that does dynamic typing, and supports anonymous functions: javascript. Ruby has some functional style support, too. And there are others.
Dynamic typing and functional programming are independent concepts. You can have either, neither or both in a language.
Static typing means that types of objects are known at compilation time. In dynamic typing they are known at runtime.
Functional programming means programming style where computation is done by evaluating functions while avoiding state changes. (example: you use recursion instead of for-loops, because a loop would need changing of a counter variable, etc.) This helps to avoid bugs and makes concurrent programming easier. Pure languages require you to program in functional style, others just enable it.
Example languages:
|----------------+---------+---------|
| | Dynamic | Static |
|----------------+---------+---------|
| Functional | LISP | Haskell |
| Not functional | PHP | Java |
|----------------+---------+---------|
Dynamic languages on the other hand are a broader concept. There is no exact definition, but usually the more features of the compiler are moved to the runtime, more dynamic the language is. This means that in dynamic languages you can usually evaluate expressions, change object structure etc. at runtime.
If you're interested in paradigms, the paper Programming Paradigms for Dummies: What Every Programmer Should Know covers them.
In functional programming, state is implicit - the program executes by calling functions which call other functions. In imperative programming and object oriented programming, state is explicit - you change the value of a variable or object's field.
In a way, functional and imperative systems can be seen as duals - what's fixed in one is a dynamic value in the other.
Closures - which trap some explicit, mutable state in an object which can be called as a function - sit somewhere between, being neither pure functional programming but not quite fully fledged objects; they are more like anonymous objects than functions.
'Dynamic languages' is vague term, usually meaning one of the following:
Dynamically Typed Languages - languages which delay determination of type to runtime, but the set of types is fixed. Examples are Smalltalk, Lisps, current Fortress implementations. Some otherwise statically typed languages also allow some dynamic type checks - Java, C#, C++ and Ada. ( it was a failed dynamic type cast from float to int in Ada that crashed Ariane 5 )
Languages with dynamic types - languages where new types can be created at runtime. The most popular is JavaScript. Because you have to run the program to determine the types, it's harder to make IDEs for these with type aware autocompletion.
Languages which are dynamically compiled - languages where new scripts can be compiled at runtime. This is true of bash, JSP, PHP and ASP at the page scale, and true for at a finer scale for lisps and JavaScript which support an 'eval' function which compiles and runs an expression.
Functional languages which are strongly typed often perform a large amount of type inference, so it's common for their programs to have less explicit typing than poorly implemented static typed languages. This can confuse people who have only seen the lack of explicit typing in dynamic typed languages into believing that type inference is the same as dynamic typing.
xtofl has already offered a good overall picture. I can speak to the C# point.
C# has been becoming easier to work with in a functional way for a while now:
C# 2 introduced anonymous methods, which made it easier to create delegates which used state which was otherwise local to a method
C# 3 introduced lambda expressions which are mostly like anonymous methods but even more compact
LINQ support in both C# 3 and .NET 3.5 made it easier to query data in a functional way, chaining together predicates, projections etc
None of the C# 4 features directly contributes to functional programming IMO, although named arguments and optional parameters may make it easier to create/use immutable types, which is one of the biggest features missing from the functional picture IMO.
(There are other things functional languages often have, such as pattern matching and more impressive type inference, but you can write a lot of functional-style code reasonably easily in C#.)
C# 4 will gain some dynamic abilities through the dynamic type (which itself is effectively a static type you can do anything with). This will be somewhat "opt in" - if you never use the dynamic type, C# will still be fully static language. There's no language support for responding dynamically, but the DLR has support for this - if you implement IDynamicMetaObjectProvider or derive from DynamicObject, for example, you can add dynamic behaviour.
I would say that C# isn't becoming a functional language or a dynamic language, but one in which you can code in a functional style and interoperate with dynamic platforms.
For example: a compatibility layer between scripting objects (like strings, arrays) or scripting engines( eval() ,readFile() etc.).
Without more context, I'd have to say interfaces as well. Consider that you can represent a function or delegate as an interface with a single method and that abstract classes are just interfaces with some methods potentially already implemented.
That said, it really depends on what you're trying to accomplish. Interfaces lend themselves to cases where you have lots of objects with a common interface but potentially varying implementations. If you are, for example, designing a very simple callback system for plugins (i.e.: let the plugin hook certain events in the host application) then delegates are probably simpler and sufficient for your needs.
Also keep in mind that if you do go with interfaces, you'll probably need some way for the host to instantiate instances. The easiest way to do this is by registering a delegate with the host under some unique name.
Abstract classes are only useful if you want to use interfaces and provide a default implementation of some things. A better solution in that case is to have an actual interface instead, and provide the default implementation as a mixin.
Interfaces have my vote. That way, as long as you define the interface any developer will be able to write something compatible fairly easily without you having to distribute too much code to them.
Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.
If I think a bit longer I can probably come up with more examples.
I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.
As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data.
If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...
Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.
Command line parsing. Building up a config object based on the command line parameters that are passed in.
When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).
I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.
(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)
Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).
I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.
There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.
If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.
You could even implement your own imperfect reflection that way.
For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.