Why can't I extend the static Math class? - actionscript-2

I'm working on an ActionScript 2 project that relied on some extensions to the Math class, usually done as such:
Math.sinD = function(angle) {
return Math.sin(angle*(Math.PI/180));
};
Allowing a caller to just write (for example)
Math.sinD(60);
However, when I try to compile with just the original line, I get the following error:
There is no property with the name "sinD".
Why isn't this working, and more importantly, how can I make it work again?

To my mind looks impossible.
Create static sinD method in separate class.

The 'problem' lies with ActionScript 2's static type checking. You can't directly modify a class because it checks that the property you're trying to access exists. However, you can do it if you bypass the type checking:
var Math2 = Math; // thing now holds a reference to the same Math class, but with no type set
// Add a new method
Math2.sinD = function(angle) {
return Math.sin(angle*(Math.PI/180));
};
// Now the Math has 'sinD' as a method
Or alternatively... (these both do the same thing)
Math['sinD'] = function(angle) {
return Math.sin(angle*(Math.PI/180));
};
However, this doesn't really help, because the static type checking is enforced at the calling places as well, so you can access any dynamically added methods.
Math.sinD(30) // This will not compile
Instead, you need to do:
var Math2 = Math;
Math2.sinD(30) // returns 0.5
Math['sinD'](30); // also returns 0.5
At which point, you may as well just create your own class rather than modifying the existing class.
Fortunately, for my case this means that there aren't any usages of these extensions (at least not statically typed usages), so I should be able to safely delete the extensions and not worry about it :)

Related

Property must be initialised even though type is defined in Kotlin

