What are typical functions in object oriented programming? - programming-languages

I Could not find answer anywhere on the internet.
can someone please explain with example.

Functions are normally referred to procedural programming. In OOP, you have methods which are actually functions in nature, work the same as functions but they always work in relation to some object. You cannot declare a method/function without creating a class for it, similarly you need to always call functions using its object. So, the approach of making functions and just calling them to work doesn't work the same way in OOP. You have to associate them with a class here and usually with a constructor for that class too.
Let me show you that with an example.
Suppose we are writing code in C, which is a procedural language, a function looks like this:
int add(int a, int b){
return a+b;
}
Now for java, the method in OOP looks like this,
class NumberAdder{
int num1;
int num2;
NumberAdder(int num1, int num2){
this.num1=num1;
this.num2=num2;
}
public int getSum(){
return num1+num2;
}
}

Depends on the application and how everything is organized. In OOP, the word "methods" is actually preferred to distinguish from "functions" which are not part of an object. Look at the documentation for any library and you should find some examples.
Unity is a game engine and should make sense intuitively. Collider has methods for finding nearest points and detecting collisions. ParticleSystem has a method for emitting particles. Camera has a method for rendering. etc.
https://docs.unity3d.com/ScriptReference/ParticleSystem.html

Related

Operators for classes imported from .net dlls

I am trying to use Haxe to write scripts for game engines like Unity or Godot.
In both cases I am unable to write a line like
Translate(dir * 100.0);
where dir is a Vector2 imported from the .net dll of Godot resp. Unity.
The working alternatives I found so far would be
Translate(Vector2.op_Multiply(dir, 100.0));
which on first sight seems like a bug in the hxcs module, but after some research it seems like a limitation of Haxe's type system.
The other alternative would be to use an abstract type to overload the operator resulting in code like this:
Translate(new Vector2WithOps(dir) * 100.0);
So my question is: is there a way to get around the explicit cast to the abstract type?
Intuitively it seems like Haxe should be able to apply the operators automatically when importing from C#, and it should be able to infer the type needed for the multiplication and perform the cast to the abstract type implicitly. I understand that there are technical reasons why both is at least difficult, but I am still hoping that there's a way I haven't seen yet.
So my question is: is there a way to get around the explicit cast to the abstract type?
Yes, abstracts allow defining implicit casts. You can simply add from Vector2 to Vector2 to the declaration:
abstract Vector2WithOps(Vector2) from Vector2 to Vector2 {}
That doesn't magically make something like dir * 100.0 work, however - you still need a way to trigger the cast of dir to a Vector2WithOps, for instance by assigning it to a variable typed that:
var dirWithOps:Vector2WithOps = dir;
There's also a special syntax called type check to trigger the cast:
(dir : Vector2WithOps)
Ultimately, the most convenient option would be to make sure that you're already working with a Vector2WithOps to begin with. That would work as long as you're creating new instances in your own code, but works less well when one is returned from a native API. This reminds me of a Haxe issue that considered allowing operator overloading through static extensions, which would be quite useful here: #2803

Examples of languages that hide variable multiplicity

What are some examples of programming languages, extensions to programming languages or other solutions that hides the multiplicity of variables when operating on them, calling method etc?
Specifically I imagine a system where I have a single typed collection of objects that transparently will forward any method call on the collection of objects so that the method is applied to all of them individually including using the return value in a meaningful way. Preferably I would like to see examples of languages that does this in a good way, but it could be interesting to see also solutions where this does not work well.
I imagine something like this:
struct Foo
{
int bar();
}
void myFunction()
{
// 4 Foo objects are created in a vector
vector<Foo> vals(4);
// The bar() method is applied to each of the Foo objects and each
// return an int that is automatically inserted into a new vector
vector<int> = vals.bar();
}
Take a look at Java 8 streams. Basically, you'd "stream" the container's contents, and indicate to the stream that each thing that goes through should have the method Foo::bar applied to it.
vals.stream().forEach(Foo::bar);
A lot of these concepts come from earlier languages, including Lisp (list processing).

Proper Uses for Abstracts

