QUESTION: DIFFERENCE BETWEEN `function` AND `method` - scrypto

All I know about the difference between them is in the image below.
scrypto101 explanantion of function and method
I am unable to pinpoint the difference between two of them with complete clarity.
Especially, I am unable to see scrypto code and point out that which one is a function and which one is a method.
I read that a method causes change in state where as a function does not.
What is a state ?
What does it change in state exactly mean ?
e.g. If I have to just make some changes to a nfs's metadata etc, should that be categorised as a function or a method ? (I think method)
A guideline about distinguishing a code tasks as a function or a method will help me a lot.
I am a beginner in DeFi and blockchain technology, any explanation of above with an real life example for identifying change vs no change in state or code snippet will help me a lot.

You can think of functions and methods just like in Object Oriented Programming where you have Classes and Objects. Classes offer functions and the instantiated objects offer methods. Since functions are called on the class itself, it doesn't have any state to view/update. Methods are called on individual objects instantiated from a class and it has access to the values stored on the state of the object.
Concretely, in Scrypto, the difference is in the first argument of the function/method. If you put &self as the first argument, it will be a method rather than a function since you have access to the variables of the component through this &self argument.

Related

DiffUtil.ItemCallback - define as a companion object or as a class?

I'm currently learning Kotlin through the Kotlin Android Developer program from Udacity. There's two sample apps using DiffUtil.ItemCallback, but declare it in different ways. Both sample apps use a ListAdapter, however one declares the DiffUtil like this: companion object DiffCallback : DiffUtil.ItemCallback<MarsProperty>()
while the other like this: class SleepNightDiffCallback: DiffUtil.ItemCallback<SleepNight>()
Both DiffUtils are passed as parameters to the ListAdapter, with the only difference being that in the case of the class implementation, it has to be initialised:
class PhotoGridAdapter : ListAdapter<MarsProperty, PhotoGridAdapter.ViewHolder>(DiffCallback)
class SleepNightAdapter : ListAdapter<SleepNight, SleepNightAdapter.ViewHolder>(SleepNightDiffCallback())
The only difference between those sample apps is that one downloads and shows images from the internet (the one with the PhotoGridAdapter), while the other shows data from a database, so
my question is: Is one implementation preferred compared to the other? Are there any performance differences between them?
This is probably a matter of opinion. Mine is that the callback should be an object, or anonymous object, but not a companion object.
All it's doing is comparing properties of two objects. It doesn't have to hold any state. So it makes sense for it to be a singleton object rather than a class that you have to instantiate. Whether you define it as a named singleton object or define in place as an anonymous object assigned to a property doesn't make much different in communicating intent.
But it doesn't make sense to me to make it a companion. It's already nested and has a name. All companion does is suggest that you should need to call its functions directly and that the name PhotoGridAdapter should also be thought of as a callback. For instance, it enables you to pass the name PhotoGridAdapter to some other adapter as its DiffUtil callback, which is nonsensical. The only reason it might possibly make sense is if you also want to use it as a utility for comparing items, so you could call functions like PhotoGridAdapter.areContentsTheSame directly. However, I don't think this is likely. Usually, the contents of the callback's functions are either very trivial like passing through equals() or they are very specific to the nature of updating the displayed list.

Is a Constructor a Routine?

