Object that is needed throughout the application - c#

I have an application that gets some data from the user when the application loads and is needed throughout the application, what is the best way to keep hold of the object that holds this data throughout the entire lifetime of the application?
This data needs to be available to most other objects created during the lifetime of the application.
I learnt the other day that Singletons are not necessarily a good idea. Especially in multi threaded environments, which my application is.
I have been using Singletons to handle this problem, but I wondered if this is a good way to deal with this?
EDIT:
Let me elobarate: I'm asking for username and password when the application starts, now I know keeping a password in-memory is out security and bad practice, but throughout the logon process there is quite a few places I need this data to check various things, so this is where I used a Singleton.

I'd advise against using a class that defines its own singleton just because that usually means you'll have pains during unit testing.
If you use a generic singleton, you'll have the same functionality, but with added benefits later on when testing / moving away from the singleton pattern (going multi-users for example).
Note that the singleton is initialized with a delegate. The rationale here is that the delegate will only be called once, even if two threads are somehow registering the singleton at the same time...
Using an interface makes your life easier when writing unit tests as you can mock the part of the singleton you are interested in for your test (or your ultra quick - 2 minutes before demoing to the CEO patch/debugging session).
It might be overkill for storing a login/pass tuple, but this pattern saved my bacon more times than I care to count.
public static class Singleton<T>
{
private static T instance;
private static readonly object sync = new object();
static bool registered = false;
public static T Instance
{
get
{
return instance;
}
}
public static void Register(Func<T> constructor)
{
lock (sync)
{
if (!registered)
{
instance = constructor();
registered = true;
}
}
}
}
class Demo
{
class Data
{
public string Pass { get; set; }
public string Login { get; set; }
}
void SimpleUsage()
{
string login = "SEKRIT";
string pass = "PASSWORD";
// setup
Singleton<Data>.Register(() => new Data { Login = login, Pass = pass });
//
var ltCommander = Singleton<Data>.Instance;
}
/// <summary>
/// Using an interface will make the singleton mockable for tests!
/// That's invaluable when you'll want to fix something FAST without running the whole app!
/// </summary>
interface IData
{
string Login { get; }
string Password { get; }
}
class UnitTestFriendlyData : IData
{
public UnitTestFriendlyData(string login, string password)
{
Login = login;
Password = password;
}
public string Login { get; private set; }
public string Password { get; private set; }
}
void SmarterUsage()
{
// same setup, but through the interface.
Singleton<IData>.Register(() => new UnitTestFriendlyData("login", "pass"));
// and same for the retrieval
var data = Singleton<IData>.Instance;
}
void UnitTestSetupWithMoq()
{
// Register a mock.
var mock = new Mock<IData>();
mock.SetupProperty(x => x.Login, "Login");
mock.SetupProperty(x => x.Pass, "Pass");
Singleton<IData>.Register(() => mock.Object);
// and same for the retrieval
var data = Singleton<IData>.Instance;
}
}

See this for some explanations
Implementing Singleton in C# , looking at Multithreaded Singleton.
Also Ist way of implementing Singleton Pattern in C#: looking at IIIrd way of implementing Singleton Pattern in C#: Simple Multithreaded Singleton Pattern and IVth way of implementing Singleton Pattern in C#: Multithreaded Singleton Pattern

In this case, a singleton is the proper choice. You just don't want to start shoving in a lot of unrelated stuff in there -- you want the class to remain cohesive and not just a "bag of properties" that sits around. As far as multithreading goes, you can put the appropriate controls on your singleton class, no problem. What types of locks and protections you use, however, is specific to your implementation (there's not enough detail in your question to answer that, though).

My first reaction to this is that if you have a piece of data that is required by most other types in the application, you may want to encapsulate it better. It sounds like a violation of the Single Responsibility Principle. However, without knowing more about your scenario, it difficult to say what the remedy could be.

From the way you described your situation, it sounds like you just want to save off a string once at startup and then it would always just be read-only everywhere else. If this is the case, you can really just do something like:
internal static class LoginInfo
{
internal static string Username;
internal static string Password;
}
Then from anywhere in your app you can just say:
var usr = LoginInfo.Username;
var pwd = LoginInfo.Password;
Now i'm sure everyone will comment that is is a terrible design practice, but I'm prepared to live with that :)
Now if you plan on changing the value all the time, and if this wasn't just a string and was instead some more complex object, then thread-safety could certainly become an issue. You could always make a thread-safe getter on a property.

