{{unimplemented}}

Objects in MethodScript allow for object oriented approaches to designing your
code. Object in MethodScript are extremely flexible and powerful, yet easy to use
and understand.

=== Definition vs Instance ===

An object is an instance of a class. A class is defined in code, and is used to
define methods and members that will be in an instance of that object. A class
can be instantiated, and get a real object out of it at runtime. You can think
of the difference between the two as a blueprint for a house, there is only one
blueprint, but multiple houses that are actually built, and in each house, some
things are different, like, the paint color.

=== Example ===
Before getting into the details about objects, lets look at an example:

%%CODE|
class A {

	protected @b;
	private static int @C = 0;

    public A(int @b = 0){
        @this->b = @b;
        @C++;
    }

    public static int Method1(int @a){
        return(@a + 1);
    }

    public method2(int @b){
        return(@b + @this->b);
    }

    public static final int Instantiations(){
        return(@C);
    }
}
%%

This example will be used in the explanation below.

=== Members and Methods ===

An object contains any number of '''members''' and '''methods''', collectively
called '''elements'''. A member is a variable, and a method is a function. Both
members and variables can have various
'''modifiers''', which affect behavior in various ways. In the example, you can
see that we are defining @b as a member variable, and Method1 and method2
are methods. The modifiers in use include '''public''', '''static''', '''final''',
'''int''', '''protected''' and '''private''' though there are others too.

Additionally in this example, there is one '''constructor''', which is the code that
is called when a new instance of the object is created (see below). The constructor (or constructors,
there can be several). A constructor is defined by creating a method with the same name
as the object it's contained in, with no return type. The constructor is where you
may place code that is necessary for initial configuration of the object.

By convention, static elements are named with capital first letters, and
non-static elements are named with lowercase first letters, and all elements
use camel case.

=== Basic Type Manipulation ===
Before moving on to using objects, it is important to understand the type system
in MethodScript. All variables are ''mixed'' by default, which is actually an
object type. All objects extend from mixed, and all user defined objects extend
from Object. "Primitives" are in fact objects, though they are somewhat special,
in that they are handled differently internally, but in code, they behave exactly
like user defined objects, meaning you can dereference them to access their
methods. If a type isn't explicitly specified when defining a variable, it is
considered to be mixed, and any value can be put in it. Other than this caveat
which makes MethodScript different from other strongly typed languages, it is
otherwise a full strongly typed language, meaning types are checked at compile
time, and invalid types will cause compiler errors. Type intersections and
unions are discussed later, since they are an advanced topic, but they are also
supported.

=== Instantiation ===

In order to use an object, the first thing that must happen is that it is
instantiated. To instantiate our object that we defined above, we would use
the following code:

%%CODE|
A @A = new A();
%%

Now, we can use the '''dereference operator''' to access members or methods in
the object, for instance,

%%CODE|
msg(@A->method2(2));
%%

would output 2, since we called the method that returns our input plus @b,
which in this case is 0.

We can only have one constructor per object, but we can use default parameters,
and static methods can be created to fake multiple constructors, or we can use
type unions.
The constructor is simply a method that is defined with the same name of the
class, and no return type.

=== Overloaded Methods ===

Unlike procs, it is allowed to have multiple methods with the same name, so long
as they are distinguishable between each other based on the parameter lists.
This is allowed, for instance:

<%CODE|
class A {
	int method(){ return(1); }
	int method(int @a) { return(@a); }
}
%>

We can easily determine which method to call, based on whether or not we pass an int
to the method when we call it.

<%CODE|
	new A()->method(); // calls the first method
	new A()->method(1); // calls the second method
%>

Where this becomes a problem is when two parameter lists are indistinguishable from
each other.

<%CODE|
class A {
	void method(int @a, number @b) {}
	void method(number @a, int @b) {}
}

// This is a compile error, because which method should we be calling here, the first
// or the second? Both parameters match both methods.
new A()->method(1, 1);

// TODO: Actually, should this be allowed? When it comes to inheritance, we will
// probably run into the same problem as with varied return types.

// This is allowed, however, because we are explicitly typing the method, which allows
// us to exactly distinguish the method. This notation is in general allowed for any
// method, though is not necessary most of the time.
new A()->method<void, int, number>(1, 1);

// By the way, this is how you reference the Callable object, if you want to get
// a reference to the method dynamically, and there are multiple methods with the
// same name.
Callable<void, int, number> @m = A->method<void, int, number>;
%>

A method may be overridden with simply changing the return type, but then, just as
in the above example, would require fully qualifying the method each time it were
called. Due to this, anytime you define a method that would require disambiguation
every time it's called, a compiler warning is issued for the definition. This can
be suppressed, however.

=== Inheritance ===

An object can '''inherit''' from, or ''extend'' another object. Let's define the
object B, which extends A.

%%CODE|
class B extends A {
    public B(){
        super();
    }
    public method2(int @b){
        return(@b + 3);
    }
}
%%

