General Interface Syntax : using variable names - language-agnostic

In languages like Java and c#, when you declare an interface the parameters on the functions have variable names. Could you make it more minimal and have the syntax work like this:
void Print( String );
Instead of the current
void Print( String str );
Other then readability, where the variables help define what the parameters are supposed to be, are there reasons require variable names on interfaces?
Readability example:
void doSomething( long, long );
versus
void doSomething( long id, long timeLimitMilli );

Based on my test I would say the answer is "not a bit":
./a/Foo.java
public interface Foo {
void run(int x);
}
./b/Foo.java
public interface Foo {
void run(int y);
}
Then
$ sha1sum ./a/Foo.class
7ae75c91f553e09e5a06d5630134e63d650d734e ./a/Foo.class
$ sha1sum ./b/Foo.class
7ae75c91f553e09e5a06d5630134e63d650d734e ./b/Foo.class
ie Java cares so little about the parameter names they are discarded entirely on compiling. They are, for all intents and purposes, comments.

Related

How to create an async variadic function in Vala

Is it possible to create an async variadic function in Vala? If yes, how?
I couldn't find anything related in the Vala tutorial provided on the gnome website or in any example of code. My conclusion is that it's not possible, because vala requires async functions to have fixed arguments. But then, i don't know how to achieve something similar to a variadic function.
Example of code (non async, working without issues):
void long_function(string first_val, ...) {
var list = va_list();
string? second_val = list.arg();
print("%s,%s\n", first_val, second_val);
}
void main() {
long_function("a", "b");
}
Example of async code (not working):
async void long_function(string first_val, ...) {
var list = va_list();
string? second_val = list.arg();
print("%s,%s\n", first_val, second_val);
}
void main() {
long_function.begin("a", "b");
}
The error returned by the vala compiler (compiled with: vala --pkg gio-2.0 main.vala) is
main.vala:7.28-7.30: error: Argument 2: Cannot convert from `unowned string' to `void GLib.AsyncReadyCallback? (GLib.Object?, GLib.AsyncResult)'
My real use case scenario is (pseudo code):
async void fetch_from_api_with_params(...) {
// ExternalLibrary is a function which accepts a string with a url and any number of POST parameters
ExternalLibrary.fetch_from_url.begin("http://example.com", va_list());
// ...
}
Sadly, this is not possible with Vala. Vala uses C's variadic arguments system and GLib's co-routine system. Unfortunately, the two aren't compatible. Depending on your needs, you might be able to pass an array of Variant.

Vala different type of constructors

