Design pattern to process different file types in OOP - file

I need to process a big set of files that at the moment are all loaded into memory on a List.
i.e:
List(FileClass) Files;
Use:
Reader.Files; //List of files of the type
File Class has one attribute to match each FileInfo object property i.e: Name,CreateDate,etc.
Also has a List of Lines of the type (LineNumber, Data).
Now I need to create an logic to interpret these files. They all have different logic interpreteations and they will be loaded on to their correspondent Business Object.
i.e:
Model model = new Model()
.emp => Process => Employee Class
.ord => Process => Order Class
model.AddObject(emp);
model.AddObject(ord);
My question what is the best design pattern for a problem of this sort.
All I can think of is... something like this:
public ProcessFiles(List<Files> Files)
{
Model model = new Model()
var obj;
foreach(file in Files)
{
switch (File.GetExtension(file))
{
case "emp":
obj = BuildEmployee(file) //returns Employee class type
break;
case "ord":
obj = BuildOrder(file) //returns Order class type
break;
}
model.AddObject(obj);
}
}
Is there a better way to approach this?
This solution looks procedural to me, is there a better Object Oriented Approach to it?
Cheers
UPDATE:
I've come across a few options to solve this:
1)- Use of Partial classes for separation of concerns.
I have a data model that I don't want to mix File processing, Database use, etc (Single Responsibility)
DATA MODEL:
public partial class Employee
{
public int EmployeeID;
public string FirstName;
public string LastName;
public decimal Salary;
}
INTERPRETER/FILE PARSER:
This partial class defines the logic to parse .emp files.
// This portion of the partial class to separate Data Model
from File processing
public partial class Employee
{
public void ProcessFile(string FileName)
{
//Do processing
}
...
}
Intepreter Object
public class Interpreter : IInterpreter
{
foreach(file in Files)
{
switch (fileExtension)
{
case .emp
Employee obj= new Employee();
case .ord
Order obj = new Order(file);
}
obj.ProcessFile(File)
Model.AddObject(emp)
}
}
2)- Perhaps using some sort of Factory Pattern...
The input is the file with an extension type.
This drives the type of object to be created (i.e: Employee, Order, anything) and also the logic to parse this file. Any ideas?

