How to eliminate duplicate code?

Writing and using Classes in Dyalog APL
Post Reply
paulmansour
Posts: 431
Joined: Fri Oct 03, 2008 4:14 pm

How to eliminate duplicate code?

Post by paulmansour »

Consider the following code which specifies three properties in a class:

Code: Select all

Property MyPropA
:Access Public
 ∇ z←get x
   z←GetProperty x
 ∇
 ∇ set x;z
   z←SetProperty x
 ∇
:EndProperty

:Property MyPropB
:Access Public
 ∇ z←get x
   z←GetProperty x
 ∇
 ∇ set x;z
   z←SetProperty x
 ∇
:EndProperty

:Property MyPropC
:Access Public
 ∇ z←get x
   z←GetProperty x
 ∇
 ∇ set x;z
   z←SetProperty x
 ∇
:EndProperty


The work required for getting and setting each property is identical, and thus extracted into two common sub functions, GetProperty and SetProperty.

However, despite this, the code is still massively repetitive, which makes me feel like writing it is a colossal waste of time. How can I get rid of it? I guess I have to write a function which generates the class script and then fixes it, is that the only way?
gil
Posts: 72
Joined: Mon Feb 15, 2010 12:42 am

Re: How to eliminate duplicate code?

Post by gil »

If you know the names of all the properties at the time of designing the class you can simply provide a list of names:

Code: Select all

:Property MyPropA,MyPropB,MyPropC
:Access Public
 ∇ z←get x
   z←GetProperty x
 ∇
 ∇ set x;z
   z←SetProperty x
 ∇
:EndProperty


      x.Name
will contain the name of the property that is accessed.
paulmansour
Posts: 431
Joined: Fri Oct 03, 2008 4:14 pm

Re: How to eliminate duplicate code?

Post by paulmansour »

Gil, thanks, that's great!

I had no idea you could do that!
Post Reply