Just yesterday, I decided to begin learning the Haxe programming language after having used Actionscript 3 for the past few years. Today I have been exploring abstract types, and I have come to realize that they seem quite different from abstract classes in Java. I am beginning to grasp some of what they do, but I am unsure of what abstracts are used for. What constitutes the proper use of abstracts in Haxe, and when ought I to favor them over classes?
For instance, below is an incomplete definition for a complex number type using an abstract type. Ought I to prefer this or just an ordinary class?
abstract Complex({real:Float, imag:Float}) {
public function new(real:Float, imag:Float) {
this = { real: real, imag: imag };
}
public function real():Float { return this.real; }
public function imag():Float { return this.imag; }
#:op(A + B)
public static function add(lhs:Complex, rhs:Complex):Complex {
return new Complex(lhs.real() + rhs.real(), lhs.imag() + rhs.imag());
}
public function toString():String {
return real() + " + " + imag() + "i";
}
}
Indeed abstracts are not at all like abstract classes in Java. Abstract types in Haxe are powerful and interesting. Their main characteristic is that they are types that exist only at compile-time. At runtime they are entirely replaced by the wrapped type. Methods are transformed into static functions. In the case you described all of your instances will be replaced by anonymous objects with the two fields real and imag. Is that a good use case? Probably yes since a Complex type is not meant to be extended and you probably want to define some operator overloading (as you did for the addition).
To keep it even more light-weight you could use an Array<Float> as the wrapped type where the first element is the real part and the second the imaginary one.
So what is good about abstract types?
they add semantic to types (particularly primitive types). For example you could define an abstract RGB(Int) {} to always output very efficient color encoding with the benefit of methods and properties. Or you could have an abstract Path(String) {} to conveniently deal with path concatenation, relative paths and the like.
you can define operator overloading. In the case above you could do something like white + black and get something meaningful out of it.
similarly to operator overloading, abstracts can define implicit casts from and to other types. In the case of the RGB above you could easily define a method fromString() to parse an hex string into an Int representing a color. With the implicit cast you could do: var color : RGB = "#669900";. thx.color defines a lot of abstracts for color handling.
they are ideal to wrap the very powerful Enums in Haxe. With an abstract you can add methods and properties to enumerations (that natively do not support any of that).
they are ideal to wrap optimized code. Abstract methods can be inlined and the wrapped type ensures that you are not adding any additional layer of indirection when executing your code.
What is not so good? Or better, what we should know about abstracts?
since they are just a compile-time artifact, you cannot use runtime checks (eg: no Std.is(value, MyAbstract)).
abstracts are not classes, so no inheritance.

Is there a language where types can take content of fields into account?

