Method advice

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi I have the following code which runs ok from a button click event

private void btnCompact_Click(object sender, System.EventArgs e)
{
string mdbComp = @"C:\Compact.mdb";
string mdbTemp = @"C:\tempdb.mdb";

JRO.JetEngine jro;
jro = new JRO.JetEngine();
jro.CompactDatabase(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
mdbComp + @"", @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbTemp +
@";Jet OLEDB:Engine Type=5");

File.Delete(mdbComp);
File.Move(mdbTemp, mdbComp);

MessageBox.Show("Finished Compacting Database!");
}

Would this code be better split up so that it calls a method. If so, what is
the best way, also how would the strings mdbComp and mdbTemp be passed.
 
hmmmmm...here's my $0.02:

1~ make the mdbComp and mdbTemp strings private constants of the
surrounding class, or, if they can be set in a config file, make them
private fields of the surrounding class and have them initialized in
the class contructor (or in the static constructor);

2~ Yes, I think your idea to move the code that actually does stuff
away from this method is good. I usually like to have my event handler
only deal with GUI, and calling other methods for the actual function
implementation. After all, it may be that another button will have to
call the same functionality... so,

public class MySample
{
private const string mdbComp = @"C:\Compact.mdb";
private const string mdbTemp = @"C:\tempdb.mdb";

private void btnCompact_Click(object sender, System.EventArgs e)
{
try
{
this.CompactDatabase();
MessageBox.Show(this, "Database has been compacted.");
}
catch(Exception e2)
{
MessageBox.Show(this, "An Exception occurred: "+e2.Message);
}
}
private void CompactDatabase()
{
try
{
JRO.JetEngine jro;
jro = new JRO.JetEngine();
jro.CompactDatabase(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
MySample.mdbComp + @"", @"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=" + MySample.mdbTemp +
@";Jet OLEDB:Engine Type=5");

File.Delete(MySample.mdbComp);
File.Move(MySample.mdbTemp, MySample.mdbComp);
}
catch(Exception e)
{
throw new ApplicationException("An Exception occurred while
compacting the database:\n"+
e.Message, e);
}
}
}

HTH,
F.O.R.
 
Thanks, that works great.

The only other thing is that there could be upto 7 different databases to
compact. Would it be better to pass these names into the CompactDatabase
method as parameters?
 
Back
Top