In this case, we are extending A, and '''overriding''' method2. In order to
override a method, you simply name it the same as the method in the parent
class. However, it is important to note that the method signatures must be
'''type compatible''', that is, it cannot completely redefine the types of the
variables that are passed in, and there are specific rules for '''narrowing''' and
'''broadening''' types. Take the following examples:

<%CODE|
class A {
	number f(number @a) { /*...*/ }
}

class B extends A {
	// We are allowed to "narrow" the return type of a method, and this still
	// overrides the A->f method. Note that the override keyword is in place
	// to ensure this method does indeed override a parent method. If it does
	// not, it will cause a compile error, and actually, it is required
	// if the method does override a parent method.
	override int f(number @a) { /*...*/ }
}

class C extends A {
	// Not allowed! Actually, the only reason this isn't allowed is because we have
	// added the override keyword. It is possible to create this method anyways,
	// (without the override keyword), but then if the method were called, it would
	// follow the normal overloading rules of deciding which method to call, as
	// if we had simply created both methods within the same class.
	override number f(int @a) { /*...*/ }
}

class D extends A {
	// This is not allowed, (with or without the override keyword, it's a compiler error with it),
	// because the rules governing inheritance do not allow for return type changes.
	string f(number @a) { /*...*/ }
}
%>

In the last example, it is shown that return type changes are not allowed (only narrowing is).
Why is this, when return type changes are allowed within a single class? Consider the following code.

<%CODE|
// We are creating a new D, but the variable @a is defined as type A
A @a = new D();
// One might think this should work, because D defines a method with return type
// string, accepting one number parameter. However, the variable is defined as A, not D!
// It is entirely possible that instead of an object of type D, we have an object of
// type A, which does not define a method<string, number>.
@a->f<string, number>(1);
%>

Examining the constructor, there is the new function, <code>super()</code>,
which is used to call the parent's constructor. <code>super</code> is optional,
however, in the case where a call to <code>super()</code> is omitted, it is
implied to have been called at the top of the child's constructor. If
<code>super()</code> is called, it must be called ''before'' manipulating the
parent's members, even transiently, otherwise it is a compiler error. For
instance, consider the following:

%%CODE|
class A {

	private int @a;

    public A(){
        @a = 0;
    }

    public void initA(){
        @a = 9000;
    }

    public int getA(){
        if(time() &percnt; 2 == 0){
            initA();
        }
    }
}

class B extends A {
    public B(){
        int @var = getA();
        super(); // Compile error
    }
}
%%

In this example, we have a compile error, because the call to getA() could
potentially call initA(), which manipulates @a, which is a member variable.
The reason for this is so that the object is never in an ''inconsistent state''
which could occur if a subclass manipulates members of the parent before it is
allowed to run its initialization. Had we left off the call to super, it would
have been automatically placed at the top of the constructor, and this would not
have been a compile error.

This works differently if there are no default constructors defined in the superclass,
and the subclass defines constructors with different signatures (which is allowed).
If so, in that case, it is required to call any constructor on the superclass
manually. For instance:

<%CODE|
class A {
	public A(int @a) {
		// Note we are defining a constructor that accepts an int
	}
}

class B extends A {
	public B(int @b) {
		// super(@b);
		// No call to super is required, it will be added automatically for us
		// at the top, because we are defining a constructor with the same signature
		// as one defined in A. It may be necessary to make a call to the superclass
		// anyways, however, if you wish to change the value that is sent to the
		// superclass's constructor. However, by default, the one added automatically
		// will simply re-call super with the list of arguments that were passed in
		// to this constructor.
	}
	public B() {
		// In this case, we are defining a constructor that accepts no
		// argument. But there is no constructor defined with no arguments
		// in A, so we must manually call it ourselves, and provide a value.
		super(0);
	}
}

%>

==== Default Constructors ====

If zero constructors are provided, a default constructor is always provided, with
the definition:

<%CODE|
/**
 * @{InheritDoc}
 */
@{Inject}
public A(){
	if(@self != mixed) {
		super();
	}
}
%>

(Assuming the class name is A). However,
if a superclass defined a constructor that accepted parameters, without also
defining a constructor that takes no arguments, this will not happen, and you
must manually define a constructor which calls <code>super</code> with the appropriate
inputs.

Note that the default constructor is annotated with the @{Inject} annotation. If you do not
wish your class to be automatically injectable, you need to implement a no-arg constructor yourself, with
the @{NoInject} annotation. (This is used in the [[Dependency Injection|DependencyInjection]] framework.)

=== Static members and methods ===
You may have noticed that the keyword '''static''' has been used a few times.
A ''static'' variable is one that is usable outside of any instances, often times
utility methods, singletons, and factory methods are defined this way. A static
method can be accessed as such:

%%CODE|
class A {
	public static void init(){
		return()
	}
}

#Usage:
A::init()
%%

You do not need to instantiate a class before using a static method. Since a static
method is essentially a convenient way to namespace a method, or otherwise
associate it with similar non-static code and it isn't ''really'' part of the class,
it is not possible to call a static method by dereferencing an instance. If you are creating
a pure utility class, that only has methods (no members), then consider using
a namespace instead.

