Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!newsfeed.straub-nv.de!weretis.net!feeder4.news.weretis.net!usenet.ukfsn.org!not-for-mail From: Martin Gregorie Newsgroups: comp.lang.java.programmer Subject: Re: refactoring problem Date: Sun, 3 Feb 2013 16:23:03 +0000 (UTC) Organization: UK Free Software Network Lines: 51 Message-ID: References: <7fssg8dakvofmv6pk3sfvp5jmaku55vgmm@4ax.com> NNTP-Posting-Host: 84.45.235.129 Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: localhost.localdomain 1359908583 19793 84.45.235.129 (3 Feb 2013 16:23:03 GMT) X-Complaints-To: usenet@localhost.localdomain NNTP-Posting-Date: Sun, 3 Feb 2013 16:23:03 +0000 (UTC) User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508 git://git.gnome.org/pan2) Xref: csiph.com comp.lang.java.programmer:22045 On Sun, 03 Feb 2013 06:30:40 -0800, Roedy Green wrote: > Consider the following refactoring problem. > > There is a hunk of almost identical code that appears multiple times. > It sets up 6 local variables. > > I would like to encapsulate it. > > > I could create a separate class just to hold the values. This is > tedious, but it may be the only way. > ...which you can return from a method. I keep wondering whether I should use this approach but so far haven't used it. > I think, why can methods have multiple inputs, but only one output? I > have been thinking that for about 50 years, and it ,seems unlikely to > change soon. > Formally true, but not necessarily so in practice. You can return a class instance containing as many variables as you need to return. You can also pass the constructor a reference to a mutable object which contains the variables you want to change. I use this quite a lot: its particularly useful for letting logically separate sets of methods access and manipulate a collection: each set of methods forms a class that's handed a reference to the collection. Example: I've just finished dealing with a way of handling a collection of geographical points: Each point forms a Waypoint that contains coordinates and descriptive attributes together with the methods needed to access its (immutable) attributes. The collection forms a WaypointList class that holds a set of Waypoints as an ArrayList plus two TreeMaps that give keyed access to Waypoints and methods needed to add, remove and retrieve individual Waypoints. There is a requirement to read a waypoint file into the WaypointList and to write it out to a file: there are currently five externally defined waypoint file formats I need to deal with so there is a set of classes, one per file format, that each implement a load() and a save() method. In addition there will be three programs that carry out more complex operations on one or more WaypointLists: only one of these has been written so far. -- martin@ | Martin Gregorie gregorie. | Essex, UK org |