When is an iterator implementation a better practice than offering indexing? When it is better, why?
I am assuming that I am the implementer of a class that can offer either and a choice needs to be made.
Because most collections are iterable, but few collections are indexable (e.g. hashtables).
Using iterators allows you to create code that doesn't care about the type of each collection.
Encapsulation: with an iterator you do not have to know what the valid indices are.
Related
Are functional collection types available in Kotlin? Something like immutable Queue or Stack in Scala?
If not, is there any good library out there which provides functional collection types to Kotlin (based on Kotlin's Any) ?
Arrow Library
Λrrow is a library for Typed Functional Programming in Kotlin.
https://arrow-kt.io/
val myarray: Array<out Any> = arrayOfNull(100)
https://kotlinlang.org/docs/reference/basic-types.html#arrays
Assigning <Any> to <String> is wrong, though the opposite is not.
So solution wasn't actually that hard. A persistent Stack can be easily implememted using a linked list which results with O(1) complexity for both push() and pop(). As for the Queue it seems there is no much choice but to accept O(n) complexity of either enqueue or dequeue. In such case I can simply use one stack as an input (enqueue) and another one as an optput (dequeue). It will be just a matter of reversing the input stack and swapping with the output when the output gets empty - probably the best idea is to do in on the dequeue().
This may be not the most elegant approach, I may need to re-think this for larger number of elements (maybe add a queue/tree of Stacks to limit reversing) but for my current needs this should be enough. Thanks to all of you for your suggestions.
Persistent Stack implementation -
https://github.com/nekomatic/types/blob/graph/src/main/kotlin/com/nekomatic/types/Stack.kt
Persistent Queue implementation - https://github.com/nekomatic/types/blob/graph/src/main/kotlin/com/nekomatic/types/Queue.kt
In the book Learning Rust With Entirely Too Many Linked Lists, in the implementation of IntoIter, why is List wrapped in a tuple struct? Instead, Iterator could have been implemented for a List.
Yes, technically Iterator could be implemented for List in this case. This isn't generally true, since iterators might need different state that's not in the base container (e.g. a Vec iterator might need to store an index to the next item to iterate efficiently).
One reason is that if the implementation changes in future and the List iterator would be better with extra state, it's possible to change the iterator struct without changing any callers.
Another reason is that in Rust it's common to use types to narrow interfaces to reduce the chance of errors. If you implement Iterator directly (and presumably IntoIterator to return self), then that leaves the possibility for the user to call other List methods during iteration, which is probably wrong. Instead the iterator is a separate type, meaning that there's no possibility of someone pushing items on during iteration. (Note that in a for loop it'd be hard to do this anyway due to the borrowing/move rules, but the general point is still there).
What are the differences between these two? Why would you pick one over the other, is it just personal preference, or is there an actual reason behind why you would use either a built-in function or whatever .length is.
I think using *.length over *.length() or len(*) is kind of a historical artifact, which was probably done to make getting the length of an array as fast as possible. Arrays after all, are a very basic data structure in many languages, and getting the length of one is an extremely common operation. And accessing a property is much faster than calling a method.
Nowadays a compiler could probably optimize that kind of thing out, but back then I think there was a pull towards ease-of-implementation which guided many languages to simply have *.length as a property.
However, in any OOP language at least, it's more consistent to have *.length(), because while arrays have immutable lengths, and can afford to have *.length exposed as a constant value, other data structures which you can add or remove values would not be able to do this.
I have some measurement object instances from a series of test runs stored in a test collection object. I also have some logic that can compare two test result object instances and tell me if they are "close enough".
Where should this logic be placed?
On the object as a method? Like: instance.approximately_equal(other)
On the object's class as a class/static method? class.approximately_equal(a,b)
On the collection object as a method? collection.approximately_equal(a,b)
What is the correct OO design for this?
(I ask, since although #1 would seem the correct solution, I'd never be asking if some one instance is approximately_equal to a different instance. Only if "some group of objects" are equal to each other. It got me thinking...)
Thanks
The object oriented design books I have read suggest putting cross class functionality into service provider objects. This will decouple the two objects and reduce complexity, but may be overkill if your project is small.
I would use option 1 (instance method) since that enables you to refine the comparison logic in derived classes (if needed).
I've found #3 is the least obtrusive and leads to less bloated code, because it tends to force you to make those methods as flexible/reusable as possible. For example, in C++, you'd potentially just use operator overloading to handle it; if you have a utility class (or, if you plan on extending a native data type), the net effect is the same, just with a different presentation.
I have a strong feeling that I do not know what pattern or particular language technique use in this situation.
So, the question itself is how to manage the growing parameter list in class hierarchy in language that has OOP support? I mean if for root class in the hierarchy you have, let's say 3 or 4 parameters, then in it's derived class you need to call base constructor and pass additional parameters for derived part of the object, and so forth... Parameter lists become enormous even if you have depth of inheritance more than two.
I`m pretty sure that many of SOwers faced this problem. And I am interested in ways how to solve it. Many thanks in advance.
Constructors with long parameter lists is an indication that your class is trying to do too much. One approach to resolving that problem is to break it apart, and use a "coordinator" class to manage the pieces. Subclasses that have constructor parameter lists that differ significantly from their superclass is another example of a class doing too much. If a subclass truly is-a superclass, then it shouldn't require significantly more data to do its job.
That said, there are occasional cases where a class needs to work on a large number of related objects. In this situation, I would create a new object to hold the related parameters.
Alternatives:
Use setter injection instead of constructor injection
Encapsulate the parameters in a separate container class, and pass that between constructors instead.
Don't use constructors to initialize the whole object at once. Only have it initialize those things which (1) are absolutely required for the existence of the object and (2) which must be done immediately at its creation. This will dramatically reduce the number of parameters you have to pass (likely to zero).
For a typical hierarchy like SalariedEmployee >> Employee >> Person you will have getters and setters to retrieve and change the various properties of the object.
Seeing the code would help me suggest a solution..
However long parameter lists are a code-smell, so I'd take a careful look at the design which requires this. The suggested refactorings to counter this are
Introduce Parameter Object
Preserve Whole Object
However if you find that you absolutely need this and a long inheritance chain, consider using a hash / property bag like object as the sole parameter
public MyClass(PropertyBag configSettings)
{
// each class extracts properties it needs and applies them
m_Setting1 = configSettings["Setting1"];
}
Possibilities:
Perhaps your class(es) are doing too much if they require so much state to be provided up-front? Aim to adhere to the Single Responsibility Principle.
Perhaps some of these parameters should logically exist in a value object of their own that is itself passed in as a parameter?
For classes whose construction really is complex, consider using the builder or factory pattern to instantiate these objects in a readable way - unlike method names, constructor parameters lack the ability to self document.
Another tip: Keep your class hierarchy shallow and prefer composition to inheritence. That way your constructor parameter list will remain short.