==== <code>@this</code> and <code>@self</code> variables, and <code>super</code> and <code>self</code> keywords ====
There are two variables that are specially defined within code inside a class,
<code>@this</code> and <code>@self</code>. <code>@this</code> refers to the
current instance of the class, and while not usually necessary, can be used in
all cases to provide clarity to the code. In some cases, however, it is necessary,
when a local variable hides a member variable. In our original class example, we
have the following code:

<%CODE|
	protected @b;

	public method2(int @b){
		return(@b + @this->b);
	}
%>

In this case, we must use the @this keyword, as we are naming the method's argument
<code>@b</code>, and so to differentiate between that and the member variable, we must
use <code>@this->b</code>. <code>@this->b</code> refers to the member variable, and
<code>@b</code> refers to the variable that is passed in to the method, that is,
the local variable.

<code>@self</code> works in somewhat the same way, but it ALWAYS refers to the class
that it is used in, whereas <code>@this</code> refers to the instance that the type
is at runtime. To be very precise, <code>@this</code> refers to the current
instance of the class, which may be an instance of the current class, or it may be
an instance of a subclass. However, <code>@self</code> always refers to the current
class. This can be useful to call a method that is not private, when you want to ensure
that the code being called is not code that is overridden by a subclass. This feature
should generally speaking be used sparingly, as it is a violation of the Liskov Substitution
Principal, though it can be used in meta cases, for instance, to dynamically get the current
class definition for reflective purposes. It can also be useful when calling static methods.

<%CODE|
// This will ALWAYS call the method defined in this class, and may be easier to type
// than the full name of the current class name.
@self::StaticMethod();

// If the subclass does not redefine the StaticMethod method, then using @this is the
// same thing. However, if a subclass redefines this method, and the instance was
// constructed as that subclass, this will refer to a different method.
@this::StaticMethod();
%>

The <code>super</code> keyword refers to the direct superclass. In the above examples,
we used it to call the superclass's constructor, but it can more generally be used to
refer to an element defined within a superclass.

<%CODE|
class A {
	public string @x = 'a';
	public string method() {
		return(@x);
	}
}

class B {
	@{Override} // It is good practice to use this annotation, and is required in strict mode
	public string method() {
		return(super->method()->toUpperCase());
	}
}

A @a = new A();
msg(@a->method()); // 'a'
B @b = new B();
msg(@b->method()); // 'A'
@b->x = 'xyz'; // Note we are changing @x which is defined and only referenced in A
msg(@b->method()); // 'XYZ'
%>