Well, it seems that you want to vary the processing behaviour based on the file type. Behaviour and Type being keywords. Does any behavioural pattern suit your requirement?
Or is it that the object creation is driven by the input file type? Then creation and type become important keywords.
You might want to take a look at strategy and factory method patterns.
Here is something from the book Refactoring to Patterns:
The overuse of patterns tends to result from being patterns happy. We
are patterns happy when we become so enamored of patterns that we
simply must use them in our code. A patterns-happy programmer may work
hard to use patterns on a system just to get the experience of
implementing them or maybe to gain a reputation for writing really
good, complex code.
A programmer named Jason Tiscione, writing on SlashDot (see
http://developers.slashdot.org/comments.pl?sid=33602&cid=3636102),
perfectly caricatured patterns-happy code with the following version
of Hello World. ..... It is perhaps impossible to avoid being patterns
happy on the road to learning patterns. In fact, most of us learn by
making mistakes. I've been patterns happy on more than one occasion.
The true joy of patterns comes from using them wisely.

Related

Use of Wrapper class for deserialization in callout?

I found the following use of a wrapper class, and was wondering if it is a good practice or whether its just duplication of code for no reason.
//Class:
public class SomeClass{
public Integer someInt;
public String someString;
}
//Callout Class:
public class CalloutClass{
public SomeClass someMethod(){
//...code to do a callout to an api
SomeClass someClassObj = (SomeClass)JSON.Deserialize(APIResponse.getBody(), SomeClass.class);
return someClassObj;
}
}
//Controller:
public class SomeController {
public SomeController(){
someClassObj = calloutClassObj.someMethod();
SomeWrapper wrapperObj = new SomeWrapper();
for(SomeClass iterObj : someClassObj){
wrapperObj.someWrapperInt = iterObj.someInt;
wrapperObj.someWrapperString = iterObj.someString;
}
}
public class someWrapper{
public Integer someWrapperInt{get;set;}
public String someWrapperString{get;set;}
}
}
The wrapper class "someWrapper" could be eliminated if we just use getters and setters ({get;set;}) in "SomeClass."
Could anyone explain if there could be a reason for following this procedure?
Thanks,
James
My assumption (because, code in controller is extra pseudo) is
SomeClass is a business entity, purpose of which is to store/work with business data. By work I mean using it's values to display it (using wrapper in controller), to calculate smth in other entities or build reports... Such kind of object should be as lightweight as possible. You usually iterate through them. You don't need any methods in such kind of objects. Exception is constructor with parameter(s). You might want to have SomeObject__c as parameter or someWrapper.
someWrapper is a entity to display business entity. As for wrapper classes in controllers. Imagine, that when you display entity on edit page and enter a value for someWrapperInt property, you want to update someWrapperString property (or you can just put validation there, for example, checking if it is really Integer). Usually, as for business entity, you don't want such kind of functionality. But when user create or edit it, you may want smth like this.

New to AutoFixture trying to get my head around it and I can't see it helping me

Currently, I'm using custom made fake objects that behind the scenes use NSubstitute which creates the actual objects but it's becoming very hard to maintain as the project grows, so I'm trying to find alternatives and I'm hoping that AutoFixture is the right tool for the job.
I read the documentation and I'm struggling because there's very little to no documentation and I read most of the blog posts by Mark Seemann including the CheatSheet.
One of the things that I'm having hard time to grasp is how to create an object with a constructor that have parameters, in my case I need to pass argument to CsEmbeddedRazorViewEngine as well as HttpRequestBase to ControllerContext.
The way I see it is that I need to create a fake objects and finally create a customization object that injects them to
I also looked into NBuilder it seems slightly more trivial to pass arguments there but I've heard good things about AutoFixture and I would like to give it a try. :)
I'm trying to reduce the amount of fake objects I have so here is a real test, how can I do the same thing with AutoFixture?
[Theory,
InlineData("en-US"),
InlineData("en-us"),
InlineData("en")]
public void Should_return_the_default_path_of_the_view_for_enUS(string language)
{
// Arrange
const string EXPECTED_VIEW_PATH = "~/MyAssemblyName/Views/Home/Index.cshtml";
CsEmbeddedRazorViewEngine engine = CsEmbeddedRazorViewEngineFactory.Create(ASSEMBLY_NAME, VIEW_PATH, string.Empty);
string[] userLanguage = { language };
HttpRequestBase request = FakeHttpRequestFactory.Create(userLanguage);
ControllerContext controllerContext = FakeControllerContextFactory.Create(request);
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, VIEW_NAME, false);
// Assert
RazorView razorView = (RazorView)result.View;
string actualViewPath = razorView.ViewPath;
actualViewPath.Should().Be(EXPECTED_VIEW_PATH);
}
P.S. I'm using xUnit as my testing framework and NSubstitute as my mocking framework should I install both AutoFixture.Xunit and AutoFixture.AutoNSubstitute?
UPDATE: After learning more and more about it I guess it is not the right tool for the job because I tried to replace my test doubles factories with AutoFixture rather than setting up my SUT with it.
Due to odd reason I thought it's doing the same thing NBuilder is doing and from what I can see they are very different tools.
So after some thinking I think I'll go and change the methods I have on my test doubles factories to objects then use AutoFixture to create my SUT and inject my test doubles to it.
Note: I don't have the source code for the CsEmbeddedRazorViewEngine type and all the other custom types.
Here is how it could be written with AutoFixture:
[Theory]
[InlineAutoWebData("en-US", "about", "~/MyAssemblyName/Views/Home/Index.cshtml")]
[InlineAutoWebData("en-US", "other", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view_for_enUS(
string language,
string viewName,
string expected,
ControllerContext controllerContext,
CsEmbeddedRazorViewEngine sut)
{
var result = sut.FindPartialView(controllerContext, viewName, false);
var actual = ((RazorView)result.View).ViewPath;
actual.Should().Be(expected);
}
How it works:
It uses AutoFixture itself together with it's glue libraries for xUnit.net and NSubstitute:
PM> Install-Package AutoFixture.Xunit
PM> Install-Package AutoFixture.AutoNSubstitute
With InlineAutoWebData you actually combine inline values and auto-generated data values by AutoFixture – also including Auto-Mocking with NSubstitute.
internal class InlineAutoWebDataAttribute : CompositeDataAttribute
{
internal InlineAutoWebDataAttribute(params object[] values)
: base(
new InlineDataAttribute(values),
new CompositeDataAttribute(
new AutoDataAttribute(
new Fixture().Customize(
new WebModelCustomization()))))
{
}
}
Remarks:
You could actually replace the WebModelCustomization customization above with AutoNSubstituteCustomization and it could work.
However, assuming that you are using ASP.NET MVC 4, you need to customize the Fixture instance with:
internal class WebModelCustomization : CompositeCustomization
{
internal WebModelCustomization()
: base(
new MvcCustomization(),
new AutoNSubstituteCustomization())
{
}
private class MvcCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<ControllerContext>(c => c
.Without(x => x.DisplayMode));
// Customize the CsEmbeddedRazorViewEngine type here.
}
}
}
Further reading:
Encapsulating AutoFixture Customizations
AutoData Theories with AutoFixture
I ended up doing this.
[Theory,
InlineData("en-US", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en-us", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view(string language, string viewName, string expected)
{
// Arrange
CsEmbeddedRazorViewEngine engine = new CsEmbeddedRazorViewEngineFixture();
ControllerContext controllerContext = FakeControllerContextBuilder.WithLanguage(language).Build();
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, viewName, false);
// Assert
string actualViewPath = ((RazorView)result.View).ViewPath;
actualViewPath.Should().Be(expected);
}
I encapsulated the details to setup my SUT into a fixture and used the builder pattern to handle my fakes, I think that it's readable and pretty straightforward now.
While AutoFixture looks pretty cool, the learning curve seems long and I will need to invest enough time to understand it, for now, I want to clean-up my unit tests and make them more readable. :)