Why, and what does the three vala constructors ?
class construct
construct
method with class name
and more specific, why the 3rd construct is never called when using it from a Gtk.Builder file?
Short answer: because that's how GObject works. The long answer is just a smidge longer:
C doesn't have objects or constructors, it has structs and functions. Structs are very simple; they contain fields, and that's it. No methods, constructors, destructors, etc. They look like this:
typedef struct Foo_ {
int bar;
char* baz;
} Foo;
To "instantiate" a struct, you allocate the necessary memory (either on the stack or the heap, I'll focus on the heap for the rest of the question) and set the fields.
This quickly gets to be a pain, even for our simple struct, so you'll usually see functions to help out with allocating and freeing structs. Something like this:
Foo* foo_new (int bar, char* baz) {
Foo* foo = malloc (sizeof (Foo));
/* malloc() can fail. Some libraries would return null, some would
just assume it never does. GLib-based software generally just exits
with an error, which is what we'll do here. */
if (NULL == foo) {
fprintf (stderr, "%s:%d: Unable to allocate room for struct Foo\n",
__FILE__, __LINE__);
exit (EXIT_FAILURE);
}
foo->bar = bar;
foo->baz = (NULL != baz) ? strdup (baz) : NULL;
return foo;
}
void foo_free (Foo* foo) {
if (NULL == foo)
return;
if (NULL != foo->baz)
free (foo->baz);
free (foo);
}
In Vala, the *_new functions are mapped to named constructors. The Vala binding for this might look something like:
[Compact]
public class Foo {
public Foo ();
public int bar;
public string? baz;
}
That's all pretty simple, but what happens when you want to "extend" Foo and add a new field? C doesn't have any language-level support for "extending" a struct. C programmers get around this by embedding the base struct in the child struct:
typedef struct Qux_ {
struct Foo parent;
int quux;
} Qux;
This is a pretty decent solution at the C level; the first part of Qux struct is exactly the same as a Foo struct, so when we want to use a Qux as a Foo all we have to do is cast:
void qux_set_bar_and_qux (Qux* qux, int bar, int quux) {
((Foo*) qux)->bar = bar;
qux->quux = quux;
}
Unfortunately it breaks down pretty badly when creating a new instance. Remember that our foo_new function allocates a slice of sizeof(Foo) bytes on the heap (using malloc)—there is no room for the quux field! That means we can't call our foo_new function.
If you're calling a library written in Vala, there is a way around this: in addition to the foo_new function, Vala will actually generate a foo_construct function. So, given something like
[Compact]
public class Foo {
public Foo (int bar, string? baz) {
this.bar = bar;
this.baz = baz;
}
}
What Vala will actually generate is something a bit like this:
void foo_construct (Foo* foo, int bar, char* baz) {
foo->bar = bar;
foo->baz = g_strdup (baz);
}
Foo* foo_new (int bar, char* baz) {
Foo* foo = g_malloc (sizeof (Foo));
foo_construct (foo, bar, baz);
return foo;
}
Now, if our Qux class in Vala subclasses Foo, it can call our Foo named constructor:
[Compact]
public class Qux : Foo {
public Qux (int quux) {
base (0, "Hello, world");
this.quux = quux;
}
public int quux;
}
Because the generated code doesn't actually call foo_new, it calls foo_construct:
Qux* qux_new (int quux) {
Qux* qux = g_malloc (sizeof (Qux));
foo_construct ((Foo*) qux, 0, "Hello, world");
qux->quux = quux;
}
Sadly, code not written in Vala rarely follows this convention (grep for the 'has_construct_function' CCode attribute in the VAPIs distributed with valac).
At this point you might be thinking, "It's a pain, but why not just re-create the contents of the foo_new function in qux_new". Well, because you may not have access to the contents of the Foo struct. The person who wrote Foo may not want you messing with their private fields, so they can make Foo an incomplete type in the public headers, and keep the full definition to themselves.
Now, let's start talking about GObject properties. I'm going to be a bit light on the details, but basically it allows you to register types, and includes a bit of information about them which is available at runtime.
Classes registered with GObject can have properties. These are conceptually somewhat similar to fields in C structs, but the type provides callbacks for loading and storing them instead of just letting your code store to an address directly. This also means it can do thinks like emit a signal when you set a value, and some other convenient stuff.
Class initialization in GObject is fairly complicated. We'll talk about that a bit more in a minute, but let's first look at it from the point of view of a library which wants to instantiate a GObject class. That would look something like this:
Qux* qux = g_object_new (QUX_TYPE,
"bar", 1729,
"baz", "Hello, world",
"quux", 1701,
NULL);
It's probably pretty obvious what this does: it creates a Qux instance, and sets the "bar" property to 1729, "baz" to "Hello, world", and "quux" to 1701. Now, back to how the class is instantiated. Again, this is (more than) a little simplified, but…
First, enough memory to hold the Qux instance (including the Foo parent class, and now also the GObject class which is the ancestor of all GObjects) is allocated.
Next, the callbacks to set the "bar", "baz", and "qux" properties are invoked.
Next, the *_constructor function is called. In Vala, this is mapped to the construct block. It looks something like this:
static GObject * foo_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam construct_properties[n_construct_properties]) {
GObjectClass * parent_class = G_OBJECT_CLASS (foo_parent_class);
GObject * obj = parent_class->constructor (type, n_construct_properties, construct_properties);
Foo * self = G_TYPE_CHECK_INSTANCE_CAST (obj, TYPE_FOO, Foo);
/* The code from your construct block goes here */
return obj;
}
Note that you don't get to control the arguments to this function. As you can see, each constructor calls the constructor of its parent class. I've added a comment where the code from your construct block goes; we'll get back to why that is separate from the named constructor soon.
Now, let's look at the code for a named constructor. Remember, the vast majority of libraries don't have a *_construct function, so we'll imagine one which doesn't (for our Qux class):
Qux* qux_new (int bar, int quux) {
Qux* qux = g_object_new (QUX_TYPE,
"bar", bar,
"quux", quux,
NULL);
/* Code from your named constructor goes here. */
}
At last, we get to why your named constructor isn't called when using GtkBuilder: it doesn't call qux_new, it calls g_object_new. Calling qux_new is an enormous pain without knowledge of your library, and obviously it's not feasible for GtkBuilder to know about your library.
Finally, let's talk about class construct blocks. They're basically an entirely different thing. Luckily, it doesn't take nearly as long to explain them: they are called when the type is registered with GObject, not when an instance of the type is instantiated. Basically, it gets called the first time your class is instantiated and never again. A quick example:
public class Foo : GLib.Object {
class construct {
GLib.message ("Hello, world!");
}
construct {
GLib.message ("%d", this.bar);
}
public int bar { get; set; default = 1729; }
}
private static int main (string[] args) {
var foo = new Foo ();
foo = new Foo ();
return 0;
}
Will output
Hello, world!
1729
1729

the cause of overloading a constructors in java

So I just can't seem to understand the problem of overloading. I know it is caused by constructors sharing the same parameters; but do that have to be exactly the same or will the overload happen if they share one common parameter, or even they if one had three parameters but shares two with another?
Not sure what you are asking here.
But Overloading is not only for Constructors. That can be for other methods too.
Here are the rules (My). You can have same method name, but the parameters should be different.
Example: Constructor Overloading
public Car()
{
}
private Car(int speed, int maxSpeed)
{
//...
}
public Car(String make, String model)
{
//...
}
This is overloading.
But below is illegal with the above constructors.
public Car(String color, String make)
{
//...
}
Because the JVM wouldn't be able to distinguish the (String make, String model) & (String color, String make) Constructors. Therefore the rule is, parameters should be different (Types and/or the number of parameters).
Again Remember:
public void printNames(String name1, String name2)
public void printNames(String x, String y)
This is not overloading and even the compiler wouldn't let you do it.
A java class can contain two or more methods with the same name, provided that those methods accept different parameters. That is called overloading. When you create overloaded methods every method must have a unique signature.

