473,802 Members | 1,978 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Code Reuse.... What level should I expect?

I am just trying to get to grips with C# and OOP, and one of the benefits
would seem to be code reuse. However I am not sure where to draw the line. I
have the following section of code:

if (ev.locationLis t != null)
{
//isListNull = true ensures that we do not recheck the list
every time we add a new item
bool isListNull = false;

if (this.locationL ist == null)
{
this.locationLi st = new List<EventLocat ion>();
isListNull = true;
}
foreach (LocationInfoDT O loList in ev.locationList )
{
EventLocation loc = null;
if (!isListNull)
{
//listMatch is used by the Find Predicate to
match to objects already within the LocationList
listMatch = loList;
loc =
this.locationLi st.Find(EventLo cationListMatch );
}
if (loc == null)
{
this.LocationLi st.Add(EventLoc ation.Create(lo List));
}
else
{
loc.Update(loLi st);
}
}
}

Which is used in my constructor to take the inputs in the form of a DTO (ev)
and translates them into an list object within a business object. I find
that in another class I have a need to populate another list of a different
type from a different type of DTO. Apart from these being different types
the method of populating the list in the other class is identical and
therefore I would live to reuse the code, rather than cutting and pasting. I
therefore have 2 questions:

1. Are my expectations correct, should I be able to create a generic helper
method that does the tasks needed? i.e. :
a.. if the list does not already exist then create it.
b. iterate through each list item in the dto.
c. if the list already existed, then check if the item being added already
exists and update rather than create it
d. else add a new item to the list.

2. If I should be able to produce a generic method, then where should I be
looking for inspiration?

Thanks, Richard

Jul 2 '08 #1
7 1446
On Wed, 02 Jul 2008 05:01:47 -0700, RichB <ri***@communit y.nospamwrote:
[...]
1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? [...]

2. If I should be able to produce a generic method, then where should I
be looking for inspiration?
I don't know how to answer your second question. The answer to your first
question is probably "yes", but we don't really have enough information
about the classes to answer with authority. Looking at the code you
posted, it seems possible that "LocationInfoDT O" is a sub-class of
"EventLocation" . If that's correct, then I would expect the code you
posted to be easily moved to a helper method, probably in a base class
shared by any objects that would use it.

By the way, you may also want to read up on anonymous methods and lambda
expressions. You appear to be using a member field to store state for
your predicate passed to Find(), but this can be addressed in a cleaner,
more readable fashion with an anonymous method or lambda expression. For
example, instead of:

listMatch = loList;
loc = this.locationLi st.Find(EventLo cationListMatch );

(and of course, whatever the implementation of "EventLocationL istMatch()"
is)

you could have:

loc = this.locationLi st.Find(lo =lo == loList);

or:

loc = this.locationLi st.Find(delegat e(EventLocation lo) { return lo ==
loList; });

Pete
Jul 2 '08 #2
"RichB" <ri***@communit y.nospamwrote in message
news:BB******** *************** ***********@mic rosoft.com...
>I am just trying to get to grips with C# and OOP, and one of the benefits
would seem to be code reuse. However I am not sure where to draw the line.
I have the following section of code:
[ SNIP ]
Which is used in my constructor to take the inputs in the form of a DTO
(ev) and translates them into an list object within a business object. I
find that in another class I have a need to populate another list of a
different type from a different type of DTO. Apart from these being
different types the method of populating the list in the other class is
identical and therefore I would live to reuse the code, rather than
cutting and pasting. I therefore have 2 questions:

1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? i.e. :
a.. if the list does not already exist then create it.
b. iterate through each list item in the dto.
c. if the list already existed, then check if the item being added already
exists and update rather than create it
d. else add a new item to the list.

2. If I should be able to produce a generic method, then where should I be
looking for inspiration?

Thanks, Richard
You're fundamentally looking at set operations here, however you may choose
to implement that. Each item has a property or properties that distinguishes
it from any other. As I understand it, the C# options available to you for
actual implementation include HashSet, Hashtable and Dictionary (the latter
two have the same functionality). For coding uniqueness for your DTOs see
http://msdn.microsoft.com/en-us/libr...thashcode.aspx