The <code>self</code> keyword refers to the ClassType of the currently defining class. This is a shortcut
to listing the current defining type, and can generally be thought of as simply replacing the self keyword
at compile time with the ClassType of the currently defining class. (Though this isn't exactly the case.)
This is mostly useful when defining method signatures. For instance:

<%CODE|
class A {
	/**
	 * If this method is overridden by a subclass, it must return an object of its own class (or a subclass). As it
	 * stands in this method, the return type must be of class A.
	 */
	self newInstance() {
		return(new A());
	}
}

class B extends A {
	/**
	 * Since the return type was defined as self, we MUST also define the return type here as self, for this
	 * to be a proper override. But in this case, we must return a value of type B, not type A.
	 */
	override self newInstance() {
		return(new B());
	}
}
%>

The self keyword can also be used in generic definitions, such as <code>ClassType<? extends self></code>, and within
general code, such as <code>self @a = new self();</code> or <code>msg(self);</code>.

=== Access Modifiers ===
'''public''', '''protected''', '''internal''', '''package''', and '''private''' are the five modifiers that
control what can access an object's methods or members (in order of visibility). If something is public,
anything can access it. If it is private, only that class can access it, and if
it is protected, only that class, or subclasses can access it. '''package''' means
that only classes defined within the same folder (or subfolders) may access it, and '''internal'''
means that only classes within that project (or class library, depending on how the class
library is set up) can access it.

The access modifier may be left off. In that case, the behavior is a bit dynamic. If the method
is defined in a parent class or interface, then the method will adopt the overridden
method's access modifier. For classes, it will be whatever the parent specifically set
it as, and for methods defined in an interface, they will be public. (They are necessarily
public anyways, because all methods in an interface are public.) If the defined method
is not overriding a method in a parent class, then the method is considered internal.
Fields that have the default visibility default to internal.

In general, when overriding methods in a parent class, it is only possible to grant it
a higher visibility state. For instance, if the parent class defines a method as public,
the child class cannot make it private. However, the opposite is allowed. If a parent
class defines a method as protected, a child class can make it public.

The modifier can be applied to methods and fields, but also to classes. This leads
to an interesting effect, however. If there is a class defined with a lower visibility
than a method which returns or has parameters of a type that has a lower visibility, then
it means that the method cannot in fact be called by code that is not of the appropriate
visibility. If this occurs, then a compiler error will be issued. To fix it, you may either
make the class the same visibility as the method, or you can reduce the visibility of the
method.

=== Explicit namespacing ===
In an instance, we can always using explicit namespacing to reference a parent's
methods. If we are in a static context, it will be a compiler error to reference
instance methods in this manner, but static references are always valid. For
instance, assume class B had been defined this way:

%%CODE|
class B extends A {
    public B(){
        A::super()
    }
    public method2(int @b){
        return(A::super->method2(@b))
    }
}
%%

Note that we are explicitely calling A's constructor with the call to super,
and A's method2. If there had been several parents, this could be used to
"un-override" a call, or otherwise explicitely selected a method that had been
overridden by multiple children. This is useful outside of diamond inheritance,
but is more often used when dealing with multiple inheritance. Note that in the
case of super() constructors, it is always an error to cause a child's
constructor to be invoked before the parent's constructor. Calling a parent's
method is only valid inside the class, an overridden method is not callable
from outside of the instance.

<!--
=== Reflection ===
Using reflection, you are able to access all members and methods reflectively,
using simple, array-like notation. Using reflection bypasses the safeguards put
in place with public/private/protected accesses though, which may be desired,
but should be used with caution, since it violates the object's contract of
access. All objects implement the ability to get, set, and enumerate all the
members and methods in it, using string based names. New members and even methods
can be added to an object at runtime by using this mechanism. Compilation type
checks obviously won't apply, so things that normally would be a compile error
will be runtime errors, so code that uses reflection must be very careful.
Consider our class A, defined above, and instantiated as such:

%%CODE|
A @a = new A();
%%

We can access both the protected and private static variables in the class by
using the following code:

%%CODE|
msg(@a['A::b'])
msg(@a['c'])
%%

If you do not fully qualify a variable name, it is automatically qualified with
that instance's actual runtime type. So unless you want to actually get a type's
method without caring precisely which method it will be, consider always fully
qualifying the variable name. (@a['A::b'] vs @a['b'])

We can change existing variables (or add new ones) with:

%%CODE|
@a['A::b'] = 5
@a['A::c'] = 10
@a['A::d'] = proc(@a, @b){ return(@a + @b) } #Add a new method
%%

If a variable is added with reflection, it will obviously only be
accessible through reflection, and it only becomes part of that instance.
Changes to static variables or methods are not possible, because static variables
are not actually a part of that instance. You must use the class reflection methods
to manipulate those. The array
notation is merely a convenience, using this notation simply hides the
complexity of getting and setting static and instance variables reflectively.
You can iterate through the variables using foreach, and array_keys will work
as well. As you can see, for this reason, a member and a method cannot share
the same name in a class. It is also important to note that variables are
prefixed with the class name, because a parent's variables are also available.
In the case of inherited variables, the child class will not have a variable in
the array, even though calling the method non-reflectively would work.

This mechanism of reflection is useful for setting and getting variables in an
''instance'', but if you are interested in information about the Class itself
(not an instance of it, or you are interested in static variables)
you can use the functions that are provided in the reflection namespace.
-->

=== Interfaces ===

Interfaces are a way to define the methods and constructors in an object, without actually implementing them. Thus, an
interface is not allowed to have code, but merely provides the definitions. Since all methods in an interface are only
useful as publicly accessible from outside classes, no access modifiers are allowed in the "instance" and unimplemented
static methods in the interface definition, everything is implied to be public. The exception is that static elements
are allowed to be defined and implemented within an interface.

<%CODE|
interface MyInterface {
	/**
	 * It is extremely useful to be sure to add comments in interfaces, since they are the ideal thing to program
	 * against.
	 */
	void method();

	void method2();

	/**
	 * This method being static and unimplemented means that it is an error to call MyInterface::method3(), but
	 * it is allowed to call @a::method3() where @a is an instance of MyInterface, because in reality, @a would
	 * be some concrete class, as interfaces cannot be instantiated.
	 */
	static void method3();

	/**
	 * Since this is implemented, it is allowed to call MyInterface::method4();
	 */
	static void method4() {
		msg();
	}

	/**
	 * This is a constructor definition. This enforces that all implementing classes must provide a constructor
	 * with this signature (though it can have others as well).
	 */
	MyInterface(int @a);
}
%>

It is not allowed to construct a new instance of an interface. Instead, you must instantiate an instance of a
'''concrete class''', or an object that is defined with the '''class''' keyword. However, if an interface was
defined with a constructor, it is allowed to dynamically construct classes that implement this interface, for
instance:

<%CODE|
// One may often use <? extends MyInterface> which can refer to any interface, class, enum, etc, but
// restricting it further to class means that only concrete classes can be provided. This is useful
// when implementing a factory pattern, though consider dependency injection instead.
ClassType<class extends MyInterface> @c = MyClass;
MyInterface @a;
//@a = new @c(); // Compile error, because MyInterface does not define a no-arg constructor
@a = new @c(1); // Correct, as MyInterface defined a constructor that takes 1 int argument.
%>

=== Abstract Classes ===

=== Multiple Inheritance ===

==== <code>inherit</code> keyword ====

Though default inheritance would work in singly inherited classes, it is really
only useful when dealing with multiple inheritance. In the case where multiple
objects are inherited from, and each defines their own version of a method,
it may be useful to inherit the method's behavior from the non-primary inherited
class. One way to do this would be to override the method yourself, and simply
delegate behavior to the correct super class's method, for instance:

%%CODE|
class A {
	public mixed method(int @a){
		return(@a + 1);
	}
}

class B {
	public mixed method(int @a){
		return(@a);
	}
}
class C extends A, B {
	public mixed method(int @a){
		return(B::method(@a));
	}
}
%%

However, since this could occur fairly often, you may simply indicate that you
would like to ''inherit'' functionality from the specified parent. So instead
of defining the class C as above, we can get the exact same functionality by
defining it as such:

%%CODE|
class C extends A, B {
	inherit B::method(int @a);
}
%%

By default, methods with multiple overrides in parent classes inherit from the
primary parent, in this case, A, though you can also be explicit and inherit a
method individually. If no access modifier is provided, the method is inherited with
the same access level as the parent method. However, the visibility of the method
may also be increased:

<%CODE|
class A {
	protected void method(int @a) {
		//...
	}
}

class B extends A {
	/**
	 * This increases the visibility of the method, but changes nothing else. Note that in general,
	 * it is not allowed to decrease the visibility of any method, whether or not it is inherited using
	 * the inherit keyword.
	 */
	inherit public method(int @a);
}
%>

=== Type Unions ===

A type union can be used any time disjoint types are required. Assume the following
hierarchy:

%%CODE|
class A { }
class B extends A { }
class C extends A { }
class D extends B { }
%%

Now, assume that we want to accept an instance of either type D or type C, but not
type B or A. In this case, the nearest parent is type A, so we could accept type A and
do a runtime check to ensure that it is of type D or C only, but this is a runtime
check, and it would be better if we could simply declare that we only want those
two types. In that case, we can use a '''type union''' to signal to the compiler
the various types we will accept. To specify a type union, use the
'''%%NOWIKI||%%''' character.

%%CODE|
D | C @var;
%%

As many types as required can be chained this way. As far as the inferred type of
that object, it will be whatever the nearest '''type intersection''' is. So, in this
case, the code using the variable @var must assume that it is of type A, unless it
does an explicit cast first. So, as far as code that ''uses'' the variable, it will
work as if it were defined as <code>A @var</code>, but with the guarantee that only
a D or C type instance will have been assigned to it.

=== <code>use</code> statements ===

If classes were not arranged in a hierarchical structure, we would quickly find
ourselves being overwhelmed with naming conflicts, if two classes had the same
name. Therefore, MethodScript supports a hierarchical naming system. To define
a class within this
hierarchy, simply add the package name to the class when defining it.

<%CODE|
// Instead of this:
class A {}
// do this:
class organization.project.B {}
%>

In general, the naming convention should follow the convention of
organizationIdentifier.projectName, which, if followed correctly, will prevent
overlapping class names, but if the organization represents a single
project, it can be ok to leave off the project name. In general, the
organization name should be based on a domain you control, in reverse
domain order. For instance, if you own me.example.com, your organization
name should be "com.example.me". This is not required, but substantially
reduces confusion, especially when distributing your code.

When creating a class like this, references to that class must be the '''fully qualifed \
class name''', for instance, following the above class definitions:

<%CODE|
A @a = new A();
organization.project.B @b = new organization.project.B();
%>

All classes should be within a hierarchy, but having to type the fully qualified class
name every time is very cumbersome. Instead, you can use the '''use''' keyword to tell
the compiler to imply a package name.

<%CODE|
// This tells the compiler to look in the organization.project package if it can't find a class
use organization2.project;
use organization.project;

// So far so good, we have a class named A
A @a = new A();

// Uh oh, we don't actually have a class named B, but we do have one named organization.project.B.
// The compiler will see that we don't have a class named B, but will not give up yet, it will see
// if there is a class named "organization2.project.B" and "organization.project.B". There is one
// named organization.project.B, so it will internally change this line to
// organization.project.B @b = new organization.project.B();
// for us, then get rid of the use statements.
B @b = new B();
%>

Since this is just syntax sugar, rather than a runtime setting, this is why you will always
see references to a class's fully qualified class name when reading error messages and things.
So, are system level classes in a hierarchy? Yes, they are! So why do you not need use
statements for them? The system automatically adds some use statements for you. Particularly,
it always adds <code>ms.lang</code>, as well as the current package,
but others may be added as well. Regardless, the ones
that are added automatically are added as if they are below all of your use statements. This
allows you to define classes with the same name as system classes, without having to fully
qualify them. On the flip side, if you have duplicate class names, and you use both within
a file, at least one of them would have to be fully qualified anyhow, but the consolation is
that at least '''ms.lang.''' is relatively little to type. Otherwise, the search pattern for
classes always goes from top to bottom in the use statements, if there are duplicate class
names.

You don't have to provide the full package for the class names either. If you have a class
named com.project.util.MyClass, you can <code>use com.project;</code>, and then refer to the
class as <code>util.MyClass</code>, though it's usually just as well to
<code>use com.project.util;</code>.

Additionally, you can use the asterisk notation in a use statement, to ''use'' all
the subdirectories, for instance, if we have 3 classes, named com.org.util.class1,
com.org.class2, com.org.folder.class3, we can do:

<%CODE|
// This line is equivalent
use com.org.*;

// to these lines:
use com.org;
use com.org.util;
use com.org.folder;
%>

In general, this is not advised, as this may cause problems down the road if,
within the * structure, any class names are duplicated, and you're using one
of them, it will become a compile error. Therefore, it is still recommended that
you fully qualify the package name. Nevertheless, this functionality is available.

=== Inner Classes ===
An inner class is a class that is defined within another class, for instance:

<%CODE|
class my.project.A {
	static class B {}
}
%>

There are two types of inner classes, however, unlike an outer class, an instance based
class, and a static class. The above example shows an static inner class being defined.

A static inner class is easier to explain, as it is essentially just a way of further
containing other classes, and is nearly purely an organizational mechanism. (Though
there are a few access differences.) The inner class is
defined as if the outer class is simply a package, so the fully qualified class name of
B in this example is <code>my.project.A.B</code> and creating a new instance of class B
works the same as other usual cases: <code>new my.project.A.B();</code>. You can also
'''use''' the outer class, same as if it were a package, and then no longer need to
fully qualify the inner class.

<%CODE|
// If we simply use the actual package, we can do A.B to fully qualify it
use my.project;

new A.B();

// Or we can use the outer class, and just use the simple name
use my.project.A;

new B();
%>

On the other hand, an instance based class is one that can only exist in the context of an instance of the
parent class. You cannot create a new instance of class B without creating an instance of
class A, then using that to create the new class B. To define the instance based class,
leave off the static keyword.

<%CODE|
class A {
	class B{}
}
%>

In this example, we have to first create a new instance of the outer class, in order to create
an instance of the inner class. We can dereference the instance of A, and use the new keyword,
such as this:

<%CODE|
new A()->new B();
// Or create it later
A @a = new A();
@a->new B();
%>

Within the class A, in non-static methods, we can create a new instance of the class B
in the usual manner, since <code>@this</code> is implied. This is the most common use
of instance classes.

<%CODE|
class A {
	class B {}

	public B newInstanceOfB() {
		return(new B());
	}
}

B @b = new A()->newInstanceOfB();
%>

Within the inner class, we have access to all elements of the outer class, and vice-versa,
including private elements, though an inner static class only has access to the static
context, and therefore cannot call instance (non-static) elements.
However, if it has an instance of the outer class, it may access private elements on the instance.

Inner classes are allowed to create elements named the same as the outer class, therefore it
is sometimes useful to differentiate between what exactly <code>@this</code> refers to.

<%CODE|
class A {
	string @myProperty = "A->myProperty";
	string @a = "A->a";

	class B {
		string @myProperty = "B->myProperty";
		string @b = "B->b";

		public void method() {
			msg(@a); // Definitely refers to A->a
			msg(@b); // Definitely refers to B->b
			// Overload! In general, accessing any
			// class element is the same as using an
			// implied @this, so both @myProperty
			// and @this->myProperty refer to the
			// same thing, B->myProperty.
			msg(@myProperty); // B->myProperty
			msg(@this->myProperty); // B->myProperty
			msg(A::this->myProperty); // A->myProperty
		}
	}
}
%>

=== Immutable classes and immutable variables ===
Classes may be marked as immutable, which means that none of the fields in the class may be changed after construction
is complete.

<%CODE|
immutable class A {
	string @myProperty;
	// This is effectively constant due to the fact that we don't modify the value in the constructor
	string @constant = "const";
	public A(string @value) {
		@myProperty = @value;
	}

	public void m() {
		// Can't do this, would be a compile error
		// @myProperty = "test";
	}
}
%>

Immutable classes may be useful from a business logic standpoint, as it allows enforcement of immutability by the
compiler. However, the compiler/runtime can also do some optimizations when immutable classes are used, for instance,
classes that are immutable can be passed either by value or reference, and the effective result will be the same. So
the runtime may choose the most performant method if a class is marked as immutable.

Individual fields may be marked as immutable as well. This has the effect of making the class immutable, but only
through that particular object reference.

<%CODE|
// Note that MyObject is not immutable
class MyObject {
	public string @value;

	public void setValue(string @v) {
		@value = @v;
	}
}

class A {
	MyObject @a;
	immutable MyObject @b;

	public A(MyObject @a, MyObject @b) {
		this->@a = @a;
		this->@b = @b;
		// This is valid. Immutable values are not "frozen" until construction is complete.
		this->@b->@value = "initial value";
		this->setup();
	}

	public void m() {
		// Valid
		this->@a->@value = "test";
		this->@a->setValue("test");

		// Compile error, fields in @b may not be modified, either directly or indirectly
		// this->@b->@value = "test2";
		// this->@b->setValue("test2");
		// this->setup();
	}

	private void setup() {
		// This is valid too, but only because the setup method is only called from the constructor. Note that this
		// method is actually not available to the reflection mechanism either, as it is inlined in the constructor.
		this->@b->@value = "called from setup";
	}

	public void publicSetup() {
		// This isn't valid, because the method is public. Methods that modify immutable values are only allowed
		// to be private, and are only allowed to be called from the constructor.
		// this->@b->@value = "invalid";
	}
}
%>

Immutable fields are a sort of overloaded type. That is, ''MyObject'' is different
than ''immutable MyObject'', and it is required to declare them differently in each use. Mutable fields may safely
be cast to the immutable variant, but not vice versa.

<%CODE|
class A {
	immutable MyObject @immutable;
	MyObject @mutable;

	public void set(immutable MyObject @v) {
		this->@immutable = @v;
	}

	public void set(MyObject @v) {
		this->@mutable = @v;
	}
}

A @a = new A();
@a->set(new immutable MyObject()); // sets the immutable object
@a->set(new MyObject()); // sets the mutable object
@mo = new MyObject();
@a->set((immutable MyObject) @mo); // sets the immutable object, despite the @mo value being mutable
%>

It's also worth pointing out that an immutable field is not constant, and the referenced object may be changed,
(unless the field is marked as ''final'' in addition). The previous example shows this, when we set ''@immutable''
in the set method, this is allowed. What we cannot do, however, is set some field within the MyObject instance,
even if MyObject normally does declare some publicly accessible methods that set fields.

If a class itself is marked as immutable, it is not an error to also mark an instance of the field as immutable. This
can be desirable anyways, in cases where it's possible that the class itself becomes mutable in the future, but
regardless, you wish this field to always be immutable. In general, however, it's bad practice to change a class's
mutability after release.

=== Class Library ===
In general, MethodScript prefers to work with classes that are defined in the '''Class \
Library'''. When using the class library, this prevents complex management of include
statements, and also provides an easier and more straightforward mechanism of managing
the classes within the class library, as well as enabling certain features in the compiler
that expect to know about all classes beforehand. '''Dynamic Classes''' are discussed below,
but are not expected to be used in normal use. Multiple class libraries may be defined,
but they must all be known at compile time, and may not be added to later.

So what is the Class Library? It is simply a folder in your project directory that contains
several .ms files, which define classes. Your "default" class library is defined within
the classLibrary/ folder in your installation, but each LocalPackage may have their own
classLibrary folder as well. MSLP files will have their own class library bundled in
as well. When an .ms file is defined within a class library, the rest of your code does
not have to do anything extra to load them in; at compile time, they will all be loaded
automatically, and added to the object definition table that is usable at runtime
throughout the rest of your code. There can be no directly executable code within these
file, however, and this is enforced by the compiler. There may be only one outer class
definition per file, and the fully qualified class name will be the path of the class,
starting at the root of the class library folder. For instance, if we have the following
file structure:

<pre>
classLibrary/
----organization/
--------project/
------------MyClass1.ms
------------MyClass2.ms
</pre>

Then we would have 2 classes defined, '''organization.project.MyClass1''' and '''organization.project.MyClass2'''.
The namespace for both of these classes must be defined as "organization.project", since they are within the
'''organization/project''' folder structure.
The name of the file must correspond to the name of the class, this will be a compile
error otherwise.

If we looked at MyClass1.ms, we might see the following:

<%CODE|
use my.project;

class organization.project.MyClass1 {
	// OtherClass is defined in my.project
	public OtherClass @a;
}
%>

==== classLibrary Manifest ====
In addition to providing a project structure, a class library may contain one or more '''manifest''' files,
(named simply "manifest.json"). There must be one manifest at the root of the classLibrary, but there may be more within
subfolders, if it makes sense to organize multiple projects within the same classLibrary. The manifest defines
certain information about the class library as a whole, and turns it into a "project". The manifest includes
information such as project versions, author information, changelogs, etc. The manifest.json file has a
specific format, which is described [Manifests|here]. One of the most useful features of the manifest is
the version number, and dependency information. The project should define what dependencies and versions
of dependencies are needed, but not where to find them. Meanwhile, as a system level configuration, the
system should define where to look for dependencies. This may be on the local system, or it may be in a
package manager. Regardless, at minimum, every classLibrary must have at least one manifest file within
the file structure that defines the organization name, project name, and project version. This ensures
that the dependency fulfillment mechanisms are always able to uniquely identify a project. A default
manifest.json file is created for you when running the system for the first time, but you must
change the values in it, if you intend on shipping your code, or re-using it in a more modular fashion.

=== Dynamic Classes ===
Dynamic classes are classes that are defined not through the class library, but dynamically
at runtime. These classes are defined more or less the same, but are not eligible for many
compiler checks. Things like ExhaustiveVisitors cannot be made to work with these classes,
they cannot be pre-compiled, and they cannot be used in the Dependency Injection system, among
other things. Having said all that, if you are ok with the downsides, these classes can be
defined anywhere, and then that file {{function|include}}'d (or dynamically loaded from other
sources, such as eval, or even the interpreter). Once loaded, they will work mostly just
as if they had been loaded at compile time. Existing, static code cannot reference the
classes, of course, as they would have already triggered a compile error for not being able
to find the class, but code that works generically with objects, or if the virtual class
extends/implements existing classes, this can be useful when doing dynamic things. Defining
a class outside of a class library, then causing it to be loaded will do this.