The reason people say that a Singleton isn't necessarily a good idea is because it encourages a scenario like yours. Needing a static object is the bad part - a Singleton is just seen as an enabler.
That said, I can't really comment on whether it's neccesary in your application, because you haven't detailed it. But if you REALLY need static data held in an object for the application's lifetime, go right ahead and use a singleton.
You can make them thread-safe as well.

Related

Decorator pattern mess

I'm having a problem figuring out if I'm using the decorator pattern the right way. Let's suppose I'm working on a console application. In this application I have defined a simple IConfigPathProvider interface, which will provide a configuration file path to some class.
public interface IConfigPathProvider
{
string GetConfigPath();
}
The path is stored in the appSettings section of the console application's app.config file.
public class AppSettingsConfigPathProvider : IConfigPathProvider
{
public string GetConfigPath()
{
return System.Configuration.ConfigurationManager.AppSettings["configPath"];
}
}
The thing is this path is also encrypted, so...
public class DecryptingConfigPathProvider : IConfigPathProvider
{
private readonly IConfigPathProvider _provider;
private readonly IStringDecrypter _decrypter;
public DecryptingConfigPathProvider(IConfigPathProvider provider,
IStringDecrypter decrypter)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
_decrypter = decrypter ?? throw new ArgumentNullException(nameof(decrypter));
}
public string GetConfigPath()
{
var path = _provider.GetConfigPath();
//decrypting method of IStringDecrypter interface
return _decrypter.DecryptString(path);
}
}
But, wait: it's not over. I have to add a specific portion to the path to get it right.
public class AppendSectionConfigPathProvider : IConfigPathProvider
{
private readonly IConfigPathProvider _provider;
public AppendSectionConfigPathProvider(IConfigPathProvider provider)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
}
public string GetConfigPath()
{
var path = _provider.GetConfigPath();
return System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(path),
"section",
System.IO.Path.GetFileName(path));
}
}
And now - why not? - let's add some logging.
public class LoggingConfigPathProvider : IConfigPathProvider
{
private readonly static ILog _log =
LogManager.GetLogger(typeof(LoggingConfigPathProvider));
private readonly IConfigPathProvider _provider;
public LoggingConfigPathProvider(IConfigPathProvider provider)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
}
public string GetConfigPath()
{
_log.Info("Getting config path...");
var path = _provider.GetConfigPath();
_log.Info("Config path retrieved successfully!");
return path;
}
}
Divide et impera
Of course the instant outcome is the separation of concerns, BUT what about the added complexity in instantiating the object? You need to know which decorator comes first and in which order they should be chained, otherwise you'll end up with a buggy IConfigPathProvider.
new LoggingConfigPathProvider(
new AppendSectionConfigPathProvider(
new DecryptingConfigPathProvider(
new AppSettingsConfigPathProvider(),
decrypter));
And this is just a simple provider. In a rather complex application you'd likely come across multiple components with multiple references...this could easily led to a maintenance nightmare. Now, is this a well-known drawback or I'm just using this pattern in the wrong way?
This is a well-known drawback. The GoF mentions the following liability of the Decorator Pattern.
Lots of little objects. A design that uses Decorator often results in systems
composed of lots of little objects that all look alike. The objects differ only
in the way they are interconnected, not in their class or in the value of
their variables. Although these systems are easy to customize by those who
understand them, they can be hard to learn and debug.
You're not necessarily correct. Rather than decorating object right away, keep some kind of a decoration shema, validatable, lazy, which can be converted into needed (final, ready-to-use) object by calling, let say, .Build(). Just a code sketch: obj.DecorateWith<Decorator1>().DecorateWith<Decorator2>().DecorateWith(() => new Decorator3(IContainer.Resolve<SomeWhatArgument> ...).Build(). It makes things definitely harder, however as long as decorating is right way to go and your project is indeed big enough to benefit from such a high abstraction, it will solve your problem.

Simpler Singleton Pattern

I have been reviewing some code of some old projects and I found a singleton there. It is a requirement to use a singleton and I was thinking of a way to make it look "simpler" when using.
I found, it would be easier to access the methods and properties like a static class. So I basically implemented a singleton using static methods to skip the requirement to use GetInstance(). This is how I implemented it:
public class ExampleSingleton
{
string someRequiredValue = "This is an example.";
/// <summary>
/// Private Constructor
/// </summary>
private ExampleSingleton() { }
private static volatile ExampleSingletoninstance;
/// <summary>
/// !!! PRIVATE !!!
/// Instance Property.
/// Returns the instance of this singleton.
/// (ThreadSafe)
/// </summary>
private static ExampleSingleton Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
{
instance = new ExampleSingleton();
}
}
}
return instance;
}
}
/// <summary>
/// Example field contains a value that should be
/// accessible from outside.
/// </summary>
public static string SomeRequiredField
{
get
{
// Here you do the job you would have to do "outside"
// of the class normally.
return ExampleSingleton.Instance.someRequiredValue;
}
}
// Helper for a secure thread synchronisation.
private static object _lock = new object();
}
So when you want to access the singleton values you can just do it like this:
// Access the values like this
string requiredField = ExampleSingleton.SomeRequiredField;
// Instead of this
string requiredField = ExampleSingleton.Instance.SomeRequiredField;
// Or even this
string requiredField = ExampleSingleton.GetInstance().SomeRequiredField;
Am I violating the principles of the singleton pattern here? It basically is still a singleton pattern but the work of getting the instance is done internally. What could be the con's of this example? Are there other pro's?
Thanks
In terms of cons, there are two that have bitten me in the past:
It's hard to mock the singleton due to the fact that the getters are static
Changes to the singleton interface need 2 separate changes (one for the public static, one for the internals).
Namely, I think that this:
ExampleSingleton.Instance.SomeRequiredField
Is easier to mock simply because you would need to replace/revert the Instance field. Questions pop up from time to time around "how to mock static this or that" probably due to classes like the one you posted:
How to mock with static methods?
Mocking Static methods using Rhino.Mocks
In general, a singleton pattern in C# is probably not the best idea due to the fact that they are harder to mock in general, unless you make the constructor public or use a ioc container, but if you need one, having the instance getter is probably easier to test in general.
Second point is more around incremental maintenance cost of code. Basically to "add to the class" you have two points of code that must be changed:
class ExampleSingleton
{
... existing code ...
public static int ComputeComplicatedMethod()
{
return ComputeComplicatedMethodImplementation();
}
private int ComputeComplicatedMethodImplementation()
{
// really complex code.
}
}
So you've essentially added an extra layer of abstraction for every new field versus just once for a get instance field. Either that or you have a static method that uses the internal static singleton like so:
class ExampleSingleton
{
... existing code ...
public static int ComputeComplicatedMethod()
{
// use ExampleSingletonInstance here
}
}
Which is really no better than just having a static class with static methods. A better question is why isn't the Singleton pattern implemented with just a static class? That might be better explained here: http://www.dotnetperls.com/singleton-static
I think you have to choose the solution with the least code (but it looks like people likes to wrote a bunch of useless code, so you may have difficulty to explain what is your point).
Use a static access to a property like in your example save you a word:
string requiredField = ExampleSingleton.SomeRequiredStuff;
vs
string requiredField = ExampleSingleton.Instance.SomeRequiredStuff;
But you have to wrote the getter for this property.
Also if you have a lot of properties it became an issue: you have to wrote a lot of static getter.
And this is not standard and go against OOP spirit: you handle the property of an object, so get the object then the property.
Also if your value is invariable, it is not a property!, the habit is to put the field const and public. Like ulong.MaxValue.
Doing this for the methods look like a bad idea. (and again in OOP, method belong to objects). If you don't want to have anything static you will have to build static functions that call the non-static ones. It will be not pleasant to maintain.

