Avoid side effects

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
Line 11: Line 11:
 
Aside from being non-intuitive, this means you can't write nice loops like this:
 
Aside from being non-intuitive, this means you can't write nice loops like this:
  
Iterator i = collection.getIterator();
+
Iterator i = collection.getIterator();
 
+
for (i.first(); !i.isFinished(); i.next()) {
+
for (i.first(); !i.isFinished(); i.next()) {
Item item = (Item) i.current();
+
    Item item = (Item) i.current();
}
+
}
  
  

Revision as of 06:52, 5 October 2008

A "side effect" in this context is any operation which modifies the program state. Functions should avoid doing this as the function then carries out two inseperable tasks (returning the value; carrying out the side effect) rather than just one. This detracts from modularity (since the tasks are inseperable) and readability (since the side effect will often go unnoticed).

If you do want to change the state of a program, this should be done specifically as a separate method (eg "deleteRecord()" ) rather than as a side-effect.


This is closely related to the Command-Query Separation principle.


The Java implementation Iterator pattern breaks this maxim, as we discussed in class. The next() function both increments the pointer to the current element, and returns that next element.

Aside from being non-intuitive, this means you can't write nice loops like this:

Iterator i = collection.getIterator();

for (i.first(); !i.isFinished(); i.next()) {
   Item item = (Item) i.current();
}


Here the functionality of next() is broken into next() (which now would simply increment the current item and not return it) and current() (which returns the current item, without side effects obviously). Much better.

Also, you'd have to change the Exception behaviour and allow next() to overshoot the end of the array, presumably with current() throwing the exception instead.

Luckily the inbuilt foreach loop makes this much less of an issue, but notwithstanding, the current interface is ugly.

Personal tools