Two possible types for a property - oop

I have a class that is a leaf in the composite pattern. This class has a property that can be either of type A or type B. Their only common interface is of type Object.
How should I support this.
I can
have a add method for each type. That would however mean that I should have two properties of type A and B and should check for null when I want to get the right property.
have one property of type of Object. That would mean I had to check to see which kind of instance it is when I get the property.
What is the best solution for this type of problem? Or any better solutions?

Personally I would choose the single Object property approach. Document what types of objects the property may return, and let the calling code use the available language features to determine the object type, and cast as necessary. Implementing two properties is kinda reinventing the "is-a" operator of your language, and will quickly become unmanageable if you ever need to add more possible types.

Well if you are using a language that supports type abstraction (like Generics in Java or Templates in C++) you can just set that property as a generic type. If not, use Object, Having a method for each type is just an ugly hack (and unmaintanable, if you add more types later).

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.

What to name a class with few properties and no methods whose instances get passed around a lot?

I have several small classes that are similar in that they only possess a few properties and no methods, and their instances often get passed around and put into arrays and what not. Is there a naming convention for such a class? At first I was naming them xxxObject, but in OOP that's not really what an object is. Then I considered naming them xxxHelper, but helper seems to indicate methods. What should I add on to the end of this type of class's name?
I would not make these classes at all, it looks like you're using some kind of a global enum or a dictionary.
Enum from C would indicate a key and an integer value.
Dictionary from Python would indicate key and value, value doesn't have to be a specific type.
I would probably use XXDictionary.

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.

Is there a good reason to use a public property / field?

One of the important parts of object-oriented programming is encapsulation, but public properties / fields tend to break this encapsulation. Under what circumstances does a public property or field actually make sense?
Note: I only use the term 'property' or 'field' because terminology varies between languages. In general, I mean a variable that belongs to an object that can be accessed and set from outside the object.
Yes, there are sometimes good reasons. Information hiding is usually desirable. But there are some occasional exceptions.
For example, public fields are reasonable and useful for:
A C++ pimpl - a struct/class holding the private implementation of another class. Its fields may be declared public syntatically, but are typically accessible only within one source file, by the class holding the pimpl.
Constant fields. For example, Joshua Bloch writes in Effective Java: "Classes are permitted to expose constants via public static final fields."
Structs used for communication between C and C++.
Types which represent only data, whose representation is unlikely to change. For example, javax.vecmath.Point3d, which represents an {x,y,z} coordinate.
Short answer: never.
Actually, if you use an object for simply storing data, but the object itself does no logic, and you never mean to derive from this object, then it is OK to have public fields. Sometimes I do things like this in C++:
struct A {
int a;
float b;
string c;
A():a(0),b(0.0) {}
A(int a_, float b_, string c_):a(a_),b(b_),c(c_) {}
};
But other than having initializing constructors, it is nothing more than a C struct. If your class does anything more than this, than you should never use public (or even protected) fields.
As for properties, it depends on what language you use. For example, in Delphi, the main purpose of properties is to provide public interfaces to fields, and can provide getters/setters to them, while still working syntactically like a variable.
Is there a good reason to use a public
property / field?
No.
Public members are always dangerous. You may not need any control now, but once you expose them, you lose any possibility of having control later. If you have gettes/setters right away you have room for adding control later.
Ps:
Depending on the language you use, properties and fields may mean different things.
C# properties are actually a way to both achieve encapsulation and at the same time not being very verbose.
There is a bad reason: by directly accessing the datum you avoid pushing a method call onto the stack, for what that's worth.
In many languages this is also achievable by inlining the accessor method/s.
If the purpose of the object is to hold data in its fields, then yes. It would also make sense to have methods on the object which are (a) purely functional (in that they do not change the state of the object, or anything else); or (b) which manipulate the state of the object, and the point is that they manipulate the state in a particular way.
The kind of things that you should avoid are (c) methods that do things to other objects based on the state of the object (and certainly if there are assumptions about what is a "valid" state).

What Does the "Structure" in VB.NET Mean?

I was reading a VB.NET code and there was the following:
Structure MyRecord
"some code here"
End Structure
Then he use it as if it is a Class. So, what is the "Structure" ??
IS it only in .NET ,or there are similar things in other language??
Something else,in the same code there are:
Dim num As integer=FreeFile()
what does that mean?,can we put a function in a variable in VB?
If we can, then what does that mean??
1
A structure is used to define a value type, just as a class is used to define a reference type. However, a structure is more complicated to implement correctly than a class, so you should stick to classes until you really need to implement a value type. The structure in the example should probably also be implemented as a class instead.
There are structures in other languages, but they may be handled differently. In C++ for example a structure is used to define a type, and the usage determines if it's a value type or a reference type.
2
Yes, you can put a reference to a function (i.e. a delegate) in a variable, but that's not what that code does. It simply calls the function and puts the return value in the variable.
Via startVBdotnet.com:
Structures can be defined as a tool
for handling a group of logically
related data items. They are
user-defined and provide a method for
packing together data of different
types. Structures are very similar to
Classes. Like Classes, they too can
contain members such as fields and
methods. The main difference between
classes and structures is, classes are
reference types and structures are
value types. In practical terms,
structures are used for smaller
lightweight objects that do not
persist for long and classes are used
for larger objects that are expected
to exist in memory for long periods.
We declare a structure in Visual Basic
.NET with the Structure keyword.
Generally, I would suggest implementing a class instead of a structure. This way you can use inheritance and general Object Oriented Design later, if needed.