AHS
Jul 2 '08 #3
Thanks Peter, that is a really good start in two ways... firstly gives me
the confidence to spend some time working it out, without feeling it may all
be for nought, and secondly the tips on improving the use of the find
method. Having said that the match criteria will be different between the
different lists, so I'm not sure that I can use a anonymous method or lambda
expression, but will consider it when I get that far in working out a
common approach.

One last thing, just to clarify the List<LocationIn foDTOis part of the
EventDTO class structure and provides the raw data to instantiate a Event
class, which has a List<EventLocat ion>. EventLocation and LocationInfo DTO
map to each other. It is this mapping that I am trying to acheive in this
case.

Thanks for your help, I suspect that I shall be back for a little more, but
in the meantime I have enough to get me started.

Thanks, Richard

"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Wed, 02 Jul 2008 05:01:47 -0700, RichB <ri***@communit y.nospamwrote:
[...]
1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? [...]

2. If I should be able to produce a generic method, then where should I
be looking for inspiration?
I don't know how to answer your second question. The answer to your first
question is probably "yes", but we don't really have enough information
about the classes to answer with authority. Looking at the code you
posted, it seems possible that "LocationInfoDT O" is a sub-class of
"EventLocation" . If that's correct, then I would expect the code you
posted to be easily moved to a helper method, probably in a base class
shared by any objects that would use it.

By the way, you may also want to read up on anonymous methods and lambda
expressions. You appear to be using a member field to store state for
your predicate passed to Find(), but this can be addressed in a cleaner,
more readable fashion with an anonymous method or lambda expression. For
example, instead of:

listMatch = loList;
loc = this.locationLi st.Find(EventLo cationListMatch );

(and of course, whatever the implementation of "EventLocationL istMatch()"
is)

you could have:

loc = this.locationLi st.Find(lo =lo == loList);

or:

loc = this.locationLi st.Find(delegat e(EventLocation lo) { return lo ==
loList; });

Pete

Jul 3 '08 #4
Arved,

Thanks, for your reply. I assume that you are suggesting that I use a
hashcode as a key for my hashtable perform a comparison. That probably
replaces the loc = this.locationLi st.Find(eventLo cationListMatch ) with a
much cleaner approach.

thanks,
Richard
"Arved Sandstrom" <as********@acc esswave.cawrote in message
news:TyOak.1438 $7%6.1200@edtnp s82...
"RichB" <ri***@communit y.nospamwrote in message
news:BB******** *************** ***********@mic rosoft.com...
>>I am just trying to get to grips with C# and OOP, and one of the benefits
would seem to be code reuse. However I am not sure where to draw the line.
I have the following section of code:
[ SNIP ]
>Which is used in my constructor to take the inputs in the form of a DTO
(ev) and translates them into an list object within a business object. I
find that in another class I have a need to populate another list of a
different type from a different type of DTO. Apart from these being
different types the method of populating the list in the other class is
identical and therefore I would live to reuse the code, rather than
cutting and pasting. I therefore have 2 questions:

1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? i.e. :
a.. if the list does not already exist then create it.
b. iterate through each list item in the dto.
c. if the list already existed, then check if the item being added
already exists and update rather than create it
d. else add a new item to the list.

2. If I should be able to produce a generic method, then where should I
be looking for inspiration?

Thanks, Richard

You're fundamentally looking at set operations here, however you may
choose to implement that. Each item has a property or properties that
distinguishes it from any other. As I understand it, the C# options
available to you for actual implementation include HashSet, Hashtable and
Dictionary (the latter two have the same functionality). For coding
uniqueness for your DTOs see
http://msdn.microsoft.com/en-us/libr...thashcode.aspx

AHS
Jul 3 '08 #5
Thanks for your help. In the end it was pretty easy to solve... Just needed
the confidence to spend the time. I also in the end stayed with the List and
Find(Predicate< T>) method and used an anonymous delegate, which removes the
need for the member field as you advised.

