What is the purpose or possible usages of value class in Kotlin - kotlin

I found the new value class been
I found the purpose is like :
value class adds attribute to a variable and constraint it’s usage.
I was wondering what is some practical usage of value class.

Well, as stated in the documentation Kotlin Inline classes
Sometimes it is necessary for business logic to create a wrapper around some type. However, it introduces runtime overhead due to additional heap allocations. Moreover, if the wrapped type is primitive, the performance hit is terrible, because primitive types are usually heavily optimized by the runtime, while their wrappers don't get any special treatment.
To solve such issues, Kotlin introduces a special kind of class called an inline class. Inline classes are a subset of value-based classes. They don't have an identity and can only hold values.

A value class can be helpful when, for example, you want to be clear about what unit a certain value uses: does a function expect me to pass my value in meters per second or kilometers per hour? What about miles per hour? You could add documentation on what unit the function expects, but that still would be error-prone. Value classes force developers to use the correct units.
You can also use value classes to provide clear means for other devs on your project on doing operations with your data, for example converting from one unit to another.
Value classes also are not assignment-compatible, so they are treated like actual new class declarations: When a function expects a value class of an integer, you still have to pass an instance of your value class - an integer won't work. With type aliases, you could still accidentally use the underlying type, and thus introduce expensive errors.
In other words, if you simply want things to be easier to read, you can just use type aliases. If you need things to be strict and safe in some way, you probably want to use value classes instead.

Related

What are the in and out positions in Kotlin Generics?

I want to start with what I know, or at least I think I know, so what I'm asking would be more clear.
First of all, I know that you can declare a variable of a supertype and assign an object of a subtype to take advantage of polymorphism with Inheritence and Interfaces.
I know that generics provide type safety because the type parameters are invariant by definition, so where A is a subtype of B, Foo<A> is not necessarily a subtype of Foo<B>, and may not be used in place depending on mutability of the object. With this, possible exceptions that could arise at runtime due to dynamic dispatching can be caught in compile time.
They also help to define a generic logic for different types: Like in Lists where you have collections of type A objects, but it doesn't change the implementation for type B objects.
Also, I understood why MutableList<String> doesn't count as the subtype of MutableList<Any> because that could result in cases where you create a variable with type MutableList<Any> that holds a reference to a MutableList<String> object, and add an Int element to a List of Strings, which is obviously a problem.
I also understood why List version of the previous example works because Lists are immutable so you can't make any modification to the object that could result in type mismatches.
Lastly, I know that type parameters with in can only be used as function parameters, being consumed, and the ones with out can be used as the function return types, being produced.
Now to the part what I don't understand:
I didn't quite understand what the words consumer and producer actually means in terms of in and out. What does it mean for a type to be in consumed or produced position? Does that mean the object with that type can only be read or write only? Does that have anything to do with the object at all?
What would be the behaviour of the object if, let's say, we don't define it using in or out, or, opposite, we define it using in or out, not talking about the subtype-supertype relationship that I explained above.
I spend the last few days looking at different explanations of this, but I found the lack of examples a big problem, especially because that's how I usually learn.
I can use these concepts in code, but the lack of underlying knowledge or the logic greatly disturbs me, so please, if you decide to take the time to write an explanation, provide it with examples and counter examples of why or how a certain idea works.
Just one correction to your first bullet points: List is not immutable; it is read-only. A List could be an up-cast mutable implementation and some other object that references it could be mutating it.
Producer means the generic type appears as a return type in any functions or properties of the object. You can get T’s out of a List, for instance.
Consumer means the generic type appears as a parameter of any functions or as the type of any var properties of the object. You can put T’s into a MutableList, for example.
Since List produces but doesn’t consume (it doesn’t have any functions with T as a parameter), its type is marked as producing-only, aka covariant, aka out right at the declaration site so its type can always be assumed to be out wherever it’s used even if the out keyword is not used.
Since the List type is always covariant out, any List can be safely upcast to a List where the type is a supertype of the originating type. A List<String> can be cast to List<CharSequence> because any item you get out of it (anything it produces) is going to be a String, and therefore also qualifies as the supertype CharSequence.
The reverse logic would apply for something that is purely a consumer with the type marked in, but it’s harder to come up with a simple example where you would actually have a useful object like this.
A MutableList both produces and consumes, so it is invariant by default, but since it is also a List, a MutableList<String> could be safely cast to a List<CharSequence>. If you have a reference to the List<CharSequence>, you can get CharSequences out of it. The underlying object might continue to have new Strings put into it from the original reference.