JCR, JackRabbit : Making XPath for search for a Year of a Date and for subnodes properties values

Grettings!.
I am having too much troubling with the following question... i will try to be as clear as possibly.
Currently i have a Jackrabbit JCR implementation running in our web application. All things works fine, buts just a little (big) problem appears when trying to do some specific search.
For a brief synopsis of what kind of data is stored, we have 3 a node class called "Entry", that extends another node class named "BaseEntry" and that extends another called "BaseNode".
The Entry class represents a Node in our JCR system, and has a set of properties (mapped as attributes in the corresponding class), an also inherits the properties mapped in their superclasses as well.
I copy and paste, the important part of the class definition and the properties of interest...
#Node(jcrType = "entry", extend = BaseEntry.class)
public class Entry extends BaseEntry {
... // nothing really important here
}
#Node(jcrType = "baseEntry", extend = BaseNode.class, isAbstract = true)
public abstract class BaseEntry extends BaseNode {
#Collection (jcrType = "attachment",
collectionConverter = NTCollectionConverterImpl.class)
protected List<Attachment> attachments = new ArrayList<Attachment>();
...
}
#Node(jcrType = "baseNode", isAbstract = true)
public abstract class BaseNode {
#Field(jcrName = "name", id = true)
protected String name;
#Field(jcrName = "creationDate")
protected Date creationDate;
...
}
1) How i can make a predicate for select only those nodes (entries) that have a specific year in the property creationDate ignoring the rest. The attribute is of type Date (in the class) and i guess the property is stored in a xs:DateTime format i guess... i really do not know very well... how it really match a Date in the JCR underlying system.
So far i get to this...
there must something like this //element(*, entry)[getYear(#creationDate) == <year>]
must be an integer, string, ... i really don't kwow.
2) How i can make a predicate for select only those nodes (entries) that contains attachments that have name a certain name.
Again the class Attachment, the important part...
#Node(jcrType = "attachment", discriminator = true)
public class Attachment extends BaseNode implements Comparable<Attachment> {
...
}
So far i get to this.. that is working.. but there must be a better way:
//element(*, entry) [jcr:contains(./*,'<nameOfInterest>')]
That all friends, i really apologies for the absent of information that i reader may require to understand better the background of the matter, i guess this is what i can do. I am pretty new to Jackrabbit and JCR, and i have to get the hands (dirty) on it, without knowing very well what i am doing.. and obliviously it began to be very complicated...
Well hope any charity soul can answer this, and help, at least a little :D.
Thanks for advance.
Greetings.
Víctor.
I'm not an expert, but I try to answer anyway:
Question 1
//element(*, entry)[getYear(#creationDate) == <year>]
I think you could use:
//element(*, entry)[
#creationDate >= '2001-01-01T00:00:00.0'
and #creationDate < '2002-01-01T00:00:00.0']
Question 2
Select only those nodes (entries) that contains attachments that have name a certain name.
I only know the SQL-2 query, using equality on the node name. I'm not sure if this is what you are looking for:
select * from [nt:base] where name() = '<nameOfInterest>'

unit test to verify that a repository loads an entity from the database correctly