I had this crazy idea and was wondering if such a thing exists:
Usually, in a strongly typed language, types are mainly concerned with memory layout, or membership to an abstract 'class'. So class Foo {int a;} and class Bar {int a; int b;} are distinct, but so is class Baz {int a; int b;} (although it has the same layout, it's a different type). So far, so good.
I was wondering if there is a language that allows one to specify more fine grained contraints as to what makes a type. For example, I'd like to have:
class Person {
//...
int height;
}
class RollercoasterSafe: Person (where .height>140) {}
void ride(RollercoasterSafe p) { //... }
and the compiler would make sure that it's impossible to have p.height < 140 in ride. This is just a stupid example, but I'm sure there are use cases where this could really help. Is there such a thing?
It depends on whether the predicate is checked statically or dynamically. In either case the answer is yes, but the resulting systems look different.
On the static end: PL researchers have proposed the notion of a refinement type, which consists of a base type together with a predicate: http://en.wikipedia.org/wiki/Program_refinement. I believe the idea of refinement types is that the predicates are checked at compile time, which means that you have to restrict the language of predicates to something tractable.
It's also possible to express constraints using dependent types, which are types parameterized by run-time values (as opposed to polymorphic types, which are parameterized by other types).
There are other tricks that you can play with powerful type systems like Haskell's, but IIUC you would have to change height from int to something whose structure the type checker could reason about.
On the dynamic end: SQL has something called domains, as in CREATE DOMAIN: http://developer.postgresql.org/pgdocs/postgres/sql-createdomain.html (see the bottom of the page for a simple example), which again consist of a base type and a constraint. The domain's constraint is checked dynamically whenever a value of that domain is created. In general, you can solve the problem by creating a new abstract data type and performing the check whenever you create a new value of the abstract type. If your language allows you to define automatic coercions from and to your new type, then you can use them to essentially implement SQL-like domains; if not, you just live with plain old abstract data types instead.
Then there are contracts, which are not thought of as types per se but can be used in some of the same ways, such as constraining the arguments and results of functions/methods. Simple contracts include predicates (eg, "accepts a Person object with height > 140"), but contracts can also be higher-order (eg, "accepts a Person object whose makeSmallTalk() method never returns null"). Higher-order contracts cannot be checked immediately, so they generally involve creating some kind of proxy. Contract checking does not create a new type of value or tag existing values, so the dynamic check will be repeated every time the contract is performed. Consequently, programmers often put contracts along module boundaries to minimize redundant checks.
An example of a language with such capabilities is Spec#. From the tutorial documentation available on the project site:
Consider the method ISqrt in Fig. 1, which computes the integer square root of
a given integer x. It is possible to implement the method only if x is non-negative, so
int ISqrt(int x)
requires 0 <= x;
ensures result*result <= x && x < (result+1)*(result+1);
{
int r = 0;
while ((r+1)*(r+1) <= x)
invariant r*r <= x;
{
r++;
}
return r;
}
In your case, you could probably do something like (note that I haven't tried this, I'm just reading docs):
void ride(Person p)
requires p.height > 140;
{
//...
}
There may be a way to roll up that requires clause into a type declaration such as RollercoasterSafe that you have suggested.
Your idea sounds somewhat like C++0x's concepts, though not identical. However, concepts have been removed from the C++0x standard.
I don't know any language that supports that kind of thing, but I don't find it really necessary.
I'm pretty convinced that simply applying validation in the setters of the properties may give you all the necessary restrictions.
In your RollercoasterSafe class example, you may throw an exception when the value of height property is set to a value less than 140. It's runtime checking, but polymorphism can make compile-time checking impossible.

Object Oriented Programming - Best Practice?

Which of the following would you go with?
And based on object oriented programming which one is the best practice?
A
Class Note
{
//Some properties, etc
public static Note getNoteFromServer();
public void UpdateNoteOnServer();
}
B
Class Note
{
//Some properties, etc
}
Class NoteManager
{
public static Note getNoteFromServer();
public static UpdateNoteOnServer(Note);
}
I would say option B. In that way you separate concerns: you have a Note that can be reused anywhere (and not necessarily on a networked application), and you have a manager class that only cares with server communication.
You may also think on implement logic for multiple servers. For example, you may want to comunicate with data formats like JSON or XML. You may implement an interface (example, interface INoteManager) and then implement two classes with servers for each of the data types I mentioned (example, NoteManagerXml and NoteManagerJson).
The main point on this question is sepration of concerns. Hope I've helped! :)
To take a different viewpoint from my other answer, I'd suggest that your division into Note/NoteManager is the wrong one - not because Note has anything wrong with it, but because the term Manager is a bit of a code smell because it's very generic, inviting the use of the class as a general dumping ground.
If the class is responsible for note persistence, call it NoteRepository.
If it's responsible for validating the content of a single note, move the logic onto the Note.
If it's responsible for creating notes, providing a number of convenience methods for easily creating notes, call it NoteFactory.
And if it's responsible for all of the above, split it into separate pieces because it's doing too much.
That's a pretty opinion based question you're asking there.
You're essentially asking (if I understand correctly) whether it is better to have a Class which contains only properties and another class to manage that object (Example B) or to have a class which does everything (Example A).
It really depends. If we're planning on using a MVC kind of framework, Example B would fit better, with Note being your Model, and NoteManager being the controller.
Personally, I would go with a hybrid of A and B, where NoteManager is handling controller actions, but the Model still has methods of its own to do things like managing a singleton instance. So maybe something like this?
Class Note
{
//Some properties, etc
public static Note getInstance(noteIdentifier);
public void saveNote();
}
Class NoteManager
{
// This handles view validation and calls Note.saveNote();
public static UpdateNoteOnServer(Note);
}
I think A is better, for 1 reason:
It implements the Object Oriented
paradigm to the letter.
The problem i see with B is that a static method that receives an instance of the same class sounds redundant to me because, why would you use a static method to apply behaviour to an instance of the same class? The whole idea behind classes and instances is that Classes are the frame and instances cookies, if you need different cookies, modify your frame and get new ones.
It seems to depend on how its going to be used in your program. If Note is the only class or is the parent class for derived classes then there is no point and having a "Manager", Keep It Simple Stupid (KISS). However if the Manager has to deal with other classes via Interfaces then I can see having a seperate class.
As per my experience best practice is , as long as things are separated DRY is best practice. you can extends note to notemanager
Class Note
{
//Some properties, etc
}
Class NoteManager
{
public static Note getNoteFromServer();
public static UpdateNoteOnServer(Note);
}
I'd choose B, unless you want to end up like poor ol' PHP:
get_note_from_server_and_print_the_response($note, 'PHP, why must you be so disorganized?')
But seriously, it may seem intuitive to do A at the moment, but you'll eventually split A up, as those server operations will require more and more related functions, until you have a mammoth Note class which contains every function in your program...
"It Depends"
One of the things it depends upon is the language of implementation.
If you are working in C# or Java, then you'll likely want to go with the Note/NoteManager approach as this gives you the most flexiblity of implementation - because static members in those languages a kind of second class citizens.
To illustrate, in Delphi's original Object Pascal lanaguage, methods and properties that could be accessed without an instance were known as class members, not static members, and they could be virtual, and therefore overridden in descendent classes.
If you're working with a language that provides features like "virtual class (static) members" and a few others, then you might want to merge Note/NoteManager together.
I would go with "B"
Reason why is that you may require "Note" to be used with another type of Controller class, like what you have done for NoteManager.
Also gives you the ability to dissociate your Data Objects or DTO's or Model away from your actual controller classes.
C
Class Note
{
//Some properties, etc
public static Note LoadFrom(Whatever);
public void SaveTo(Whatever);
}

Resources