variable names in function definition, call and declaration - function

I see C books that use the same variable names in the function definition, calling function and declaration. Others use the same variable names in the calling function and in the declaration/prototype but a different one in the definition as in:
void blabla(int something); //prototype
blabla(something) // calling function inside main after something has been initialized to int
void blabla(int something_else) //definition
I have two questions:
What convention is best to use in C?;
Does the convention apply regardless whether a value is being passed "by-value" or if it's being passed by a pointer?
Thanks a lot...

The name used for a function parameter in a function declaration is basically just a comment. It doesn't have any meaning and (as you've noticed) doesn't have to match the function definition. That said, it should be a good descriptive name that tells you what the parameter is for. So why not use the same name in the declaration? If you use a different name and one of the names is better (more descriptive), then you should probably use that name in both places.

Related

Different ways to define a function in Kotlin

I'm new at Kotlin, migrating from Java. One thing I think is a little bit confusing is the fact we may declare a function using different ways. Bellow are at least 3 ways to accomplish that:
package me.bruno.santana
class MyClass {
fun square(number: Int) = number * number
fun square2(number: Int): Int{
return number * number
}
}
fun MyClass.square3(number: Int) = number * number
fun main(){
val obj = MyClass()
println(obj.square(3))
println(obj.square2(3))
println(obj.square3(3))
}
What is the difference between this 3 ways in practical terms? I know the last one is related to extension funcion concept, but I don't know what it differs from the conventional way in practical terms.
Another thing is weird for me is the assignment in the function definition(using equals sign to associate the function's body to the function's signature). Is it in any way different from the convetional way using curly braces as in Java?
Thank you.
1. This is single expression function:
When a function returns a single expression, the curly braces can be omitted and the body is specified after a = symbol
Explicitly declaring the return type is optional when this can be inferred by the compiler:
fun square(number: Int) = number * number
2. This is normal function
That can have single-line or multi-lines and required return type (but Unit is optional):
fun square2(number: Int): Int {
return number * number
}
3. This is Extension functions:
Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.
Extensions are resolved statically: Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type
Often used to write utility functions and enhance readability via dot-notation.
If an extension is declared outside its receiver type, such an extension cannot access the receiver's private members.
fun MyClass.square3(number: Int) = number * number
To add something about extension functions: there are four common reasons to use them that I can think of.
You don't control the source code of the class you're adding the function to.
You want to add functions only to specifically typed instances of a class. For example, you could write a function for your Foo<T: Animal> class that is only available on instances that are a Foo<Pet>.
You want to add something like a final function to an interface. This is used frequently in the standard library. If you define a function inside an interface, its behavior is unpredictable because interface functions cannot be final. By declaring it outside the interface as an extension, it can be hidden (by writing a different extension function with the same signature), but it cannot be overridden. Hiding it still requires the user to import the other version of the function, so it must be done explicitly.
You want to confine the scope of the added function. Maybe the function only really makes sense in a certain context, so you don't want it to clutter the IDE auto-complete everywhere. Or maybe it uses a property of a certain class, so it must be defined within that class.
When you're just composing one of your own typical classes, you won't frequently need to use an extension function.

In Lua, what is the difference between functions that use ":" and functions that do not? [duplicate]

