When you are developing an API for a code library, you want it to be easy to use and not work well. Ideally, you want this to be proof of an idiot.
You can also make it compatible with older systems that cannot handle generics such as .Net 1.1 and Java 1.4. But you do not want this to be a pain to use from newer code.
I am wondering how to make things easily iterable in a safe way ... Remembering that you cannot use generics, so Java is Iterable<T>missing, as is .Net IEnumerable<T>.
You want people to be able to use the extended loop in Java (for Item i : items)and the foreach/ loop For Eachin .Net, and you don't want them to cast. Basically, you want your API to be now friendly as well as backward compatible.
The best safe type I can imagine is arrays. They are fully compatible with feedback and are easy to sort by type. But arrays are not perfect because you cannot make them immutable. That way, when you have an immutable object that contains an array that you want people to iterate over to maintain immutability, you need to provide a protective copy every time they access it.
Java (MyObject[]) myInternalArray.clone(); -. , .Net . :
class Schedule {
private Appointment[] internalArray;
public Appointment[] appointments() {
return (Appointment[]) internalArray.clone();
}
}
:
for (Appointment a : schedule.appointments()) {
a.doSomething();
}
, , .
- :
for (int i = 0; i < schedule.appointments().length; i++) {
Appointment a = schedule.appointments()[i];
}
, ( , ). , , , . .
- ? ... , .
toAppointmentArray() appointments(), , , , - . , .
, , appointments(), , . .
, , , , . , , ?
NB , , Java .Net, . -, , . Java, # ( Appointments accessor a)).
UPDATE. , , Java. :
- ArrayList
- ArrayList (
Collections.unmodifyableList),
- (
).
10 ( ) :
100 :
1000 :
10000 :
- 68000
- 445000
- 651000
- 655180000
, , :