Currently we are writing our bachelor thesis about the implementation of a Compiler for an academic object-oriented mini programming language.
We want to be precise in our documentation, and we're currently discussing if a constructor is a routine.
What we think points out that a constructor is a routine is that it has a block of Commands, Parameters and local variables. Despite the missing name, all other attributes of other routines are given.
What we think points out that a constructor is not a routine is that it can only be called once per instance.
We are not sure if this question has a clear answer, or if the definition is different from theory to theory.
We would be happy if someone could give a pointer to some literature about this semantic question.
Best
Edit: Some Information about how we name specific things in our Language:
We have functions and procedures. Functions do have a return value, procedures don't.
A constructor is like an unnamed procedure (without explicit return value)
a constructor is called implicit, java like: x := new X(1, new Y())
Parameters are defined during the definition of a constructor. The own instance (this) is not considered a parameter but provided implicitly
Thanks for your answers so far, they're helping with the though process.
This depends on language - and for this academic language - I would not say that a constructor is a routine. I say that because in not saying that it is a routine, a separation is kept: unless the language explicitly unifies routines/functions/constructors, don't say it does :)
Now, consider these counter-examples (and there are many more, I am sure):
Languages like Eiffel allow giving constructors different names (which I think is awesome and wish was used more).
Languages like Ruby don't have a "new" operator and invoking a constructor appears as invoking any (class) method. Ruby doesn't even have a way of signaling that a method acts as a constructor (or factory method, as it were).
Constructors in languages like JavaScript are just functions which can be run in a special context when used with new.
Also, at some level it may be viewed that there needs to be no difference in calling a constructor multiple times (you get back a new object - so what?) than calling a function multiple times (where one might get back the same value). Consider that the new object may be immutable and may have value equality with other objects.
That is, considering the following code, is there a constructor used?
5 4 vec2 "1" int 2 vec2 add puts
I made it up, but I hope it makes a point. There may or may not be a constructor or an external difference between a constructor and an ordinary function depending upon how the specific language views the role (or even need) of constructors.
Now, write the language specification as deemed fit and try to avoid leaking implementation details.
Constructor is a constructor.
It may be like a function(that returns value: the new object), procedure(routine, function with no return value, called on uninitialized object), it may be callable once or many times on an object (although it is arguable whever the object is of the same identity afterwards..), it may have a name or not or the name may be enforced to match the class, etc. The constructor may even "not exist" or be implicitly created by the compiler from various scattered initializers and code blocks, which otherwise would be expressions/routines/whatchamacallit.
It all depends on your language that you compile and on what do you mean by 'function', 'routine', or even 'parameters' (i.e. is 'this' a parameter?).
If you want to ask about such thing, first describe/define your language and all your terms that you want to use (what is a class? method? function? routine? parameter? constructor? ...) and then, well, most probably you will automatically deduce the answer matching your ontology.
A constructor is a function with special semantics (such that it is called in specific context - as part of object construction), but it is a function anyway - it can have parameters, it has usual flow of control, it can have local variables, etc. It is not better or worse than any other function. I'd say it is a routine.
From outside, a constructor can be seen as a class method, with an instance of that class as return value. Insofar, the claim that "it can only be used once per instance" does not hold water, since there is no instance yet when the constructor is used.
From inside, some special keywordish name like "this" is bound to the uninitialized instance.
Usually, there is some syntactic sugar, like a new keyword. Also, the compiler may help to make sure the instance is properly initialized.
It is special insofar as the functionality of creating a new object is nowhere else provided. But as far as its usage is concerned, a constructor is not (or at least should not be) different from any other class method that happens to return an instance of the class.
BTW, is "routine" an established term in OOP?
I think that a Routine is what is that can be called explicitly as and when required by the caller on a constructed object/class, while a constructor can be called a special type of routine that is called at runtime when the instance of the class is requested.
A constructor helps only in constructing and initializing the class
object and its variables.
It may or may not accept parameters, it can be overloaded with
different set of parameters
If the constructor has no parameters and also no code inside its code
block, you may want to omit it
Some languages automatically create a default parameter-less
constructor (like C#) if you do not provide your own constructor
A constructor can have an access modifier to restrict the creation
scope of the class
A constructor cannot have a return type because its constructing the
same class in which it is declared, and obviously there is no point
returning the same type (may be that's the reason some languages use same name for the constructor as the class name)
All the implementation rules for a constructor differ from language to language
Furthermore, the most important requirement of a well written constructor is that after it is executed it should leave the class object in a valid state
A constructor (as in the name) is only executed by the compiler when you create a new instance of that class.
The general idea is this: You put some set of operations which should be executed during the startup and that is what is done on the constructor. So this implies, you cannot call a constructor just like the other methods of your class.

Is it poor design to create objects that only execute code during the constructor?

In my design I am using objects that evaluate a data record. The constructor is called with the data record and type of evaluation as parameters and then the constructor calls all of the object's code necessary to evaluate the record. This includes using the type of evaluation to find additional parameter-like data in a text file.
There are in the neighborhood of 250 unique evaluation types that use the same or similar code and unique parameters coming from the text file.
Some of these evaluations use different code so I benefit a lot from this model because I can use inheritance and polymorphism.
Once the object is created there isn't any need to execute additional code on the object (at least for now) and it is used more like a struct; its kept on a list and 3 properties are used later.
I think this design is the easiest to understand, code, and read.
A logical alternative I guess would be using functions that return score structs, but you can't inherit from methods so it would make it kind of sloppy imo.
I am using vb.net and these classes will be used in an asp.net web app as well as in a distributed app.
thanks for your input
Executing code in a constructor is OK; but having only properties with no methods might be a violation of the tell don't ask principle: perhaps instead those properties should be private, and the code which uses ("asks") those properties should become methods of the class (which you can invoke or "tell").
In general, putting code that does anything significant in the constructor a not such a good idea, because you'll eventually get hamstrung on the rigid constructor execution order when you subclass.
Constructors are best used for getting your object to a consistent state. "Real" work is best handled in instance methods. With the work implemented as a method, you gain:
separation of what you want to evaluate from when you want to evaluate it.
polymorphism (if using virtual methods)
the option to split up the work into logical pieces, implementing each piece as a concrete template method. These template methods can be overridden in subclasses, which provides for "do it mostly like my superclass, but do this bit differently".
In short, I'd use methods to implement the main computation. If you're concerned that an object will be created without it's evaluation method being called, you can use a factory to create the objects, which calls the evaluate method after construction. You get the safety of constructors, with the execution order flexibility of methods.

How do you fight growing parameter list in class hierarchy?

I have a strong feeling that I do not know what pattern or particular language technique use in this situation.
So, the question itself is how to manage the growing parameter list in class hierarchy in language that has OOP support? I mean if for root class in the hierarchy you have, let's say 3 or 4 parameters, then in it's derived class you need to call base constructor and pass additional parameters for derived part of the object, and so forth... Parameter lists become enormous even if you have depth of inheritance more than two.
I`m pretty sure that many of SOwers faced this problem. And I am interested in ways how to solve it. Many thanks in advance.
Constructors with long parameter lists is an indication that your class is trying to do too much. One approach to resolving that problem is to break it apart, and use a "coordinator" class to manage the pieces. Subclasses that have constructor parameter lists that differ significantly from their superclass is another example of a class doing too much. If a subclass truly is-a superclass, then it shouldn't require significantly more data to do its job.
That said, there are occasional cases where a class needs to work on a large number of related objects. In this situation, I would create a new object to hold the related parameters.
Alternatives:
Use setter injection instead of constructor injection
Encapsulate the parameters in a separate container class, and pass that between constructors instead.
Don't use constructors to initialize the whole object at once. Only have it initialize those things which (1) are absolutely required for the existence of the object and (2) which must be done immediately at its creation. This will dramatically reduce the number of parameters you have to pass (likely to zero).
For a typical hierarchy like SalariedEmployee >> Employee >> Person you will have getters and setters to retrieve and change the various properties of the object.
Seeing the code would help me suggest a solution..
However long parameter lists are a code-smell, so I'd take a careful look at the design which requires this. The suggested refactorings to counter this are
Introduce Parameter Object
Preserve Whole Object
However if you find that you absolutely need this and a long inheritance chain, consider using a hash / property bag like object as the sole parameter
public MyClass(PropertyBag configSettings)
{
// each class extracts properties it needs and applies them
m_Setting1 = configSettings["Setting1"];
}
Possibilities:
Perhaps your class(es) are doing too much if they require so much state to be provided up-front? Aim to adhere to the Single Responsibility Principle.
Perhaps some of these parameters should logically exist in a value object of their own that is itself passed in as a parameter?
For classes whose construction really is complex, consider using the builder or factory pattern to instantiate these objects in a readable way - unlike method names, constructor parameters lack the ability to self document.
Another tip: Keep your class hierarchy shallow and prefer composition to inheritence. That way your constructor parameter list will remain short.

When to use an object instance variable versus passing an argument to the method

How do you decide between passing arguments to a method versus simply declaring them as object instance variables that are visible to all of the object's methods?
I prefer keeping instance variables in a list at the end of the Class, but this list gets longer as my program grows. I figure if a variable is passed often enough it should just be visible to all methods that need it, but then I wonder, "if everything is public there will be no need for passing anything at all!"
Since you're referring to instance variables, I'm assuming that you're working in an object-oriented language. To some degree, when to use instance variables, how to define their scope, and when to use local variables is subjective, but there are a couple of rules of thumb you can follow whenever creating your classes.
Instance variables are typically considered to be attributes of a class. Think of these as adjectives of the object that will be created from your class. If your instance data can be used to help describe the object, then it's probably safe to bet it's a good choice for instance data.
Local variables are used within the scope of methods to help them complete their work. Usually, a method should have a purpose of getting some data, returning some data, and/or proccessing/running an algorithm on some data. Sometimes, it helps to think of local variables as ways of helping a method get from beginning to end.
Instance variable scope is not just for security, but for encapsulation, as well. Don't assume that the "goal should be to keep all variables private." In cases of inheritance, making variables as protected is usually a good alternative. Rather than marking all instance data public, you create getters/setters for those that need to be accessed to the outside world. Don't make them all available - only the ones you need. This will come throughout the development lifecycle - it's hard to guess from the get go.
When it comes to passing data around a class, it's difficult to say what you're doing is good practice without seeing some code . Sometimes, operating directly on the instance data is fine; other times, it's not. In my opinion, this is something that comes with experience - you'll develop some intuition as your object-oriented thinking skills improve.
Mainly this depends on the lifetime of the data you store in the variable. If the data is only used during a computation, pass it as a parameter.
If the data is bound to the lifetime of the object use an instance variable.
When your list of variables gets too long, maybe it's a good point to think about refactoring some parts of the class into a new class.
In my opinion, instance variables are only necessary when the data will be used across calls.
Here's an example:
myCircle = myDrawing.drawCircle(center, radius);
Now lets imaging the myDrawing class uses 15 helper functions to create the myCircle object and each of those functions will need the center and the radius. They should still not be set as instance variables of the myDrawing class. Because they will never be needed again.
On the other hand, the myCircle class will need to store both the center and radius as instance variables.
myCircle.move(newCenter);
myCircle.resize(newRadius);
In order for the myCircle object to know what it's radius and center are when these new calls are made, they need to be stored as instance variables, not just passed to the functions that need them.
So basically, instance variables are a way to save the "state" of an object. If a variable is not necessary to know the state of an object, then it shouldn't be an instance variable.
And as for making everything public. It might make your life easier in the moment. But it will come back to haunt you. Pease don't.
IMHO:
If the variable forms part of the state of the instance, then it should be an instance variable - classinstance HAS-A instancevariable.
If I found myself passing something repeatedly into an instance's methods, or I found that I had a large number of instance variables I'd probably try and look at my design in case I'd missed something or made a bad abstraction somewhere.
Hope it helps
Of course it is easy to keep one big list of public variables in the class. But even intuitively, you can tell that this is not the way to go.
Define each variable right before you are going to use it. If a variable supports the function of a specific method, use it only in the scope of the method.
Also think about security, a public class variable is susceptible to unwanted changes from "outside" code. Your main goal should be to keep all variables private, and any variable which is not, should have a very good reason to be so.
About passing parameters all they way up the stack, this can get ugly very fast. A rule of thumb is to keep your method signatures clean and elegant. If you see many methods using the same data, decide either if it's important enough to be a class member, and if it's not, refactor your code to have it make more sense.
It boils down to common sense. Think exactly where and why you are declaring each new variable, what it's function should be, and from there make a decision regarding which scope it should live in.