=== Naming Conventions ===

Class, field, and method names are case sensitive, and for consistency sake, should generally conform to
standard rules, though this is only a convention, and not enforced (except in ultra strict mode, which is
not a recommended mode for normal code). MethodScript follows these conventions, and you are strongly
encouraged to follow the same conventions in your own code, even if you never distribute it. For reference,
here are the names of various casing conventions:

 * snake_case
 * UPPER_SNAKE_CASE
 * lowerCamelCase
 * UpperCamelCase

{|
| Class Names
| In general, class names should be upper camel case. For classes that contain common acronymns or abbreviations,
such as "HTTP" or "URL", then the acronym should be fully capitalized, for instance, "HTTPUtility" or "URLUtils".
There are also exceptions for core internal classes, and classes that extend them (other than those that extend mixed),
which use snake case, but this list is fixed and finite: mixed, array, closure, and primitive. Classes which
extend one of these (other than mixed) should use snake case as well. The words in a class name should generally be
only adjectives and nouns.
|-
| Method Names
| Method names should use lower camel case, and the first word should generally be a verb. If the first word is anyways
an abbreviation or acronym, it should be fully lowercase, though this is discouraged, because acronyms are always nouns.
|-
| Field Names
| Fields should use lower camel case, except for constants, which should be upper snake case.
|}

<!--

TODO Consider if this is actually good.

=== Hot Swapping ===
Hot swapping is when elements of a class, or indeed, the class itself, are redefined at runtime.
The unit test framework in part makes use of this to implement mocks and spies, but this functionality
is available during normal execution as well. Hot swapping is a dangerous mechanism, however,
and so strict security checks are in place to ensure that the code doing the hot swapping is
properly authorized to do so. In general, the reflection mechanism
can be used to "hot swap" field values, so this is not covered in this section. Instead, we
focus on swapping method code and entire classes.

==== Permissions ====
Hot swapping must be allowed in the config settings of the system, and if disabled (which is the
default) the hot swapping mechanism is totally disabled during the non-test runtime. Even if
enabled, the manifest of the code must request hot swap permissions, and they must be granted
specifically to the package by the system administrator. (See the manifest section for details.)

If permission is not granted this will cause a SecurityException to be thrown at runtime.

==== Possible Errors ====
The system in general is somewhat fault tolerant, and will not shut down if a class definition
is changed in an incompatible way, though the code that was attempting to run will throw
a IncompatibleClassChangeError if the new ObjectDefinition was changed in an unrecoverable way. This
Error can be caught, but generally it should be taken as a fatal error, and the system should be
fully restarted, as it probably will begin to point to a larger cascade of errors. (This is a good
use case for returning <code>false</code> from {{function|set_uncaught_exception_handler}}.)