Thanks for the help.

Richard
"RichB" <ri***@communit y.nospamwrote in message
news:11******** *************** ***********@mic rosoft.com...
Thanks Peter, that is a really good start in two ways... firstly gives me
the confidence to spend some time working it out, without feeling it may
all be for nought, and secondly the tips on improving the use of the find
method. Having said that the match criteria will be different between the
different lists, so I'm not sure that I can use a anonymous method or
lambda expression, but will consider it when I get that far in working
out a common approach.

One last thing, just to clarify the List<LocationIn foDTOis part of the
EventDTO class structure and provides the raw data to instantiate a Event
class, which has a List<EventLocat ion>. EventLocation and LocationInfo DTO
map to each other. It is this mapping that I am trying to acheive in this
case.

Thanks for your help, I suspect that I shall be back for a little more,
but in the meantime I have enough to get me started.

Thanks, Richard

"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Wed, 02 Jul 2008 05:01:47 -0700, RichB <ri***@communit y.nospamwrote:
>[...]
1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? [...]

2. If I should be able to produce a generic method, then where should I
be looking for inspiration?

I don't know how to answer your second question. The answer to your first
question is probably "yes", but we don't really have enough information
about the classes to answer with authority. Looking at the code you
posted, it seems possible that "LocationInfoDT O" is a sub-class of
"EventLocation" . If that's correct, then I would expect the code you
posted to be easily moved to a helper method, probably in a base class
shared by any objects that would use it.

By the way, you may also want to read up on anonymous methods and lambda
expressions. You appear to be using a member field to store state for
your predicate passed to Find(), but this can be addressed in a cleaner,
more readable fashion with an anonymous method or lambda expression. For
example, instead of:

listMatch = loList;
loc = this.locationLi st.Find(EventLo cationListMatch );

(and of course, whatever the implementation of "EventLocationL istMatch()"
is)

you could have:

loc = this.locationLi st.Find(lo =lo == loList);

or:

loc = this.locationLi st.Find(delegat e(EventLocation lo) { return lo ==
loList; });

Pete
Jul 5 '08 #6
RichB wrote:
I am just trying to get to grips with C# and OOP, and one of the
benefits would seem to be code reuse. However I am not sure where to
draw the line. I have the following section of code:

if (ev.locationLis t != null)
{
//isListNull = true ensures that we do not recheck the
list every time we add a new item
bool isListNull = false;

if (this.locationL ist == null)
{
this.locationLi st = new List<EventLocat ion>();
isListNull = true;
}
foreach (LocationInfoDT O loList in ev.locationList )
{
EventLocation loc = null;
if (!isListNull)
{
//listMatch is used by the Find Predicate to
match to objects already within the LocationList
listMatch = loList;
loc =
this.locationLi st.Find(EventLo cationListMatch );
}
if (loc == null)
{
this.LocationLi st.Add(EventLoc ation.Create(lo List));
}
else
{
loc.Update(loLi st);
}
}
}

Which is used in my constructor to take the inputs in the form of a DTO
(ev) and translates them into an list object within a business object. I
find that in another class I have a need to populate another list of a
different type from a different type of DTO. Apart from these being
different types the method of populating the list in the other class is
identical and therefore I would live to reuse the code, rather than
cutting and pasting. I therefore have 2 questions:

1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? i.e. :
a.. if the list does not already exist then create it.
b. iterate through each list item in the dto.
c. if the list already existed, then check if the item being added
already exists and update rather than create it
d. else add a new item to the list.

2. If I should be able to produce a generic method, then where should I
be looking for inspiration?
You can and should reuse code.

I also think the code can be simplified a bit.

For inspiration:

public static List<T2DTO2BO<T 1,T2>(List<T1li st, Predicate<T1p)
{
return list.FindAll(p) .ConvertAll<T2> (new Converter<T1,
T2>(delegate(T1 o) { return (T2)Activator.C reateInstance(t ypeof(T2), new
object[] { o }); }));
}

