What are some examples where dynamic typing is preferred to static typing? - typing

Let's take a simple function that increments an integer:
Static typing:
function incrementNumber(int n) {
n = n + 1;
}
Dynamic typing:
function incrementNumber(n) {
if (type of n != int) {
throw Error;
}
n = n + 1;
}
These achieve the same thing, but the dynamic approach is way uglier and longer because of the "type checking" that's required.
I've seen a lot of programmers use this approach and it makes me wonder what exactly are the benefits of a dynamically typed language, since most functions will need a parameter check like this?
Do you have any examples where dynamic typing works (or looks) better than static typing?

If you are gonna check the data type before doing anything, it has no benefits.
Dynamic typing only makes sense when you know that a function exists or an operator can be applied but the compiler don't know it until runtime. Or to create objects without definig its properties.

Related

Check if generic is an array with inline function

How can I check if a Generic is an Array using an inline function?
I tried with the following code:
class Mediator {
inline fun <reified C> mediate(string: String): Container<C> {
if (C::class == Int::class) {
//It works
}
else if (C::class == Array::class) {
//It doesn't work!
}
throw IllegalStateException("Yopta")
}
}
But it doesn't work. Maybe because it can be Array<Whatever>?
How can I do it?
Contrary to collections where for example List<String> and List<Int> are internally represented by the same class List, in arrays the type parameter is a part of the type itself. That means Array<String> and Array<Int> are internally represented as different types and as far as I know, they don't have a common super type.
I don't know a pure Kotlin solution to check if a class is an array. It seems to me like an overlook in the design of the reflection API. If you don't mind using the Java reflection, you can do it like this:
else if (C::class.java.isArray) {
Update
There is one interesting fact here. In the Kotlin type system we could consider Array<out Any?> to be a supertype of all arrays. For example, we can upcast to it without an explicit cast operator:
val intArray = arrayOf(1, 2, 3)
val arr: Array<out Any?> = intArray
However, for the reflection API these two types are entirely different:
// false
println(Array<Int>::class.isSubclassOf(Array<out Any?>::class))
I assume this is due to how arrays where implemented in Java. I'm not even sure if it would be technically possible to return true in the code above. Still, it is concerning it provides a different result than the type system at a compile time and it doesn't even produce a warning.
Actual answer that solves the issue here.
Since broot added an actual answer I'll just leave this here as a note as to how we can see that he is right basically.
If we make the call like this:
Mediator().mediate<Array<Int>>("")
Adding a simple check inside the function like this makes it a bit confusing as to why they are not equal.
println(C::class) //class Kotlin.Array
println(Array:class) //class Kotlin.Array
But doing the same for the underlying java class shows that they are not really the same object.
println(C::class.java) //class [Ljava.lang.Integer
println(Array:class.java) //class [Ljava.lang.Object
So changing the statement to:
if(C::class.java == Array<Int>::class.java)
Will make the example work ... for Int only. All other "infinite" possibilities will have to be added manually. Not an issue if you just want to check Array<X> only, but definitely not generic.

is it possible to write a method to sort an array of objects with respect to a specific field?

i mean is it possible to have a method that gets as its parameters an array of objects and another parameter which indicates which field of the objects we are using to sort the array ?
for example if the objects are contacts if we call sort(contacts , name) it would sort them with respect to name. if we call sort(contacts , number) it sorts them according to their numbers.
maybe by sending an String of the field we want !! something like :
class sorting {
public static bubble_sort(Object[] array , String field){
for(int i =0; i<array.length ; i++){
if(array[i].field > array[i+1].field)
swap(array ,i ,i+1);
}
}
(preferably in java) (and please include examples of the solutions you give !)
Assuming this is Java: yes, it is possible. You can use reflection to get the field type and value and then compare them. It would not be a good idea. Much better to use Comparator with the existing sort method.
A method that would work in pretty much any language is to pass in some kind of function object.
class sorting {
public static bubble_sort(Object[] array, FunctionObject ordering) {
for(int i =0; i<array.length ; i++){
if(ordering(array[i+1], array[i]))
swap(array ,i ,i+1);
}
};
different languages are going to have different syntaxes for such a function object -- what its type is, etc -- but pretty much every language is going to have some way to do it.
Generally the best signature for it is one that takes two different objects, and returns true if the left one is less than the right one.
Similarly, different languages are going to have different ways of invoking a function object. Some may require ordering.Invoke( array[i+1], array[i] ).
In that function object, compare the field in question. If the language/objects have reflection, you can sometimes do this via field name directly.
As this pattern is very useful, languages tend to make it easier as they mature. So the most recent version of your language may have a syntax to create such objects with far less syntax, and invoke them with less syntax as well.

Variable arraylength and template input in C++11

I've seen tons of questions about this. Some have answers, some don't, but none seem to work for me. I have this program (somebody else wrote it) that I wish to use. However there are two problems in the constructor:
template<unsigned N>
class Enumeration {
public:
Enumeration(const array<vector<pair<unsigned char, double>>, N>& pDistribution);
}
The problem with this is that I wish to run this class on user defined input. This input decides the value of N. But because of the 1. const requirement on N for arrays, seeing as I need to construct the array that I will use in the constructor and 2. the const requirement N for templates, I am in quite a pickle.
I tried double pointers, using a proxing class or constexpr voids, non seem to work (depending on whether I did it correctly, I'm reletively new in C++).
My last resort is to do something really ugly with a many-cases switch-statement, but I was hoping someone here can help me out. Preferably without using an extension for the compiler.
The class you have shown does not support N being determined at run-time. It is intended for a different purpose, for when N can be determined at compile time.
Trying to allow N be determined at run-time in the above case is almost certainly a bad idea.
Instead, writing a variant of your type such that the outermost container is not an array but rather a vector would be the general approach required to make the size of the outermost container be determined at run time.
This will involve rewriting most of the class.
class Enumeration_Runtime {
public:
Enumeration_Runtime(const std::vector<std::vector<std::pair<unsigned char, double>>>& pDistribution);
};
the const&ness of the parameter might be best turned into a pass-by-value, but I am unsure.
There is no easy route here, because the person who wrote Enumeration<N> wrote it to not allow N to vary at run time.

What is the best way to break a very big C function with around 50 local variables into smaller functions?

I have a 3500 lines long C function written by someone else that i need to break it apart without causing any regression. Since it is in C, the main problem i face is maintaining the state of the variables. For example if i break a small part of the code into another function, i will need to pass 10 arguments. Some of them will actually change inside the code of the new function. So effectively i will need to pass a pointer to them. It becomes very messy. Is there is better way of dealing with such refactoring? Any "best practice"?
Unit testing. Extract small portions of the code that depend on 3 variables or less (1 variable best) and test the hell out of it. Replace that code in original function with a call to new function.
Each function should do one thing that is easy to figure out from examining the code.
Instead of passing 10 variables around, put them into a structure and pass that around.
In my opinion, the best thing you can do is to thoroughly study that function, and fully understand its internals. It is more than probable that this function has a lot of anitpatterns inside it, so I'd not try to refactor it: once I knew how it works (which I understand this can suppose a lot of time) I'd throw it away and rewrite the equivalent smaller functions needed, from scratch.
Pack the local variables that are shared between multiple of the sub-functions into a struct and hand the struct around?
Are you stuck with C? I have sometimes converted such functions into a C++ class, where I convert the some (or all) local variables into member variables. Once this step has been done, you can easily break out part of the code into methods that work on the member variables.
In practice this means that a function like:
... do_xxx(...)
{
.. some thousand lines of code...
}
can be converted into:
class xxx_handler
{
public:
xxx_handler(...);
... run(...)
{
part1();
part2();
part3();
return ...;
}
private:
// Member variables goes here.
};
// New replacement function.
... do_xxx(...)
{
xxx_handler handler(...);
return handler.run(...);
}
One thing to start with, as a first step to taking out parts of the function as independent functions, is to move "function global" temp variables to be in tighter scope, something like:
int temp;
temp = 5;
while(temp > 0) {...}
...
temp = open(...);
if (temp < 0) {...}
converted to
{
int temp = 5;
while(temp > 0) {...}
}
...
{
int temp = open(...);
if (temp < 0) {...}
}
After that, it's easier to move each {} block into a separate function, which does one well-defined thing.
But then, most important guideline after having unit tests:
Use version control which supports "cherry-picking" (like git). Commit often, basically whenever it compiles after refactoring something, then commit again (or amend the previous commit if you don't want to have the first commit version around) when it actually works. Learn to use version control's diff tool, and cherry-picking, when you need to roll back after breaking something.

C functions overusing parameters?

I have legacy C code base at work and I find a lot of function implementations in the style below.
char *DoStuff(char *inPtr, char *outPtr, char *error, long *amount)
{
*error = 0;
*amount = 0;
// Read bytes from inPtr and decode them as a long storing in amount
// before returning as a formatted string in outPtr.
return (outPtr);
}
Using DoStuff:
myOutPtr = DoStuff(myInPtr, myOutPtr, myError, &myAmount);
I find that pretty obtuse and when I need to implement a similar function I end up doing:
long NewDoStuff(char *inPtr, char *error)
{
long amount = 0;
*error = 0;
// Read bytes from inPtr and decode them as a long storing in amount.
return amount;
}
Using NewDoStuff:
myAmount = NewDoStuff(myInPtr, myError);
myOutPtr += sprintf (myOutPtr, "%d", myAmount);
I can't help but wondering if there is something I'm missing with the top example, is there a good reason to use that type of approach?
One advantage is that if you have many, many calls to these functions in your code, it will quickly become tedious to have to repeat the sprintf calls over and over again.
Also, returning the out pointer makes it possible for you to do things like:
DoOtherStuff(DoStuff(myInPtr, myOutPtr, myError, &myAmount), &myOther);
With your new approach, the equivalent code is quite a lot more verbose:
myAmount = DoNewStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myAmount);
myOther = DoOtherStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myOther);
It is the C standard library style. The return value is there to aid chaining of function calls.
Also, DoStuff is cleaner IMO. And you really should be using snprintf. And a change in the internals of buffer management do not affect your code. However, this is no longer true with NewDoStuff.
The code you presented is a little unclear (for example, why are you adding myOutPtr with the results of the sprintf.
However, in general what it seems that you're essentially describing is the breakdown of one function that does two things into a function that does one thing and a code that does something else (the concatenation).
Separating responsibilities into two functions is a good idea. However, you would want to have a separate function for this concatenation and formatting, it's really not clear.
In addition, every time you break a function call into multiple calls, you are creating code replication. Code replication is never a good idea, so you would need a function to do that, and you will end up (this being C) with something that looks like your original DoStuff.
So I am not sure that there is much you can do about this. One of the limitations of non-OOP languages is that you have to send huge amounts of parameters (unless you used structs). You might not be able to avoid the giant interface.
If you wind up having to do the sprintf call after every call to NewDoStuff, then you are repeating yourself (and therefore violating the DRY principle). When you realize that you need to format it differently you will need to change it in every location instead of just the one.
As a rule of thumb, if the interface to one of my functions exceeds 110 columns, I look strongly at using a structure (and if I'm taking the best approach). What I don't (ever) want to do is take a function that does 5 things and break it into 5 functions, unless some functionality within the function is not only useful, but needed on its own.
I would favor the first function, but I'm also quite accustomed to the standard C style.

Resources