Is it a good design option to call a class' initializing method within a factory before injecting it

I am in the process of refactoring a rather large portion of spaghetti code. In a nutshell it is a big "God-like" class that branches into two different processes depending in some condition. Both processes are lengthy and have lots of duplicated code.
So my first effort has been to extract those two processes into their own classes and putting the common code in a parent they both inherit from.
It looks something like this:
public class ExportProcess
{
public ExportClass(IExportDataProvider dataProvider, IExporterFactory exporterFactory)
{
_dataProvider = dataProvider;
_exporterFactory = exporterFactory;
}
public void DoExport(SomeDataStructure someDataStructure)
{
_dataProvider.Load(someDataStructure.Id);
var exporter = _exporterFactory.Create(_dataProvider, someDataStructure);
exporter.Export();
}
}
I am an avid reader of Mark Seemann's blog and in this entry he explains that this code has a temporal coupling smell since it is necessary to call the Load method on the data provider before it is in a usable state.
Based on that, and since the object is being injected to the ones returned by the factory anyway, I am thinking of changing the factory to do this:
public IExporter Create(IExportDataProvider dataProvider, SomeDataStructure someDataStructure)
{
dataProvider.Load(someDataStructure.Id);
if(dataProvider.IsNewExport)
{
return new NewExportExporter(dataProvider, someDataStructure);
}
return new UpdateExportExporter(dataProvider, someDataStructure);
}
Because of the name "DataProvider" you probably guessed that the Load method is actually doing a database access.
Something tells me an object doing a database access inside the create method of an abstract factory is not a good design.
Are there any guidelines, best practices or something that say this is effectively a bad idea?
Thanks for your help.
Typically, a factory is used to resolve concrete types of a requested interface or abstract type, so you can decouple consumers from implementation. So usually a factory is just going to discover or specify the concrete type, help resolve dependencies, and instantiate the concrete type and return it. However, there's no hard or fast rule as to what it can or can't do, but it is sensible to give it enough access to only to resources that it needs to resolve and instantiate concrete types.
Another good use of a factory is to hide from consumers types dependencies that are not relevant to the consumer. For example, it seems IExportDataProvider is only relevant internally, and can be abstracted away from consumers (such as ExportProcess).
One code smell in your example, however, is how IExportDataProvider is used. The way it currently seems to work, you get an instance of it once, but it's possible to change its state in subsequent usages (by calling Load). This can lead to issues with concurrency and corrupted state. Since I don't know what that type does or how it's actually used by your IExporter, it's hard to make a recommendation. In my example below, I make an adjustment so that we can assume that the provider is stateless, and instead Load returns some sort of state object that the factory can use to resolve the concrete type of exporter, and then provide data to it. You can adjust that as you see fit. On the other hand, if the provider has to be stateful, you'll want to create an IExportDataProviderFactory, use it in your exporter factory, and create a new instance of the provider from the factory for each call to exporter factory's Create.
public interface IExporterFactory
{
IExporter Create(SomeDataStructure someData);
}
public class MyConcreteExporterFactory : IExporterFactory
{
public MyConcreteExporterFactory(IExportDataProvider provider)
{
if (provider == null) throw new ArgumentNullException();
Provider = provider;
}
public IExportDataProvider Provider { get; private set; }
public IExporter Create(SomeDataStructure someData)
{
var providerData = Provider.Load(someData.Id);
// do whatever. for example...
return providerData.IsNewExport ? new NewExportExporter(providerData, someData) : new UpdateExportExporter(providerData, someData);
}
}
And then consume:
public class ExportProcess
{
public ExportProcess(IExporterFactory exporterFactory)
{
if (exporterFactory == null) throw new ArgumentNullException();
_exporterFactory = factory;
}
private IExporterFactory _exporterFactory;
public void DoExport(SomeDataStructure someData)
{
var exporter = _exporterFactory.Create(someData);
// etc.
}
}