I have attached a full example below.

Arne

=============== =============== =============== ============

using System;
using System.Collecti ons.Generic;

namespace E
{
public class DTOEx
{
private int iv;
private String sv;
public DTOEx(int iv, string sv)
{
this.iv = iv;
this.sv = sv;
}
public int Iv
{
get
{
return iv;
}
set
{
iv = value;
}
}
public string Sv
{
get
{
return sv;
}
set
{
sv = value;
}
}
public override string ToString()
{
return "[DTO:" + iv + "," + sv + "]";
}
}
public class BOEx
{
private int iv;
private String sv;
public BOEx(int iv, string sv)
{
this.iv = iv;
this.sv = sv;
}
public BOEx(DTOEx o)
{
this.iv = o.Iv;
this.sv = o.Sv;
}
public int Iv
{
get
{
return iv;
}
set
{
iv = value;
}
}
public string Sv
{
get
{
return sv;
}
set
{
sv = value;
}
}
public override string ToString()
{
return "[BO:" + iv + "," + sv + "]";
}
}
public class Program
{
public static List<T2DTO2BO<T 1,T2>(List<T1li st,
Predicate<T1p)
{
return list.FindAll(p) .ConvertAll<T2> (new Converter<T1,
T2>(delegate(T1 o) { return (T2)Activator.C reateInstance(t ypeof(T2), new
object[] { o }); }));
}
public static void Main(string[] args)
{
List<DTOExdtoex list = new List<DTOEx>();
dtoexlist.Add(n ew DTOEx(1, "A"));
dtoexlist.Add(n ew DTOEx(2, "BB"));
dtoexlist.Add(n ew DTOEx(3, "CCC"));
foreach(DTOEx o in dtoexlist)
{
Console.WriteLi ne(o);
}
List<BOExboexli st = DTO2BO<DTOEx,BO Ex>(dtoexlist,
delegate(DTOEx o) { return o.Iv 1; });
foreach(BOEx o in boexlist)
{
Console.WriteLi ne(o);
}
Console.ReadKey ();
}
}
}
Jul 6 '08 #7
Thanks Arne,

Very neat, but I've actually done it in a more verbose way, using
inheritance and some simplified generics.

Richard
"Arne Vajhøj" <ar**@vajhoej.d kwrote in message
news:48******** *************** @news.sunsite.d k...
RichB wrote:
>I am just trying to get to grips with C# and OOP, and one of the benefits
would seem to be code reuse. However I am not sure where to draw the
line. I have the following section of code:

if (ev.locationLis t != null)
{
//isListNull = true ensures that we do not recheck the
list every time we add a new item
bool isListNull = false;

if (this.locationL ist == null)
{
this.locationLi st = new List<EventLocat ion>();
isListNull = true;
}
foreach (LocationInfoDT O loList in ev.locationList )
{
EventLocation loc = null;
if (!isListNull)
{
//listMatch is used by the Find Predicate to
match to objects already within the LocationList
listMatch = loList;
loc =
this.locationL ist.Find(EventL ocationListMatc h);
}
if (loc == null)
{

this.LocationL ist.Add(EventLo cation.Create(l oList));
}
else
{
loc.Update(loLi st);
}
}
}

Which is used in my constructor to take the inputs in the form of a DTO
(ev) and translates them into an list object within a business object. I
find that in another class I have a need to populate another list of a
different type from a different type of DTO. Apart from these being
different types the method of populating the list in the other class is
identical and therefore I would live to reuse the code, rather than
cutting and pasting. I therefore have 2 questions:

1. Are my expectations correct, should I be able to create a generic
helper method that does the tasks needed? i.e. :
a.. if the list does not already exist then create it.
b. iterate through each list item in the dto.
c. if the list already existed, then check if the item being added
already exists and update rather than create it
d. else add a new item to the list.

2. If I should be able to produce a generic method, then where should I
be looking for inspiration?

You can and should reuse code.