Type pool or class of constants?

What is the difference between Type-pool and creating a class for constants?
What is better?
My question is for a large group of constants and to be accessible to other groups.
Thank you
EDIT - Thank you for the answers and I will improve my question. I need something to store constants and I will use them on programs or other classes. Basically, I wanted to know if it is better to use a type-pool or a class with constants (only). I can have more than one class or type-pool.
The documentation mentions this:
Since it is possible to also define data types and constants in the public visibility section of global classes, type groups are obsolete and should no longer be created. Existing type groups can still be used.
A sensibly named interface with the constants you desire is the way to go. An additional benefit is that ABAP OO enforces some more rules.
Agree with #petul's answer, except for one detail: I'd recommend creating one enumeration-like class per logical group of constants, instead of collecting constants in interfaces.
Consider using the new enum language feature for specifying the constant values.
Interfaces can be accidentally "implemented", which doesn't make sense here. Classes can prevent this with final.
Making one class per logical group simplifies finding the constants with IDE features such as Ctrl+Shift+A search in the ABAP Development Tools. Constants that are randomly thrown together into interfaces are hard to find later on.
Classes allow adding enumeration-like helper methods like converters, existence checks, numbering all values.
Classes also allow adding unit tests, such as ensuring that the constant collection is still in sync with the fixed values of an underlying domain.

Decoupling a class which is used by the lots of subclasses

Hi I have a situation like that;
I have different items in my design and all these items has some specific effect on the Character. There is an apply function in every item so it can use Character object and change its functionalities. But what if I change the Character function, I would have to change all the Item classes in accordance to that.
How can I decouple Item and Character efficiently?
The language I am going to use is C++ and I don't know the other variables and functions inside the Item and Character classes. I just want to decouple them.
You could introduce an interface (abstract class in C++) that Character would inherit. Let's call it ItemUser. The Item#apply signature would be changed so that it would take an object of ItemUser instead of Character. Now you are able to change the implementation of Character freely as long as it respects the ItemUser contract.
Check Decorator design pattern, it seems that this design pattern is what you are looking for. Link :Decorator design pattern
As per what I have understood from reading your question is : You have multiple Item classes each having a effect associated. Effect corressponding to the type of Item object is applied on another entity which is Character. Now your issue is whenever there is a change in Character class your Item classes also needs to change and you want a cleaner way to avoid this.
A good way to handle change is to define the well defined Contract which is less prone to change. For example if we have a functionality to add two integers and later we may have the changes such that we require to add two floating point numbers and later we may need to replace add operation with multiplication. In such a case you can define an abstraction Compute (INum num1, INum num2) : INum as return type. Here INum is an abstraction for type and Compute is abstraction for behaviour of function. Actual implementation defines INum and Compute. Now code using our code only depends on the abstractions and we can freely modify the operation and actual type without affecting the user code.
While implementing the contract you can modify the internal implementation without affecting the outside code using the contract.
You can define an abstract class ICharacter. For certain attributes whose type can change in future you can use Templates and generics or simply create interface for the attribute type as well and let the concrete type implement the interfaces. Refer all your fields with interfaces. Let ICharacter define public abstract methods with parameters of type Interfaces and return type also as Interfaces.
Let Item class use ICharacter and When you need to apply effect as per item class just use the constant abstract functions defined. Your Character internal modifications now can change without affecting the Item class.

Can we use tracking handle to the value class?

Using c++ CLI, is it recommended not to use tracking handle for value class?
for example
value class Point {
};
Point p;
or Point ^p;
C++/CLI permits that syntax, unfortunately, it cannot be expressed directly in other managed languages. You end up with the value getting boxed in an object and stored on the GC heap. Every assignment will box, reading the value unboxes it again. That's quite expensive and 99.9% of the time is the wrong thing to do. The point of value types is to make your code fast, avoiding the extra indirection through an object reference and taking advantage of processor registers. A value type value like Point fits in two registers.
By declaring it as a handle, you get the disadvantage of a ref class but add the expense of having to unbox the value every time you retrieve a member of the value type. It therefore makes no sense to do this at all, if you need a Point class with reference type semantics then just declare a ref class Point and entirely avoid the un/boxing cost. C++/CLI has a few design flaws, induced by trying make it match native C++ semantics. This is one of them.
So no, this is not recommended.

