2009-09-25

The beauty of 2 state enums

The .NET type system already has a type for 2 states, it is of cause the Boolean. So why would I want to make a custom type?

Lets look at some code.

   1: var export = new SchemaExport(_cfg);
   2: var sb = new StringBuilder();
   3: TextWriter output = new StringWriter(sb);
   4: export.Execute(true, false, false, null, output);

The code above is from NHibernate, more specifically it is NHibernates schema export.

The documentation looks like the following.

public void Execute(bool script, bool export, bool justDrop, System.Data.IDbConnection connection, System.IO.TextWriter exportOutput)
    Member of NHibernate.Tool.hbm2ddl.SchemaExport

Summary:
Executes the Export of the Schema in the given connection

Parameters:
script: true if the ddl should be outputted in the Console.
export: true if the ddl should be executed against the Database.
justDrop: true if only the ddl to drop the Database objects should be executed.
connection: The connection to use when executing the commands when export is true.  Must be an opened connection. The method doesn't close the connection.
exportOutput: The writer used to output the generated schema

Remarks:
This method allows for both the drop and create ddl script to be executed.  This overload is provided mainly to enable use of in memory databases. It does NOT close the given connection!

Now I don't necessarily remember method signatures all to well. So custom type too the rescue, or rather custom enum too the rescue.

   1: public enum Script
   2: {
   3:     OutputToConsole,
   4:     NoConsoleOutput
   5: }
   6: pulic enum Export
   7: {
   8:     ExecuteScriptAgainstDatabase,
   9:     DontExecuteAgainstDatabase
  10: }
  11: public enum DDL
  12: {
  13:     DropOnly,
  14:     CreateAndDrop
  15: }
  16: export.Execute(Script.OutputToConsole, Export.DontExecuteAgainstDatabase, DDL.CreateAndDrop, null, output);

Another alternative is to make several methods that can be named, or create a class that takes the arguments as properties, so that they can be optional.

No comments: