Builder Pattern – Creating a full set of exercise objects

Three things need to happen in order for me to have a full ModelExercise from the API:

  1. Muscle Groups need to be downloaded
  2. Exercises need to be downloaded
  3. An association table must be built between the two.

Normally I’d use Entity Framework for this sort of thing but with PCL at a time when I started the project, it had quite a lot of problems and SQLite.NET-PCL  was the recommended solution.
That is okay but it means I need to build everything myself so long:


public virtual List<Exercise> Exercises {get; set;}

I need to build this relationship myself, so first of a model class:


 public class MuscleExerciseAssosiation
 {
 public int MuscleId { get; set; }
 public int ModelExerciseId { get; set; }
 public string MuslceType { get; set; }
 }

How I get muscles and exercises you can see in my previous post the association is build:


public override List<MuscleExerciseAssosiation> AssosiationGet()
{
if (_wgerExercises.Count == 0 || _muscles.Count == 0)
{
return new List<MuscleExerciseAssosiation>();
}
foreach (var exercise in _wgerExercises)
{
foreach (var muscle in exercise.muscles)
{
_muscleAssosiations.Add(
new MuscleExerciseAssosiation
{
ModelExerciseId = exercise.id,
MuscleId = muscle,
MuslceType = "Primary"
}
);
}
foreach (var muscle in exercise.muscles_secondary)
{
_muscleAssosiations.Add(
new MuscleExerciseAssosiation
{
ModelExerciseId = exercise.id,
MuscleId = muscle,
MuslceType = "Secondary"
}
);
}
}
return _muscleAssosiations;
}

which I then simply load into the database:


private async Task FillMuscleExerciseAssosiations(AbstractSourceFactory factory)
{
List<MuscleExerciseAssosiation> assosiations = factory.AssosiationGet();
await _connection.InsertAllAsync(assosiations);
}

But it is private… so I cannot call it outside of the class… Thats where the builder pattern comes in, as mentioned at the top of the post all 3 things need to happen in a sequence and they all need to happen, hence a new public method:


public async Task BuildMuscleDatabase(AbstractSourceFactory factory)
{
await FillMusclesFromDataStore(factory);
await FillExercisesFromDataStore(factory);
await FillMuscleExerciseAssosiations(factory);
}

calling all 3 in a sequence with one call from the outside, we are always sure that we called are methods correctly, and with this method being part of the IWorkoutStore interface we opened another ease of work for the future.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s