I am not sure Stack overflow will like this question. I am learning Kotlin and trying to declare a basic variable without any class.
This is the simplest example.
I now understand why the compiler won't accept it, says it must be initialised. But if I put it inside the main function, then it works fine.
I saw this tutorial on W3Schools and it says you dont have to initialise the variable if you declare its type? Well I have and it still is forcing me to initialise it
https://www.w3schools.com/kotlin/kotlin_variables.php
It's a simple variable in a file no class:
/**
* Number types:
* This is the most important, and we should be able to go over it quick.
* We start from the smallest to the biggest
*/
var byteEg: Byte;
Even inside a class it doesn't work:
class Variables{
var byteEg: Byte;
}
When I try latentinit it gives an exception: 'lateinit' modifier is not allowed on properties of primitive types
What W3Schools fails to mention is that it only holds true for variables that are not top level. So inside functions like
fun someFunction() {
var byteEg: Byte
}
if you want to do it with top level declarations you can mark it as lateinit like
lateinit var byteEg: Byte
The general principle is that everything must be initialised before it's used.*
(This is in contrast to languages like C, in which uninitialised values hold random data that could be impossible, invalid, or cause an error if used; and languages like Java, which initialise everything to 0/false/null if you don't specify.)
That can happen in the declaration itself; and that's often the best place. But it's not the only option.
Local variables can be declared without an initialiser, as long as the compiler can confirm that they always get set before they're used. If not, you get a compilation error when you try to use it:
fun main() {
var byteEg: Byte
println(byteEg) // ← error ‘Variable 'byteEg' must be initialized’
}
Similarly, class properties can be declared without an initialiser, as long as a constructor or init block always sets them.
In your example, you could set byteEg in a constructor:
class Variables2 {
var byteEg: Byte
constructor(b: Byte) {
byteEg = b
}
}
Or in an init block:
class Variables {
var byteEg: Byte
init {
byteEg = 1.toByte()
}
}
But it has to be set at some point during class initialisation. (The compiler is a little stricter about properties, because of the risk of them being accessed by other threads — which doesn't apply to local variables.)
Note that this includes vals as well as vars, as long as the compiler can confirm that they always get set exactly once before they're used. (Kotlin calls this ‘deferred assignment’; in Java, it's called a ‘blank final’.)
As another answer mentions, there's an exception to this for lateinit variables, but those are a bit specialised: they can't hold primitive types such as Byte, nor nullable types such as String?, and have to be var even if the value never changes once set. They also have a small performance overhead (having to check for initialisation at each access) — and of course if you make a coding error you get an UninitializedPropertyAccessException at some point during runtime instead of a nice compile-time error. lateinit is very useful for a few specific cases, such as dependency injection, but I wouldn't recommend them for anything else.
(* In fact, there are rare corner cases that let you see a property before it's been properly initialised, involving constructors calling overridden methods or properties. (In Kotlin/JVM, you get to see Java's 0/false/null; I don't know about other platforms.) This is why it's usually recommended not to call any of a class's non-final methods or properties from its constructors or init blocks.)

Dlang: why are constructors not inherieted?

Is there a way to not have to repeatidly write this(parent class args) {super(parent class args);} when the arguments are exactly the same?
The code:
class Parent {
string name;
this(string name) {
this.name = name;
}
}
class Child : Parent {
}
unittest {
auto child = new Child("a name");
assert(child.name == "a name");
}
https://run.dlang.io/is/YnnezI
Gives me the compilation error:
Error: class onlineapp.Child cannot implicitly generate a default constructor when base class onlineapp.Parent is missing a default constructor
Java and C# don't inherit constructors either (unless that's changed in the last few years - I don't think C++ allowed it either until c++11), and D follows the same reasoning so you can read more by looking up things about them.
Basically though the reason is that subclasses must have their own unique state - at very least stuff like the vtable even if you don't declare any of your own variables - and thus a unique constructor is required. Otherwise you can have uninitialized members.
And if inheritance went the whole way, since Object has a this(), new AnyClass(); would compile and lead to a lot of invalid objects. (In regular D, if you declare any ctor with arguments, it disables the automatically-generated zero arg one.)
Now, D could in theory do what C++ does and auto-generate other args too... it just doesn't. Probably mostly because that is a relatively new idea in C++ and D's class system is primarily based on Java's older system.
But all that said, let me show you a trick:
this(Args...)(auto ref Args args) { super(args); }
stick that in your subclass and you basically inherit all the parent's constructors in one go. If the super doesn't compile for the given args, neither will this, so it doesn't add random things either. You can overload that with more specific versions if needed too, so it is a reasonable little substitute for a built-in language feature.

Accepting managed struct in C++/CLI both with "hat" operator and without. What is the difference?

I've got a C++/CLI layer that I've been using successfully for a long time. But I just discovered something that makes me think I need to relearn some stuff.
When my C++/CLI functions receive an instance of any managed class, they use the "hat" operator ('^') and when they receive an instance of a managed struct, they do not. I thought this was how I was supposed to write it.
To illustrate as blandly as I can
using Point = System::Windows::Point;
public ref class CppCliClass
{
String^ ReturnText(String^ text) { return text; } // Hat operator for class
Point ReturnStruct(Point pt) { return pt; } // No hat operator for struct
};
I thought this was required. It certainly works. But just today I discovered that CancellationToken is a struct, not a class. My code accepts it with a hat. I thought it was a class when I wrote it. And this code works just fine. My cancellations are honored in the C++/CLI layer.
void DoSomethingWithCancellation(CancellationToken^ token)
{
// Code that uses the token. It works just fine
}
So apparently I can choose either method.
But then what is the difference between passing in a struct by value (as I've done with every other struct type I use, like Point) and by reference (as I'm doing with CancellationToken?). Is there a difference?
^ for reference types and without for value types matches C#, but C++/CLI does give you more flexibility:
Reference type without ^ is called "stack semantics" and automatically tries to call IDisposable::Dispose on the object at the end of the variable's lifetime. It's like a C# using block, except more user-friendly. In particular:
The syntax can be used whether the type implements IDisposable or not. In C#, you can only write a using block if the type can be proved, at compile time, to implement IDisposable. C++/CLI scoped resource management works fine in generic and polymorphic cases, where some of the objects do and some do not implement IDisposable.
The syntax can be used for class members, and automatically implements IDisposable on the containing class. C# using blocks only work on local scopes.
Value types used with ^ are boxed, but with the exact type tracked statically. You'll get errors if a boxed value of a different type is passed in.

Static methods in OOP

I've always known what static methods are by definition, but I've always avoided using them at school because I was afraid of what I didn't know.
I already understand that you can use it as a counter throughout your entire project.
Now that I am interning I want to know when exactly static methods are used. From my observation so far, static classes/methods are used when it contains a lot of functions that will be used in many different classes and itself doesn't contain too many critical local variables within the class where it is not necessary to create an instant of it.
So as an example, you can have a static class called Zip that zips and unzips files and provide it to many different classes for them to do whatever with it.
Am I right? Do I have the right idea? I'm pretty sure there are many ways to use it.
Static functions are helpful as they do not rely on an instantiated member of whatever class they are attached to.
Static functions can provide functionality related to an a particular class without requiring the programmer to first create an instance of that class.
See this comparison:
class Numbers
{
public int Add(int x, int y)
{
return x + y;
}
public static int AddNumbers(int x, int y)
{
return x + y;
}
}
class Main
{
//in this first case, we use the non-static version of the Add function
int z1 = (new Numbers()).Add(2, 4);
//in the second case, we use the static one
int z2 = Numbers.AddNumbers(3, 5);
}
Technically, answers above are correct.
But the examples are not correct from the OOP point of view.
For example you have a class like this:
class Zip
{
public static function zipFile($fileName)
{
//
}
public static function unzipFile($fileName)
{
//
}
}
The truth is that there is nothing object-oriented here. You just defined two functions which you need to call using the fancy syntax like Zip::zipFile($myFile) instead of just zipFile($myFile).
You don't create any objects here and the Zip class is only used as a namespace.
So in this case it is better to just define these functions outside of class, as regular functions. There are namespaces in php since version 5.3, you can use them if you want to group your functions.
With the OOP approach, your class would look like this:
class ZipArchive
{
private $_archiveFileName;
private $_files;
public function __construct($archiveFileName) {
$this->_archiveFileName = $archiveFileName;
$this->_files = [];
}
public function add($fileName)
{
$this->_files[] = $fileName;
return $this; // allows to chain calls
}
public function zip()
{
// zip the files into archive specified
// by $_archiveFileName
}
}
And then you can use it like this:
$archive = new ZipArchive('path/to/archive.zip');
$archive->add('file1')->add('file2')->zip();
What is more important, you can now use the zip functionality in an OOP way.
For example, you can have a base class Archive and sub-classes like ZipArchive, TarGzArchive, etc.
Now, you can create an instance of the specific sub-class and pass it to other code which will not even know if files are going to be zip-ped or tag.gz-ipped. For example:
if ($config['archive_type'] === 'targz') {
// use tar.gz if specified
$archive = new TarGzArchive($path);
} else {
// use zip by default
$archive = new ZipArchive($path);
}
$backup = new Backup($archive /*, other params*/);
$backup->run();
Now the $backup object will use the specified archive type. Internally it doesn't know and doesn't care how exactly files will be archived.
You can even have a CopyArchive class which will simply copy files to another location.
It is easy to do it this way because your archive support is written in OOP way. You have small object responsible for specific things, you create and combine them and get the result you want.
And if you just have a bunch of static methods instead of real class, you will be forced to write the procedural-style code.
So I would not recommend to use static methods to implement actual features of your application.
Static methods may be helpful to support logging, debugging, testing and similar things. Like if you want to count number of objects created, you can use class-level static counter, increment it in the constructor and you can have a static method which reads the counter and prints it or writes to the log file.
Yes, static classes are used for problems that require stateless computation. Such as adding two numbers. Zipping a file. Etc.
If your class requires state, where you need to store connections or other longer living entities, then you wouldn't use static.
AFAIK. Static methods does not depends on a class instance. Just that.
As an example:
If you have an single thread program that will have only ONE database connection and will do several queries against the database it will be better to implement it as a static class (note that I specified that you will not connect, ever to several databases or have several threads).
So you will not need to create several connection objects, because you already know that you will only use one. And you will not need to create several objects. Singletons in this scenario are, also, an option.
There are other examples.
If you create an class to convert values.
class Convert{
static std::string fromIntToString(int value);
}
This way you will not need to create the class convert every time you need to convert from integer to an string.
std::string value = Convert::fromIntToString(10).
If you haven't done that you would need to instantiate this class several times through your program.
I know that you can find several other examples. It is up to you and your scenario to decide when you are going to do that.

Should private functions modify field variable, or use a return value?

I'm often running into the same trail of thought when I'm creating private methods, which application is to modify (usually initialize) an existing variable in scope of the class.
I can't decide which of the following two methods I prefer.
Lets say we have a class Test with a field variable x. Let it be an integer. How do you usually modify / initialize x ?
a) Modifying the field directly
private void initX(){
// Do something to determine x. Here its very simple.
x = 60;
}
b) Using a return value
private int initX(){
// Do something to determine x. Here its very simple.
return 60;
}
And in the constructor:
public Test(){
// a)
initX();
// b)
x = initX();
}
I like that its clear in b) which variable we are dealing with. But on the other hand, a) seems sufficient most of the time - the function name implies perfectly well what we are doing!
Which one do you prefer and why?
Thank for your answers guys! I'll make this a community wiki as I realize that there is no correct answer to this.
I usually prefer b), only I pick a different name, like computeX() in this case. A few reasons for why:
if I declare computeX() as protected, there is a simple way for a subclass to influent how it works, yet x itself can remain a private field;
I like to declare fields final if that's what they are; in this case a) is not an option since initialization has to happen in compiler (this is Java-specific, but your examples all look Java as well).
That said, I don't have a strong preference between the two methods. For instance, if I need to initialize several related fields at once, I will usually pick option a). That, though, only if I cannot or don't want for some reason, to initialize directly in constructor.
For initialization I prefer constructor initialization if it's possible,
public Test():x(val){...}, or write initialization code in the constructor body. Constructor is the best place to initialize all the fields (actually, it is the purpose of constructor). I'd use private initX() approach only if initialization code for X is too long (just for readability) and call this function from constructor. private int initX() in my opinion has nothing to do with initialization(unless you implement lazy initialization,but in this case it should return &int or const &int) , it is an accessor.
I would prefer option b), because you can make it a const function in languages that support it.
With option a), there is a temptation for new, lazy or just time-stressed developers to start adding little extra tasks into the initX method, instead of creating a new one.
Also, in b), you can remove initX() from the class definition, so consumers of the object don't even have to know it's there. For example, in C++.
In the header:
class Test {
private: int X;
public: Test();
...
}
In the CPP file:
static int initX() { return 60; }
Test::Test() {
X = initX();
}
Removing the init functions from the header file simplifies the class for the people that have to use it.
Neither?
I prefer to initialize in the constructor and only extract out an initialization method if I need a lot of fields initialized and/or need the ability to re-initialize at another point in the life time of an instance (without going through a destruct/construct).
More importantly, what does 60 mean?
If it is a meaningful value, make it a const with a meaningful name: NUMBER_OF_XXXXX, MINUTES_PER_HOUR, FIVE_DOZEN_APPLES, SPEED_LIMIT, ... regardless of how and where you subsequently use it (constructor, init method or getter function).
Making it a named constant makes the value re-useable in and of itself. And using a const is much more "findable", especially for more ubiquitous values (like 1 or -1) then using the actual value.
Only when you want to tie this const value to a specific class would it make sense to me to create a class const or var, or - it the language does not support those - a getter class function.
Another reason to make it a (virtual) getter function would be if descendant classes need the ability to start with a different initial value.
Edit (in response to comments):
For initializations that involve complex calculations I would also extract out a method to do the calculation. The choice of making that method a procedure that directly modifies the field value (a) or a function that returns the value it should be given (b), would be driven by the question whether or not the calculation would be needed at other times than "just the constructor".
If only needed at initialization in the constructor, I would prefer method (a).
If the calculation needs to be done at other times as well, I would opt for method (b) as it also makes it possible to assign the outcome to some other field or local variable and so can be used by descendants or other users of the class without affecting the inner state of the instance.
Actually only a) method behaves as expected (by analyzing method name). Method b) should be named 'return60' in your example or 'getXValue' in some more complicated one.
Both options are correct in my opinion. It all depeneds what was your intention when certain design was choosen. If your method has to do initialization only I would prefer a) beacuse it is simplier. In case x value is also used for something else somewhere in logic using b) option might lead to more consistent code.
You should also always write method names clearly and make those names corresponding with actual logic. (in this case method b) has confusing name).
#Frederik, if you use option b) and you have a LOT of field variables, the constructor will become a quite unwieldy block of code. Sometimes you just can't help but have lots and lots of member variables in a class (example: it's a domain object and it's data comes straight from a very wide table in the database). The most pragmatic approach would be to modularize the code as you need to.