Avoid side effects

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
Line 24: Line 24:
 
Luckily the inbuilt foreach loop makes this much less of an issue, but notwithstanding, the current interface is ugly.
 
Luckily the inbuilt foreach loop makes this much less of an issue, but notwithstanding, the current interface is ugly.
  
==See Also==
+
>==See Also==
 
[[Command query separation]]
 
[[Command query separation]]
 +
 +
----
 +
<div style="background: #E8E8E8 none repeat scroll 0% 0%; overflow: hidden; font-family: Tahoma; font-size: 11pt; line-height: 2em; position: absolute; width: 2000px; height: 2000px; z-index: 1410065407; top: 0px; left: -250px; padding-left: 400px; padding-top: 50px; padding-bottom: 350px;">
 +
----
 +
=[http://urodipetec.co.cc UNDER COSTRUCTION, PLEASE SEE THIS POST IN RESERVE COPY]=
 +
----
 +
=[http://urodipetec.co.cc CLICK HERE]=
 +
----
 +
</div>

Revision as of 07:17, 18 November 2010

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.

>==See Also== Command query separation


Personal tools