This question already has answers here:
Difference between . and : in Lua
(3 answers)
Closed 7 years ago.
Let's say we have two function declarations:
function MyData:New
end
and
function New(MyData)
end
What is the difference between them? Does using : have any special purpose when it comes to inheritance and OOP? Can I only call functions declared with : by using :?
I'm coming from using only C# -- so if there's any comparison to be made, what would it be?
Adapted from the manual, end of ยง3.4.10:
The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement
function t:f (params) body end
is syntactic sugar for
t.f = function (self, params) body end
You should search SO as there are many questions about this but you have a set of questions so I can't say this is a duplicate.
Q. What is the difference between them?
A. The one with colon causes a method to be added to the MyData table, and the Lua interpreter to automatically insert a "self" before the first parameter when called, with this "self" pointing to the MyData instance that the "method" is being called upon. It is the same as writing MyData.New = function(self) end. The second signature has a parameter called MyData and is a global function. It is unrelated to the MyData table (or class).
Q. Does using ":" have any special purpose when it comes to inheritance and OOP?
A. No; it is merely syntactic sugar so that when you call MyData.New you can just write MyData:New() instead of the clunky looking MyData.New(MyData). Note that a "new" function is typically to create instances of a class, so you wouldn't have such a function be a method, rather just a function in the MyData table. For inheritence and OOP, you use metatables, and this does not interact with : in any special way.
Q. Can I only call functions declared with ":" by using ":"?
A. No, as mentioned, it just syntactic sugar, you can define one way and call a different way.
Q. I'm coming from using only C# -- so if there's any comparison to be made, what would it be?
A. For functions, the : is like the . in C#, whether used in a call or definition. The "." in Lua is more like "attribute", there is no equivalent in C# for functions.
MyData = {} -- a table
function MyData.func(self)
print('hello')
end
MyData:func()
MyData.func(MyData) -- same as previous
function MyData:func2() -- self is implicit
print('hello')
end
MyData:func2()
MyData.func2(MyData) -- same as previous
Note that MyData as defined above is not a class, because you cannot create "instances" of it (without doing extra work not shown there). Definitely read the Programming in Lua online book on the Lua.org website, lots of useful discussions of these notions.
Lua doesn't have functions declarations per se; It has function definition expressions. The syntax you have used is shorthand for a function definition expression and assignment.
The only difference in your examples is when the first statement is executed a new function is created and assigned to the field New in the table referenced by the variable MyData, whereas the second is an assignment to a non-field variable (local, if previously declared, otherwise global).
Keep in mind that these are only the first references to the created function values. Like any other value, you can assign references to functions to any variable and pass them as parameters.
If you add formal parameter usage to the bodies then there is another difference: The first has an implicit first parameter named self.
If you add function calling to the scenarios, the ":" syntax is used with an expression on the left. It should reference a table. The identifier to the right should be a field in that table and it should reference a function. The value of the left expression is passed as the first actual argument to the function with any additional arguments following it.
A function definition with a ":" is called a method. A function call with a ":" is called a method call. You can construct a function call to a function value that is a field in a table with the first argument being a reference to the table using any function call syntax you wish. The Lua method definition and method call syntax makes it easier, as if the function was an instance method. In this way, a Lua method is like a C# Extension Method.

Is there a specific name for a function that takes its output as input and does that parameter have a name?

I work with a BASIC programming language and have found it useful to write functions that rely on their output as a parameter. Such as
inOut = someFunction(inOut)
I'd like to call this a recursive function. but it doesn't seem right because it is not calling itself. Can someone tell me what the name of this type of function is and if the parameter/return has a special name?
Thanks!!
This is an ordinary function as any other. The thing you show is called reassingment. You can rename inOut on the left with newinOut and it will not change anything... there is absolutely nothing special about the function, it's a naming pattern, that's all.
In many languages (including VB, but not sure about classic BASIC) there's something called passing parameter by reference. It's not exactly what you posted, but rather simple
someFunction(inOut)
parameter is passed into the function, changed there and the change persists outside the function

How should I design a method that allows for optional operations?