I also think the code can be simplified a bit.

For inspiration:

public static List<T2DTO2BO<T 1,T2>(List<T1li st, Predicate<T1p)
{
return list.FindAll(p) .ConvertAll<T2> (new Converter<T1,
T2>(delegate(T1 o) { return (T2)Activator.C reateInstance(t ypeof(T2), new
object[] { o }); }));
}

I have attached a full example below.

Arne

=============== =============== =============== ============

using System;
using System.Collecti ons.Generic;

namespace E
{
public class DTOEx
{
private int iv;
private String sv;
public DTOEx(int iv, string sv)
{
this.iv = iv;
this.sv = sv;
}
public int Iv
{
get
{
return iv;
}
set
{
iv = value;
}
}
public string Sv
{
get
{
return sv;
}
set
{
sv = value;
}
}
public override string ToString()
{
return "[DTO:" + iv + "," + sv + "]";
}
}
public class BOEx
{
private int iv;
private String sv;
public BOEx(int iv, string sv)
{
this.iv = iv;
this.sv = sv;
}
public BOEx(DTOEx o)
{
this.iv = o.Iv;
this.sv = o.Sv;
}
public int Iv
{
get
{
return iv;
}
set
{
iv = value;
}
}
public string Sv
{
get
{
return sv;
}
set
{
sv = value;
}
}
public override string ToString()
{
return "[BO:" + iv + "," + sv + "]";
}
}
public class Program
{
public static List<T2DTO2BO<T 1,T2>(List<T1li st, Predicate<T1>
p)
{
return list.FindAll(p) .ConvertAll<T2> (new Converter<T1,
T2>(delegate(T1 o) { return (T2)Activator.C reateInstance(t ypeof(T2), new
object[] { o }); }));
}
public static void Main(string[] args)
{
List<DTOExdtoex list = new List<DTOEx>();
dtoexlist.Add(n ew DTOEx(1, "A"));
dtoexlist.Add(n ew DTOEx(2, "BB"));
dtoexlist.Add(n ew DTOEx(3, "CCC"));
foreach(DTOEx o in dtoexlist)
{
Console.WriteLi ne(o);
}
List<BOExboexli st = DTO2BO<DTOEx,BO Ex>(dtoexlist,
delegate(DTOEx o) { return o.Iv 1; });
foreach(BOEx o in boexlist)
{
Console.WriteLi ne(o);
}
Console.ReadKey ();
}
}
}
Jul 8 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

242
13466
by: James Cameron | last post by:
Hi I'm developing a program and the client is worried about future reuse of the code. Say 5, 10, 15 years down the road. This will be a major factor in selecting the development language. Any comments on past experience, research articles, comments on the matter would be much appreciated. I suspect something like C would be the best based on comments I received from the VB news group. Thanks for the help in advance James Cameron
6
2179
by: Mario T. Lanza | last post by:
Greetings, I don't know about you guys but on many occasions I've asked myself whether or not someone else has solved a particular programming issue -- whether or not they developed a clever pattern for doing some task quite well. This usually leads me to a search on today's greatest technical tool, The Internet. I indefinitely uncover many potential code snippets, components, etc. and have to weed through them to find the best one...
6
373
by: Mario T. Lanza | last post by:
Greetings, I don't know about you guys but on many occasions I've asked myself whether or not someone else has solved a particular programming issue -- whether or not they developed a clever pattern for doing some task quite well. This usually leads me to a search on today's greatest technical tool, The Internet. I indefinitely uncover many potential code snippets, components, etc. and have to weed through them to find the best one...
2
1974
by: Jeff Dege | last post by:
I'm working with a group that's been doing C++ coding for quite a long time, now, and in that environment we've pretty much worked out development practices that serve us well. We've been doing more and more, over the last few years, in C# and ASP.NET. Some web apps, some background services. In our C++ code base, we have a fair number of statically-linked libraries that contain code we share between projects. At this point, in our...
0
9562
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10305
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10285
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9115
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7598
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6838
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.