I have a simple standard repository that loads a composite entity from the database. It injects all dependencies it need to read the complete entity tree from a database through IDbConnection (wich gives the repository access to IDbCommand, IDbTransaction, IDataReader) that I could mock.
public class SomeCompositionRootEntityRepository :
IRepository<SomeCompositionRoot>
{
public RecipeRepository(IDbConnection connection) { ... }
public void Add(SomeCompositionRootEntity item) { ... }
public bool Remove(SomeCompositionRootEntity item) { ... }
public void Update(SomeCompositionRootEntity item) { ... }
public SomeCompositionRootEntity GetById(object id) { ... }
public bool Contains(object id) { ... }
}
The question is how would I write unit test for this in a good way? If I want to test that the reposity has read the whole tree of objects and it has read it correcty, I would need to write a hughe mock that records and verifies the read of each and every property of each and every object in the tree. Is this really the way to go?
Update:
I think I need to refactor my repository to break the repository functionality and unit test into smaller units. How could this be done?
I am sure I do not want to write unit test that involve reading and writing from and to an actual database.
The question is: What functionality do you want to test?
Do you want to test that your repository actually loads something? In this case I would write a few (!) tests that go through the database.
Or do you want to test the functionality inside the repository methods? In this case your mock approach would be appropriate.
Or do you want to make sure that the (trivial) methods of your repository aren't broken? In this case mocks and one test per method might be sufficient.
Just ask yourself what the tests shall ensure and design them along this target!
I think I understand your question so correct me if I'm wrong...
This is a where you cross the line from unit to integration. The test makes sense (I've written these myself), but you're not really testing your repository, rather you're testing that your entity (SomeCompositionRoot) maps correctly. It isn't inserting/updating, but does involve a read to the database.
Depending on what ORM you use, you can do this a million different ways and typically its fairly easy.
::EDIT::
like this for linq for example ...
[TestMethod]
public void ShouldMapBlahBlahCorrectly()
{
CheckBasicMapping<BlahBlah>();
}
private T CheckBasicMapping<T>() where T : class
{
var target = _testContext.GetTable<T>().FirstOrDefault();
target.ShouldNotBeNull();
return target;
}

How to use definitions stored in a DB to definitions in your source code?

I would like to get some ideas how to use definitions which are stored in a DB (which is used by your application) into the source code of the application.
Example:
Database
Cars
CarTypeDefinitions
A column of Cars links by a foreign key to a row in CarTypeDefinitions, therefore defines the type of the car which is contained in Cars.
Cars contains entries like 'Aston Martin DB8', 'Range Rover' and 'Mercedes Actros'.
CarTypeDefinitions contains entries like 'Sports car', 'SUV' and 'Truck'.
Source code
Now I would like to be able to use these definitions in my source code as well. So somehow we need to create some kind of mapping between a row in the CarTypeDefinitions table and a (preferably) type-safe implementation in the source code.
One possible implementation
The first thing which comes to my mind (and I am especially looking for other solutions or feedback on this one) would be to create an Enum ECarTypeDefinitions.
public enum ECarTypeDefinitions
{
SportsCar = 1,
SUV = 2,
Truck = 3
}
Now that we have a type-safe Enum we can use it e.g. like this:
public bool IsSportsCar(Car currentCar)
{
return (currentCar.CarType == ECarTypeDefinitions.SportsCar);
}
The contents of that enum would be auto-generated from the contents of the CarTypeDefinitions table (add two additional columns for name of the enum and its integer value).
This would also work the other way, e.g. generate the content of the CarTypeDefinitions DB table from the ECarTypeDefinitions Enum.
I'm keen to hear about other ways how to tackle this problem. How have you dealt with this?
I do it the way you have suggested. Some others prefer to combine all constants into a "Lookup" table. You can look at an example of some of the pros and cons here: http://weblogs.foxite.com/andykramek/archive/2009/05/10/8419.aspx
Edit: Here's a thought that may help spark further ideas from you.
Create a class for each Car Type:
public class SportsCarType
{
}
Now add an attribute to CarTypeDefinition:
public class CarTypeDefinition
{
...
public string typeName;
}
Populate the new attribute (for each type you have) using typeof:
...
carTypeDefinition.typeName = typeof(SportsCarType).Name;
...
Finally your new IsSportsCar method:
public bool IsSportsCar(Car currentCar)
{
return (currentCar.CarType.typeName == typeof(SportsCarType).Name);
}
I'm not familiar with Entity Framework so perhaps it has a way to allow this kind of thing to be more cleanly done. Also a little rusty on C#.

Resources