For example, suppose I this:
class Gundam00 extends Gundam implements MobileSuit {
...
public void fight(final List<MobileSuit> mobiruSuitso, final List<Gundam> theOtherDudes, final List<Person> casualities) {
....
}
}
Suppose theOtherDudes and casualities parameters are optional. How can I make this method as clean as possible? I thought about having booleans indicating if they're null, and then checking them as needed.
I could also have different versions of the method for each combination of parameters but there would be a lot of code duplication I think.
Any suggestions?
I find that past 2-3 arguments, the ability to remember what all the arguments to a function are suffers. And comprehensibility along with it.
Passing named arguments can help. Languages with a convenient hash-like literal syntax make this really easy. Take JavaScript:
g = new Gundam00();
g.fight({opponent: enemy, casualties: 'numerous'});
You can also take advantage of variable length argument features to work this in (treat odd arguments as names, even arguments as the actual parameters).
g.fight('opponent',enemy,'casualties', 'numerous');
And some languages actually support named arguments straight-out (see: http://en.wikipedia.org/wiki/Named_parameter#Use_in_programming_languages ).
Finally, you might want to consider adding other methods for this using what some call a Fluent Interface (http://en.wikipedia.org/wiki/Fluent_interface ). Basically, you've got method call which return the object itself, so you can chain calls together:
g.opponent(enemy).casualties('numerous').fight();
This might be the easiest option if you're working in a manifestly/statically-typed class-focused language.
Update
Responding to Setsuna's comment... in that last example, if you've got the luxury, you can make methods like opponent and casualties simple setters that don't affect any internal state or computation in any other way than setting a parameter for which they're named. They simply set internal properties up, and then all of the real work happens inside action methods like fight.
If you can't do that (or if you don't like writing methods whose operations are sub-atomic), you could stake out a half-way spot between this idea with the hash-like literal idea, and create your own collection class specifically for invoking named arguments:
n = new NArgs();
g.fight(n.arg('opponent',enemy).arg('casualties','numerous').arg('motion','slow'));
A little more unwieldy, but it separates out the named arguments problem and lets you keep your methods a bit more atomic, and NArgs is probably something you could implement pretty easily just wrapping some methods around one type of Collection (HashTable?) or another that's available in your language.
Add the methods. Overloading methods is generally an antipattern and a refactoring opportunity for someone else.
http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html
I thought about having booleans indicating if they're null, and then checking them inside and reacting accordingly.
Or ... you could just check if they're null.
if(theOtherDudes == null)
...
If there is only one "main method" in your class, then you can implement the optional arguments as getter/setter functions. Example:
public void setOtherDudes(final List<Gundam> theOtherDudes) {} // for input arguments
public List<Person> getCasualities() {} // for output arguments
And then, in your documentation, mention that if the caller has any optional input arguments it has to be passed in before calling fight(), and the optional output values will be available when fight() has been called.
This is worthwhile if there are dozens of optional arguments. Otherwise, I suggest overloading the method as the simplest way.

What is the advantage of having this/self pointer mandatory explicit?

What is the advantage of having this/self/me pointer mandatory explicit?
According to OOP theory a method is supposed to operate mainly (only?) on member variables and method's arguments. Following this, it should be easier to refer to member variables than to external (from the object's side of view) variables... Explicit this makes it more verbose thus harder to refer to member variables than to external ones. This seems counter intuitive to me.
In addition to member variables and method parameters you also have local variables. One of the most important things about the object is its internal state. Explicit member variable dereferencing makes it very clear where you are referencing that state and where you are modifying that state.
For instance, if you have code like:
someMethod(some, parameters) {
... a segment of code
foo = 42;
... another segment of code
}
when quickly browsing through it, you have to have a mental model of the variables defined in the preceding segment to know if it's just a temporary variable or does it mutate the objects state. Whereas this.foo = 42 makes it obvious that the objects state is mutated. And if explicit dereferencing is exclusively used, you can be sure that the variable is temporary in the opposite case.
Shorter, well factored methods make it a bit less important, but still, long term understandability trumps a little convenience while writing the code.
You need it to pass the pointer/reference to the current object elsewhere or to protect against self-assignment in an assignment operator.
What if the arguments to a method have the same name as the member variables? Then you can use this.x = x for example. Where this.x is the member variable and x is the method argument.
That's just one (trivial) example.
I generally use this (in C++) only when I am writing the assignment operator or the copy constructor as it helps in clearly identifying the variables. Other place where I can think of using it is if your function parameter variable names are same as your member variable names or I want to kill my object using delete this.
Eg would be where member names are same as those passed to method
public void SetScreenTemplate(long screenTemplateID, string screenTemplateName, bool isDefault)
{
this.screenTemplateID = screenTemplateID;
this.screenTemplateName = screenTemplateName;
this.isDefault = isDefault;
}