DataContext in static class in desktop application

i am using 3 tier architecture in my winform application so i have static class which handle the operation of equipment
public static class Equipments
{
public static void AddEquipment(string name, decimal dimLength)
{
DBClassesDataContext db = new DBClassesDataContext();
Equipment equipment = new Equipment();
equipment.Name = name;
equipment.DimLength = dimLength;
db.Equipments.InsertOnSubmit(equipment);
db.SubmitChanges();
}
public static void UpdateEquipment(int equipmentID, string name, decimal dimLength)
{
DBClassesDataContext db = new DBClassesDataContext();
Equipment oldEquipment;
oldEquipment = db.Equipments.Where("EquipmentID = #0",equipmentID).SingleOrDefault();
oldEquipment.Name = name;
oldEquipment.DimLength = dimLength;
db.SubmitChanges();}
so my questions are :
Do i need to create instance of DBClassesDataContext in each method ?
because when i done global static DBClassesDataContext it didn't work correctly.
Is there any better way to handle DBClassesDataContext instead to create it each time inside the method (like create new DBClassesDataContext each time i run a method from this class)
Thanks
Do i need to create instance of DBClassesDataContext in each method?
You should do, absolutely - just like you should normally create a new SqlConnection each time you want to access the database in non-LINQ code. In general, avoid global state - it's almost always a bad idea.
There is any better way to handle DBClassesDataContext instead to create it each time inside the method
No - that's exactly the right approach. Why would you try to avoid just creating it each time?
Even though I'll probably get stoned to death for disagreeing with the Jon Skeet, I'll post this anyway.
You definitely don't need to create the instance in every single method, or at least not like this. There's a principle I like to follow called DRY - don't repeat yourself, and repeating the same line over and over, that can be avoided, clearly violates this principle.
You have multiple options here:
1.) define the methods as instance methods, maybe something like this:
internal class MyDbActions
{
private MyDbContext _myDbContext;
private MyDbContext Db
{
get
{
if (_myDbContext == null) _myDbContext = new MyDbContext();
return _myDbContext;
}
}
internal void Add(SomeClass c)
{
Db.Table.AddObject(c);
Db.SubmitChanges();
Db.Dispose();
}
}
Or something like that, you get the idea. This can be modified to whatever you need.
2.) use can use dependency injection for your methods, so consider something like this:
public static class Equipments
{
public static void AddEquipment(DBClassesDataContext db, string name, decimal dimLength)
{
Equipment equipment = new Equipment();
equipment.Name = name;
equipment.DimLength = dimLength;
db.Equipments.InsertOnSubmit(equipment);
db.SubmitChanges();
}
}
You'd manage your datacontext outside this class.
3.) you can utilize the Repository pattern, Unit of work pattern and IoC. I won't post the example code here, because it's quite lengthy, but here's one link to give you an idea:
Repository pattern with Linq to SQL using IoC, Dependency Injection, Unit of Work

