I have a superclass Appointment that is then extended to a few different types of appointments. I need to make an ArrayList of appointments of different types which I did not think would be much of a problem since they all share a common superclass - Appointment. But when I try to add one of the subclasses Daily to the ArrayList<Appointment> book = new ArrayList<Appointment>() it fails to do so.
I have:
ArrayList<Appointment> book = new ArrayList<Appointment>()
Then later on in the program (I'm passing description, day, month, and year from the method it's place in):
book.add(new Daily(description, day, month, year));
And I get the suggestion of: The method add(AppointmentBook.Appointment) in the type ArrayList is not applicable for the arguments (Daily)
Change your code from ArrayList<Appointment> to ArrayList<? extends Appointment>
Related
I'm having trouble with Smalltalk. Is there some operator like "is in" or "is contained / included"?
I have classes Student and Exam (with attribute student) and collections StudentsList and ExamsList. In the ExamsList, I would like to show all instances of class Exam that meet the criteria that their student (object set as value of attribute student) is contained in collection StudentsList.
Something like the following code, but it does not work:
ExamsList list: (Exam allInstances select: [ :ex | (StudentsList includes: ex student) ]).
Could you think of some elegant solution?
Many thanks!
Even though your question lacks some information, there are a few comments that might help.
If your naming convention is consistent and ExamsList is a class, then StudentsList must be a class too. In that case your code doesn't work because classes do not understand the message #includes:, which is intended to be sent to subinstances of Collection.
Assuming my guess is applicable, I would point out that it is not a good idea to have a class for every collection of objects. So, instead of having the class ExamsList, you should add a class variable Exams to the class Exam, initialized to a Set and store there every instance of Exam that you want to preserve for future queries.
In the same way, you should add a class variable Students to the class Student and get rid of StudentsList.
With this design every new instance that matters should be saved in the corresponding collection held by the class (see 6 below for a hint on how to do this). This would eliminate the need for enumerating #allInstances.
In any case, you should understand that #allInstances is a system message, i.e., it is not intended for querying objects in the realm of your model as it belongs in much lower level of abstraction. Note that #allInstances will collect instances that for whatever reason (tests, examples, open debuggers or inspectors, etc.) may still be around without being part of your model.
If every Exam has a Student, you could store an Exam in the Exams collection whenever you assign it to the designated Student, something on the lines of
Exam >> forStudent: aStudent
Exams add: self.
student := aStudent
(student is an ivar of Exam, and self represents the instance with concrete questions)
Lately I was wondering if it is a bad practice to use variables in your code that are related to each other (e.g. a = 2 * b). A concrete example would be euro and dollars. Let's say we have a Person class who has some balance in euros and dollars (coded in java for demonstration):
class Person {
float balanceInEuros;
float balanceInDollars;
public Person(...) { // Problem 1 (see down below)
}
}
Problem 1: What do you need to put in the constructor arguments? Both variables are float so we can't differentiate between to distinct constructors (java can have multiple constructors for a class, as long as they have a different type of arguments). To solve this we can make two separate methods to return a Person, for example:
public static createPersonWithEuros(float euros) {
Person person = new Person();
person.setEuros(euros);
return person;
}
// Similar for dollars...
Problem 2: Now we have no value for the dollars, so a method person.getDollars() would result in an error. Of course this can be fixed again by adding a single line in the createPersonWithEuros() method: person.setDollars(Person.EXCHANGE_RATE_EURO_DOLLAR * euros) or something along those lines.
Arguments for
It feels more natural to use dollars and euros instead of a so called 'balance' which has no concrete meaning.
It makes more sense and thus enhances the readability of the code
Arguments against
By using a universal 'balance' with functions to calculate to euros/dollars etc., it results in cleaner code (less functions/bulk code...)
You need more memory to store essentially the same thing, which could be bad
What is better and why?
EDIT: Another thing I am concerned with is that I programmed this particular example in an OO language. What if this was written in javascript for example?
By creating a separate class Balance which has an amount and a currency, you can use a single constructor with a 'balance' parameter and use euros, dollars, pounds and so on as you like. All conversion goes to the Balance class and Person can use balances regardless of currencies, conversion rates and so on.
This might be an odd question, but it has actually caused me some headache.
In Object oriented programming, there are accepted names for key concepts. In our model, we have classes with methods and fields. Now, going to the data world:
An instance of a class is called an object.
An instance of a field is called... what?
A value? Isn't the term value a little broad for this? I have been offered "property" as well, but isn't property also part of the model and not the data?
(This is not purely academic, I am actually coding these concepts.)
Updated: Let me take an example. I have a class "Person" with a field "age". If I create 20 Person instances, each such instance is called an object. So far so good. But let's say I take Person "Igor", and set his age to 20. What is the storage location that contains the number 20 now called? Is it a field, or a value, or something else?
Another update: A quote from Pavel Feldman in this related question describes in different words what I tried to describe above:
"I'd say that in class-based OOP field belongs to class and does not have a value. It is so when you look at reflection in c# or java - class has fields, field has type, name, etc. And you can get value of the field from object. You declare field once, in class. You have many objects with same fields but different values."
A field can't be instantiated. A field can only contain a value. The value can be either a primitive/native type or a reference/pointer to an object instance.
As per your update: if the object represents a real world entitiy, then it's often called property. With a "real world entity" I mean something personal/human, e.g. Person, Product, Order, Car, etc. If the object does not represent something personal/human, e.g. List, String, Map, then it's more often called field. That's just what I've observed as far.
Agree with BalusC. However I think what you are asking is what to call the field of an instantiated object. Remember that an object contains both state (data) and operations (methods) you could refer to an object field as state
A field is a field weather you talk about it in the context of a class, or in the context of an object.
class C {
int i; // i is a field
}
and
obj = new C();
obj.i = 7; // obj.i is a field
As opposed to parameter vs argument there is no distinction in terminology for "instantiated" an "uninstantiated" fields.
An instance of a class is an object, a class may contain fields that point to other instantiated objects (or a null pointer). It makes no sense to say an instance of a field, but rather you might talk about the object to which a particular field points to, which may be different for different instances. Or you may talk about the type of a field (which class it belongs to)
Isn't the answer basically that we have no name for values of fields of an instance of a class (or object)?
It's like giving a name to the value returned by a method of an instance of a class...
I guess "state" is the best answer anyway as suggested "BalusC".
Portfolio A → Fund 1
Portfolio A → Fund 2
Portfolio A → Fund 3
I couldn't frame my sentence without not using is/has. But between 1 & 2,
1) has a:
class PortfolioA
{
List<Fund> obj;
}
2) is a:
class PortfolioA : List<Fund>
{
}
which one do you think is better from the point of extensibility, usability? I can still access my funds either way, albeit with a small syntactical change.
I vote with the other folks who say HAS-A is better in this case. You ask in a comment:
when I say that a Portfolio is just a
collection of funds, with a few
attributes of its own like
TotalPortfolio etc, does that
fundamentally not become an "is-a"?
I don't think so. If you say Portfolio IS-A List<Fund>, what about other properties of the Portfolio? Of course you can add properties to this class, but is it accurate to model those properties as properties of the List? Because that's basically what you're doing.
Also what if a Portfolio is required to support more than one List<Fund>? For instance, you might have one List that shows the current balance of investments, but another List that shows how new contributions are invested. And what about when funds are discontinued, and a new set of funds is used to succeed them? Historical information is useful to track, as well as the current fund allocation.
The point is that all these properties are not correctly properties of a List, though they may be properties of the Portfolio.
do not 'always' favor composition or inheritance or vice-versa; they have different semantics (meanings); look carefully at the meanings, then decide - it doesn't matter if one is 'easier' than the other, for longevity it matters that you get the semantics right
remember: is-a = type, has-a = containment
so in this case, a portfolio logically is a collection of funds; a portfolio itself is not a type of fund, so composition is the correct relationship
EDIT: I misread the question originally, but the answer is still the same. A Portfolio is not a type of list, it is a distinct entity with its own properties. For example, a portfolio is an aggregate of financial instruments with an initial investment cost, a total current value, a history of values over time, etc., while a List is a simple collection of objects. A portfolio is a 'type of list' only in the most abstract sense.
EDIT 2: think about the definition of portfolio - it is, without exception, characterized as a collection of things. An artist's portfolio is a collection of their artwork, a web designer's portfolio is a collection of their web sites, an investor's portfolio consists of all of the financial instruments that they own, and so on. So clearly we need a list (or some kind) to represent a portfolio, but that in no way implies that a portfolio is a type of list!
suppose we decide to let Portfolio inherit from List. This works until we add a Stock or Bond or Precious Metal to the Portfolio, and then suddenly the incorrect inheritance no longer works. Or suppose we are asked to model, say, Bill Gates' portfolio, and find that List will run out of memory ;-) More realistically, after future refactoring we will probably find that we should inherit from a base class like Asset, but if we've already inherited from List then we can't.
Summary: distinguish between the data structures we choose to represent a concept, and the semantics (type hierarchy) of the concept itself.
The first one, because you should try to favour composition over inheritance when you can.
It depends whether the business defines a Portfolio as a group (and only a group) of funds. If there is even the remote possibility of that it could contain other objects, say "property", then go with option 1. Go with option 2 if there is a strong link between a group of funds and the concept of Portfolio.
As far as extensibility and usefullness 1 has the slight advantage over 2. I really disagree with the concept that you should always favour one over the other. It really depends on what the actual real life concepts are. Remember, you can always^ refactor.
^ For most instances of always. If it is exposed publicly, then obviously not.
I would go with option (1) - composition, since you may eventually have attributes specific to the portfolio, rather than the funds.
The first one, because it is "consists of". => Composition
I will differ with what appears to be the common opinion. In this case I think a portfolio is very little more than a collection of funds... By using inheritance you allow the use of multiple constructors, as in
public Portfolio(CLient client) {};
public Portfolio(Branch branch, bool Active, decimal valueThreshold)
{
// code to populate collection with all active portfolios at the specified branch whose total vlaue exceeds specified threshold
}
and indexers as in:
public Fund this[int fundId] { get { return this.fundList[fundId]; } }
etc. etc.
if you want to be able to treat variables of type Portfolio as a collection of funds, with the associated syntax, then this is the better approach.
Portfolio BobsPortfolio = new Portfolio(Bob);
foreach (Fund fund in BobsPortfolio)
{
fund.SendStatement();
}
or stuff like that
IS-A relation ship represents inheritances and HAS-A relation ship represents composition. For above mentioned scenario we prefer composition as PortfolioA has a List and it is not the List type. Inheritances use when Portfolio A is a type of List but here it is not. Hence for this scenario we should prefer Composition.
Sorry for the bad question title.
Let's say that I have DateRange class that basically just consists of a start date and and end date.
My question is: How might I represent computed date ranges such as "This Week", "The Past Two Weeks", "Last Month", and "This Quarter", such that multiple clients can use these computed date ranges in a consistent way? That is, I'm going to have multiple objects of multiple classes that all need to know what "This Week" is.
I could build them into DateRange, but that doesn't seem like a good solution because more might be added or some may become obsolete over time....in fact this will happen most certainly. I could make DateRange abstract and extend it, but then I'm going to have a bunch of tiny classes. I could create some kind of static helper class that computes these dates. How might you approach this problem?
dateRange = new DateRange(RangeEnum.THISWEEK));
or
dateRange = new ThisWeek();
or
dateRange = DateHelper.getThisWeek();
or
?
To throw an additional wrench into this thing, let's say that I also need to represent a range like "the work week containing the date May 1, 2008". Upon stating that, I'm leaning towards the helper class...it just feels awkward having a big lump of goofy methods.
Why create a helper class. The common idiom used in the .NET framework would be to add Static properties to the existing class.
class DateRange
{
DateRange ourCurrentWeek = null;
public static DateRange ThisWeek
{
get
{
//create ourCurrentWeek if not yet assigned.
//test current week; is it still correct or does it need updating
return ourCurrentWeek;
}
}
}
Usage is simply:-
DateRange.ThisWeek
I would go the way with the helper class.
DateRange dr = Helper.getThisWeek();
You're right, you'll get a bunch a methods, but if you would subclass something you'll get a bunch of classes. This way you know for sure where to look.