In what cases should public fields be used instead of properties? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Public Data members vs Getters, Setters
In what cases should public fields be used, instead of properties or getter and setter methods (where there is no support for properties)? Where exactly is their use recommended, and why, or, if it is not, why are they still allowed as a language feature? After all, they break the Object-Oriented principle of encapsulation where getters and setters are allowed and encouraged.
If you have a constant that needs to be public, you might as well make it a public field instead of creating a getter property for it.
Apart from that, I don't see a need, as far as good OOP principles are concerned.
They are there and allowed because sometimes you need the flexibility.
That's hard to tell, but in my opinion public fields are only valid when using structs.
struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
};
But different people have different thoughts about:
http://kristofverbiest.blogspot.com/2007/02/public-fields-and-properties-are-not.html
http://blogs.msdn.com/b/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx
http://www.markhneedham.com/blog/2009/02/04/c-public-fields-vs-automatic-properties/
If your compiler does not optimize getter and setter invocations, the access to your properties might be more expensive than reading and writing fields (call stack). That might be relevant if you perform many, many invocations.
But, to be honest, I know no language where this is true. At least in both .NET and Java this is optimized well.
From a design point of view I know no case where using fields is recommended...
Cheers
Matthias
Let's first look at the question why we need accessors (getters/setters)? You need them to be able to override the behaviour when assigning a new value/reading a value. You might want to add caching or return a calculated value instead of a property.
Your question can now be formed as do I always want this behaviour? I can think of cases where this is not useful at all: structures (what were structs in C). Passing a parameter object or a class wrapping multiple values to be inserted into a Collection are cases where one actually does not need accessors: The object is merely a container for variables.
There is one single reason(*) why to use get instead of public field: lazy evaluation. I.e. the value you want may be stored in a database, or may be long to compute, and don't want your program to initialize it at startup, but only when needed.
There is one single reason(*) why to use set instead of public field: other fields modifications. I.e. you change the value of other fields when you the value of the target field changes.
Forcing to use get and set on every field is in contradiction with the YAGNI principle.
If you want to expose the value of a field from an object, then expose it! It is completely pointless to create an object with four independent fields and mandating that all of them uses get/set or properties access.
*: Other reasons such as possible data type change are pointless. In fact, wherever you use a = o.get_value() instead of a = o.value, if you change the type returned by get_value() you have to change at every use, just as if you would have changed the type of value.
The main reason is nothing to do with OOP encapsulation (though people often say it is), and everything to do with versioning.
Indeed from the OOP position one could argue that fields are better than "blind" properties, as a lack of encapsulation is clearer than something that pretends to encapsulation and then blows it away. If encapsulation is important, then it should be good to see when it isn't there.
A property called Foo will not be treated the same from the outside as a public field called Foo. In some languages this is explicit (the language doesn't directly support properties, so you've got a getFoo and a setFoo) and in some it is implicit (C# and VB.NET directly support properties, but they are not binary-compatible with fields and code compiled to use a field will break if it's changed to a property, and vice-versa).
If your Foo just does a "blind" set and write of an underlying field, then there is currently no encapsulation advantage to this over exposing the field.
However, if there is a later requirement to take advantage of encapsulation to prevent invalid values (you should always prevent invalid values, but maybe you didn't realise some where invalid when you first wrote the class, or maybe "valid" has changed with a scope change), to wrap memoised evaluation, to trigger other changes in the object, to trigger an on-change event, to prevent expensive needless equivalent sets, and so on, then you can't make that change without breaking running code.
If the class is internal to the component in question, this isn't a concern, and I'd say use fields if fields read sensibly under the general YAGNI principle. However, YAGNI doesn't play quite so well across component boundaries (if I did need my component to work today, I certainly am probably going to need that it works tomorrow after you've changed your component that mine depends on), so it can make sense to pre-emptively use properties.