Proper usage of "this." keyword in C#?

I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.
Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).
Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?
Thanks!
Personally I only use it when I have to which is:
Constructor chaining:
public Foo(int x) : this(x, null)
{
}
public Foo(int x, string name)
{
...
}
Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)
public void SetName(string name)
{
// Just "name = name" would be no-op; within this method,
// "name" refers to the parameter, not the field
this.name = name;
}
Referring to this object without any members involved:
Console.WriteLine(this);
Declaring an extension method:
public static TimeSpan Days(this int days)
{
return TimeSpan.FromDays(days);
}
Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.
StyleCop's default coding style enforces the following rule:
A1101: The call to {method or property
name} must begin with the 'this.'
prefix to indicate that the item is a
member of the class.
Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.
I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):
public void compareTo(MyClass other) {
if (this.someField > other.someField) return 1;
if (this.someField < other.someField) return -1;
return 0;
}
As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:
class Rect {
private int width, height;
public Rect(int w, int h) {
width = w;
height = h;
}
}
Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.
It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.
Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:
private String _someData;
public String SomeData
{
get{return _someData;}
set{_someData = value;}
}
It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.
So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.
The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)
If you have a method inside a class which uses same class's fields, you can use this.
public class FullName
{
public string fn { set; get; }
public string sn { set; get; }
//overriding Equals method
public override bool Equals(object obj)
{
if (!(obj is FullName))
return false;
if (obj == null)
return false;
return this.fn == ((FullName)obj).fn &&
this.sn == ((FullName)obj).sn;
}
//overriding GetHashCode
public override int GetHashCode()
{
return this.fn.GetHashCode() ^ this.sn.GetHashCode();
}
}

What Does "Overloaded"/"Overload"/"Overloading" Mean?

What does "Overloaded"/"Overload" mean in regards to programming?
It means that you are providing a function (method or operator) with the same name, but with a different signature.
For example:
void doSomething();
int doSomething(string x);
int doSomething(int a, int b, int c);
Basic Concept
Overloading, or "method overloading" is the name of the concept of having more than one methods with the same name but with different parameters.
For e.g. System.DateTime class in c# have more than one ToString method. The standard ToString uses the default culture of the system to convert the datetime to string:
new DateTime(2008, 11, 14).ToString(); // returns "14/11/2008" in America
while another overload of the same method allows the user to customize the format:
new DateTime(2008, 11, 14).ToString("dd MMM yyyy"); // returns "11 Nov 2008"
Sometimes parameter name may be the same but the parameter types may differ:
Convert.ToInt32(123m);
converts a decimal to int while
Convert.ToInt32("123");
converts a string to int.
Overload Resolution
For finding the best overload to call, compiler performs an operation named "overload resolution". For the first example, compiler can find the best method simply by matching the argument count. For the second example, compiler automatically calls the decimal version of replace method if you pass a decimal parameter and calls string version if you pass a string parameter. From the list of possible outputs, if compiler cannot find a suitable one to call, you will get a compiler error like "The best overload does not match the parameters...".
You can find lots of information on how different compilers perform overload resolution.
A function is overloaded when it has more than one signature. This means that you can call it with different argument types. For instance, you may have a function for printing a variable on screen, and you can define it for different argument types:
void print(int i);
void print(char i);
void print(UserDefinedType t);
In this case, the function print() would have three overloads.
It means having different versions of the same function which take different types of parameters. Such a function is "overloaded". For example, take the following function:
void Print(std::string str) {
std::cout << str << endl;
}
You can use this function to print a string to the screen. However, this function cannot be used when you want to print an integer, you can then make a second version of the function, like this:
void Print(int i) {
std::cout << i << endl;
}
Now the function is overloaded, and which version of the function will be called depends on the parameters you give it.
Others have answered what an overload is. When you are starting out it gets confused with override/overriding.
As opposed to overloading, overriding is defining a method with the same signature in the subclass (or child class), which overrides the parent classes implementation. Some language require explicit directive, such as virtual member function in C++ or override in Delphi and C#.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
}
public class Line : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}
An overloaded method is one with several options for the number and type of parameters. For instance:
foo(foo)
foo(foo, bar)
both would do relatively the same thing but one has a second parameter for more options
Also you can have the same method take different types
int Convert(int i)
int Convert(double i)
int Convert(float i)
Just like in common usage, it refers to something (in this case, a method name), doing more than one job.
Overloading is the poor man's version of multimethods from CLOS and other languages. It's the confusing one.
Overriding is the usual OO one. It goes with inheritance, we call it redefinition too (e.g. in https://stackoverflow.com/users/3827/eed3si9n's answer Line provides a specialized definition of Draw().