What methods should go in my DDD factory class?

I am struggling to understand what my factory class should do in my DDD project. Yes a factory should be used for creating objects, but what exactly should it be doing. Consider the following Factory Class:
public class ProductFactory
{
private static IProductRepository _repository;
public static Product CreateProduct()
{
return new Product();
}
public static Product CreateProduct()
{
//What else would go here?
}
public static Product GetProductById(int productId)
{
//Should i be making a direct call to the respoitory from here?
Greener.Domain.Product.Product p = _repository.GetProductById(productId);
return p;
}
}
Should i be making a direct call to the repository from within the factory?
How should i manage object creation when retriving data from a database?
What do i need to make this class complete, what other methods should i have?
Should i be using this class to create the Product object from the domain and repository from right?
Please help!
Should i be making a direct call to
the repository from within the
factory?
No, don't use a factory when your retrieving stuff, use a factory only when you are creating it for the first time.
How should i manage object creation
when retriving data from a database?
Pass that data into the factory, if it is required for the object's initial creation.
What do i need to make this class
complete, what other methods should i
have?
Many factories are not even individual classes, they are just methods that provide object creation. You could fold the factory method into another class, if you felt like it was just going to call a parameterless constructor.
Should i be using this class to create
the Product object from the domain and
repository from right?
The repository is for getting (in a sense creating) existing objects, the factory is for the first time you create an object.
Initially many factories won't do much except call a constructor. But once you start refactoring and/or creating larger object hierarchies, factories become more relevant.
Explanation and Example:
For instance, in the project I'm working on I have an excel processor base class and many subclasses implementing that base class. I use the factory to get the proper one, and then call methods on it, ignorant of which subclass was returned.(Note: I changed some variable names and gutted/altered a lot of code)
Processor base class:
public abstract class ExcelProcessor
{
public abstract Result Process(string ExcelFile);
}
One of the Processor subclasses:
public class CompanyAExcelProcessor : ExcelProcessor
{
public override Result Process(string ExcelFile)
{
//cool stuff
}
}
Factory:
public static ExcelProcessor CreateExcelProcessor(int CompanyId, int CurrentUserId)
{
CompanyEnum company = GetCompanyEnum(CompanyId);
switch (company)
{
case CompanyEnum.CompanyA:
return new CompanyAExcelProcessor();
case CompanyEnum.CompanyB:
return new CompanyBExcelProcessor();
case CompanyEnum.CompanyC:
return new CompanyCExcelProcessor(CurrentUserId);
//etc...
}
}
Usage:
ExcelProcessor processor = CreateExcelProcessor(12, 34);
processor.Process();
Be carefull, there are two reasons to instantiate a new object : Creating it and rehydrating it from the database.
The first case is handled by the factory. You can provide several methods to create an object on the factory.
Factory methods should return valid objects, so you can pass parameters to these methods to provides required information.
The factory method can also chose the actual type to instantiate based on parameters.
You should not mix this with rehydrating from the database. This kind of instantiation should take values from the datarow and instantiate the object with it. I usualy call this a data builder instead of a factory.
The main difference is that the factory will instantiate an object with a new identity while the databuilder will instantiate an object with an already existing identity.
What should go in your factory's Create method is whatever is necessary to put a brand spanking new object into a VALID state.
Now, for some objects that means you won't do anything except this:
public Product Create()
{
return new Product();
}
However, you may have business rules, default settings, or other requirements that you want to enforce when an object is created. In that case, you would put that logic in that method.
And that's part of the benefit of the Factory. You now have one and only one place where that special logic resides, and only one place where a new object gets created.
I personally would use the factory in couple of circumstances:
1) Something elsewhere governs what type of objects this factory returns (ie. it can return objects depending on circumstances. For example return a stub object when I am testing, return an actual implementation when I am not (this is obviously more of Inversion of Control / Dependency Injection issue - but if you do not want to add containers to your project just yet)).
2) I have quite complex objects that have containers, dependencies, other relation etc. and they need to be built carefully to avoid creating null or meaningless references. For example if I have a Schedule object I may need some start, end date fields set - if the logic for retrieving, figuring out these date is complex enough I may not want the calling class to know about it and just call the default factory method that created the schedule object.
Hope this helps.
In the example given above, I'm a little unclear on the distinction between your factory and the repository. I wonder if you shouldn't simply add CreateProduct as a method to the repository, and using DI to push the repository into code that needs it? If the factory isn't doing anything, etc...
Or if you just want it to act as a globally registered repository, perhaps something like:
public static IFooRepository Default {get;private set;}
public static void SetRepository(IFooRepository repository) {
Default = repository;
}
(in my mind it seems clearer to separate the "set" in this case, but you don't have to agree)
and have the callers use var product = YourFactory.Default.CreateProduct(); etc
#ThinkBeforeCoding - in #m4bwav's example, the factory is getting a valid ID from a helper method, but it's not creating a new record in a persistence layer anywhere. If, however, I'm using a database auto-generated identity column as my identities, it seems like a factory would have to call into the repository to do the initial object creation. Can you comment on which method is "correct"?
In the builder you can have any logic you need to inforce the invariants on your entites, a little example using Java as development language...
I have a User entity that has a username, a password and an email, all attributes required so I have:
public class User {
private String username;
private String password;
private String email:
/**
* #throws IllegalArgumentException if the username is null, the password is null or the
* email is null.
*/
public User(final String theUsername, final String thePassword, final String theEmail) {
Validate.notNull(theUsername);
Validate.notNull(thePassword);
Validate.notNull(theEmail);
this.username = theUsername;
this.password = thePassword;
this.email = theEmail;
}
// Getters / Setters / equal / hashCode / toString
}
and then I have the UserBuilder:
public class UserBuilder {
private String username;
private String password;
private String email;
public UserBuilder withUsername(final String theUsername) {
Validate.notNull(theUsername);
this.username = theUsername;
return this;
}
public UserBuilder withPassword(final String thePassword) {
Validate.notNull(thePassword);
this.password = thePassword;
return this;
}
public UserBuilder withEmail(final String theEmail) {
Validate.notNull(theEmail);
this.email = theEmail;
return this;
}
public User build() {
User user = new User(this.username, this.password, this.email);
return user;
}
}
And you can use the builder like this:
UserBuilder builder = new UserBuilder();
try {
User user = builder.withUsername("pmviva").withPassword("My Nifty Password").withEmail("pmviva#somehost.com").build();
} catch (IllegalArgument exception) {
// Tried to create the user with invalid arguments
}
The factory's solely purpose is th create valid instances of objects. In order not to duplicate creation and hydration code you can have your repositories to query a rowset from the database and delegate the creation of the object to a builder passing the rowset's data.
Hope this helps
Thanks
Pablo

Categories

Resources