It may be possible to manually recover the system, by ensuring all instances of the old ObjectDefinition
are lost, and that no other code references invalid elements, but it's often times not worth it,
and rebooting the process is certainly the easiest solution.

What is an example of an incompatible change? If a method changes a previously public method to private,
code that was previously allowed to call this method will fail. This won't be caught by the compiler,
as the code that is accessing the new object will have already been compiled without errors.

There are a number of subclasses of the IncompatibleClassChangeError, but they all stem from the same
underlying problem - something that previously compiled is no longer valid.

==== Full Class Swaps ====
A full class swap is when the ObjectDefinition is fully replaced at runtime. Existing instances
of the class will retain the old ObjectDefinition, but new instances will get the new one. It is
impossible to access the old ObjectDefinition object, but internally, those instances will continue
on. Doing a full class swap does not restrict what can be done, fields may change, method definitions
may change, etc.

There are two ways to do a class swap, using the hotswap keyword in the class definition, and defining it in
a dynamic source, changing the source file.

Original A.ms:
<%CODE|
public class A {
	public void method() {
		msg("First class A");
	}
}
%>

Modified A.ms:
<%CODE|
public class A {
	public void method() {
		msg("Modified class A");
	}
}
%>

To "activate" the modified class, use the {{function|hotswap}} function, either from a previously defined
source, or from a dynamic source, such as a command, etc.

<%CODE|
A @old = new A();
@old->method(); // Original class A
// Now make the changes in the code, and then run
hotswap(A); // Recompiles A.ms
@old->method(); // Original class A, since it was instantiated before the hotswap
A @new = new A();
@new->method(); // Modified class A, since it was instantiated after the hotswap
%>

We can also use the hotswap keyword in a class definition. Defining a class twice is a compile error, so
if we are intentionally re-defining a class definition, we need to specially tell the compiler that, so
it doesn't think you just accidentally redefined it. Say we are running from the terminal:

<%CODE|
mscript> class A {} // Define the class originally
mscript> class A {} // Try to define it again
COMPILE ERROR: Class A already defined!
mscript> hotswap class A {} // This is allowed, and the definition is replaced!
%>

The hotswap class may come from somewhere besides the terminal of course, it can be included, eval'd, etc.
-->
{{LearningTrail}}
