Passing HttpFileCollectionBase to the Business Layer - Bad? - asp.net-mvc-2

hopefully there's an easy solution to this one.
I have my MVC2 project which allows uploads of files on certain forms. I'm trying to keep my controllers lean, and handle the processing within the business layer of this sort of thing.
That said, HttpFileCollectionBase is obviously in the System.Web assembly.
Ideally I want to call to something like:
UserService.SaveEvidenceFiles(MyUser user, HttpFileCollectionBase files);
or something similar and have my business layer handle the logic of how and where these things are saved.
But, it feels a little icky to have my models layer with a reference to System.Web in terms of separation of concerns etc.
So, we have (that I'm aware of) a few options:
the web project handling this, and my controllers getting fatter
mapping the HttpFileCollectionBase to something my business layer likes
passing the collection through, and accepting that I reference System.Web from my business project
Would love some feedback here on best practice approaches to this sort of thing - even if not specifically within the context of the above.

I'd just use a custom model binder if you want to keep the logic out of your controllers - then you can stick the extracted data into the model which you can do what you want with.
http://www.heartysoft.com/post/2010/05/06/ASPNET-MVC-ModelBinding-Multiple-File-Uploads-to-an-Array.aspx
Clarification - I consider model binders and other interception techniques to be a convenient way of splitting logic out of controllers and into separately maintainable containers - this is infrastructure code/web logic and thus does not belong in the business logic and thus can reference System.Web etc happily.
Clarification - Effectively this is your Option 2 in disguise, you use model binders to map the unfriendly data into something the rest of your code can recognise, but you do it in a way that doesn't compromise your clean controllers.

assuming you can't easily mock up HttpFileCollectionBase you could pass in something like Dictionary<String, MyFile> where MyFile wraps HttpPostedFile. if HttpFileCollectionBase can easily be mockable for unit tests i see no point.

Related

Unity3D: Manage messy code

I am writing my main manager script for my game. I seems like the script handles 10+ huge if..else..if..else statements. It looks messy and hard to manage. And in monodevelop I am not able to minimise particular parts of code like we can do in eclipse.
I am considering of creating individual script for each part and enable-access-disable it from a common script.
Please direct me to the better ways to do?
In the best case every method or class should have one responsibility, and only one.
Try to extract duplicate code into methods
Try to split up your classes, so that each class does only one thing
Advanced: organize your classes in layers (Model-View-Control) and only talk to other classes through interfaces
share some code structure. it is a good practice to encapsulate blocks of code that perform a particular task into functions that accept parameters,
eg ( myFunction(param1, param2, param3){} )
if you ever have to reuse the code block you merely call the function and have it return the necessary values.

Stubbing & mocking in PHPUnit in a Zend Framework application

I am new to the Zend Framework and PHPUnit. I am transforming a legacy application to a MVC architecture and am trying to write unit tests. I am somewhat familiar with unit testing concepts but am stuck with stubbing and mocking in general. For instance consider the following
In a controller action I am trying to test I pass in a member ID. I then initialize a member object using the ID. Then I call a number of methods associated with the member object and assign the return values to the view objects.
class A extends Zend_Controller_Action {
public function viewAction() {
$member = new Member($this->getRequest()-> getParam('id'));
//perform various calls on the member object
$gender = $member->getGender();
...
//assign the return values to the view object
$this->view->assign('gender',$gender);
...
}
}
How do I mock the $member variable in my tests so that I can customize the methods return values?
If my understanding here is incorrect I would greatly appreciate some guidance.
Thank you!
If I understand you correctly, you're writing a test for this action. In that case it's impossible to mock $member since the new instance is created inside the method. That's why we're all striving to float as many of our new statements as far up in the object graph as possible (DI).
Generally there is the special PHPunit testcase Zend_Test_PHPUnit to test your controllers.
But it is, as a matter of fact, very hard or even impossible to test ZF controllers correctly (meaning with full isolation). You'd be better of to test the rest of your app, your general library, etc.
In other words, in the ZF1 logic, the controller is the central wiring place (after the bootstrap), where a lot of new statements are traditionally used. Obviously that leads to non-testability because every instance which is created instead of injected, is unmockable.
As #vascowhite pointed out, it is also generally good to strive for lean controllers. This means, move as much logic as possible to your model layer. This will lead to less redundance (DRY) and better testability at the same time.
But pay attention not to bloat your models either. At one point you will probably want to factor some code out into additional components.
An additional problem is that you can't mock the Front Controller either since it's a singleton. So you really don't have many options to test such an action. The only option would be to inject the member instance or get it from the registry (not a good idea either).
So, given all that it is clear that you can't reach full isolation for your action tests. But
ZF2 will be much easier to test, though.
You'd better start with covering controllers with functional tests. In this case you can bypass this mocking problem and get better coverage of test. Controllers are always hard to be covered with unit tests, because they are strongly coupled.
To write functional tests with ZF consider using Codeception: http://codeception.com/01-27-2012/bdd-with-zend-framework.html
Also, there are some examples, how a unit tests for controller can be made. But, sincerly, I recommend unit-testing controllers after functional tests for them are made.
http://codeception.com/docs/06-UnitTestsAndBDD#TestingController

Where to place reusable code accessible for controllers and models

I have some functionality related to currency conversions in my Zend project. I'd like to make use of the functionality in Controllers as well as Models. Is there a best practice for where to put this code? Or is the fact that the functionality's used in both places an indicator that perhaps I should rethink the structure of the project so it's not needed in both places?
I think the purists would argue that if you're doing currency conversions in your controller code then you're probably doing something wrong, as there shouldn't really be any business logic in there. However, sometimes practical considerations outweigh purist concerns. Let's assume that this is one such case. :-)
If your currency class is a fairly simple utility-type class, then I'd lean towards creating a new directory under "application" called "utils" and then adding that directory to the resource loader in the application bootstrap:
protected function _initResourceLoader()
{
$this->_resourceLoader->addResourceType( 'utility', 'utils', 'Utility' );
}
Then you can create a class called Application_Utility_Currency stored in the file named Currency.php in that directory and call static methods such as:
Application_Utilility_Currency::convert( $from_currency, $to_currency, $amount );
This approach would be especially useful if you had other utility classes that were also looking for a home.
However, if your currency class contains richer functionality (such as connecting to external services to obtain exchange rate data, etc), then it would, IMO, be better to treat it as a "Service" rather than a "Utility". My definition of "model" is fairly loose and includes all data-related services, whether that data is located in the application database or elsewhere, so if the class is of the more complex variety, then I would just stick it in with the other models.

Encapsulation in the age of frameworks

At my old C++ job, we always took great care in encapsulating member variables, and only exposing them as properties when absolutely necessary. We'd have really specific constructors that made sure you fully constructed the object before using it.
These days, with ORM frameworks, dependency-injection, serialization, etc., it seems like you're better off just relying on the default constructor and exposing everything about your class in properties, so that you can inject things, or build and populate objects more dynamically.
In C#, it's been taken one step further with Object initializers, which give you the ability to basically define your own constructor. (I know object initializers are not really custom constructors, but I hope you get my point.)
Are there any general concerns with this direction? It seems like encapsulation is starting to become less important in favor of convenience.
EDIT: I know you can still carefully encapsulate members, but I just feel like when you're trying to crank out some classes, you either have to sit and carefully think about how to encapsulate each member, or just expose it as a property, and worry about how it is initialized later. It just seems like the easiest approach these days is to expose things as properties, and not be so careful. Maybe I'm just flat wrong, but that's just been my experience, espeically with the new C# language features.
I disagree with your conclusion. There are many good ways of encapsulating in c# with all the above mentioned technologies, as to maintain good software coding practices. I would also say that it depends on whose technology demo you're looking at, but in the end it comes down to reducing the state-space of your objects so that you can make sure they hold their invariants at all times.
Take object relational frameworks; most of them allow you to specify how they are going to hydrate the entities; NHibernate for example allows you so say access="property" or access="field.camelcase" and similar. This allows you to encapsulate your properties.
Dependency injection works on the other types you have, mostly those which are not entities, even though you can combine AOP+ORM+IOC in some very nice ways to improve the state of these things. IoC is often used from layers above your domain entities if you're building a data-driven application, which I guess you are, since you're talking about ORMs.
They ("they" being application and domain services and other intrinsic classes to the program) expose their dependencies but in fact can be encapsulated and tested in even better isolation than previously since the paradigms of design-by-contract/design-by-interface which you often use when mocking dependencies in mock-based testing (in conjunction with IoC), will move you towards class-as-component "semantics". I mean: every class, when built using the above, will be better encapsulated.
Updated for urig: This holds true for both exposing concrete dependencies and exposing interfaces. First about interfaces: What I was hinting at above was that services and other applications classes which have dependencies, can with OOP depend on contracts/interfaces rather than specific implementations. In C/C++ and older languages there wasn't the interface and abstract classes can only go so far. Interfaces allow you to tie different runtime instances to the same interface without having to worry about leaking internal state which is what you're trying to get away from when abstracting and encapsulating. With abstract classes you can still provide a class implementation, just that you can't instantiate it, but inheritors still need to know about the invariants in your implementation and that can mess up state.
Secondly, about concrete classes as properties: you have to be wary about what types of types ;) you expose as properties. Say you have a List in your instance; then don't expose IList as the property; this will probably leak and you can't guarantee that consumers of the interface don't add things or remove things which you depend on; instead expose something like IEnumerable and return a copy of the List, or even better, do it as a method:
public IEnumerable MyCollection { get { return _List.Enum(); } } and you can be 100% certain to get both the performance and the encapsulation. Noone can add or remove to that IEnumerable and you still don't have to perform a costly array copy. The corresponding helper method:
static class Ext {
public static IEnumerable<T> Enum<T>(this IEnumerable<T> inner) {
foreach (var item in inner) yield return item;
}
}
So while you can't get 100% encapsulation in say creating overloaded equals operators/method you can get close with your public interfaces.
You can also use the new features of .Net 4.0 built on Spec# to verify the contracts I talked about above.
Serialization will always be there and has been for a long time. Previously, before the internet-area it was used for saving your object graph to disk for later retrieval, now it's used in web services, in copy-semantics and when passing data to e.g. a browser. This doesn't necessarily break encapsulation if you put a few [NonSerialized] attributes or the equivalents on the correct fields.
Object initializers aren't the same as constructors, they are just a way of collapsing a few lines of code. Values/instances in the {} will not be assigned until all of your constructors have run, so in principle it's just the same as not using object initializers.
I guess, what you have to watch out for is deviating from the good principles you've learnt from your previous job and make sure you are keeping your domain objects filled with business logic encapsulated behind good interfaces and ditto for your service-layer.
Private members are still incredibly important. Controlling access to internal object data is always good, and shouldn't be ignored.
Many times private methods I've found to be overkill. Most of the time, if the work you're doing is important enough to break out, you can refactor it in such a way that either a) the private method is trivial, or b) is an integral part of other functions.
In addition, with unit testing, having many methods private makes it very hard to unit test. There are ways around that (making test objects friends, etc), but add difficulties.
I wouldn't discount private methods entirely though. Any time there's important, internal algorithms that really make no sense outside of the class there's no reason to expose those methods.
I think that encapsulation is still important, it helps more in libraries than anything imho. You can create a library that does X, but you don't need everyone to know how X was created. And if you wanted to create it more specifically to obfuscate the way you create X. The way I learned about encapsulation, I remember also that you should always define your variables as private to protect them from a data attack. To protect against a hacker breaking your code and accessing variables that they are not supposed to use.

Help me understand OOD with current project

I have an extremely hard time figurering out how classes needs to communicate with eachother. In a current project I am doing, many classes have become so deeprooted that I have begun to make Singletons and static fields to get around(from what I get this is a bad idea).
Its hard to express my problem and its like other programmers dont have this problem.
Here is a image of a part of the program:
Class diagram
ex1. When I create a Destination object it needs information from Infopanel. How to do that without making a static getter in InfoPanel?
ex2. DestinationRouting is used in everybranch. Do I really have to make it in starter and then pass it down in all the branches?
Not sure if this makes sense to anybody :)
Its a problem that is reacurring in every project.
After looking at your class diagram, I think you are applying a procedural mind set to an OO problem. Your singletons appear to contain all of the behavior which operate on the records in your domain model and the records have very little behavior.
In order to get a better understanding of your object model, I'd try and categorize the relationships (lines) in your class diagram as one of "is-a", "has-a", etc. so that you can better see what you have.
Destination needs some information from InfoPanel, but not likely all information. Is it possible to pass only the needed information to Destination instead of InfoPanel?
What state is being captured in the DestinationRouting class that forces it to be a singleton? Does that information belong elsewhere?
There's just too little information here. For example, I am not even sure if MapPanel and InfoPanel should be the way they are. I'd be tempted to give the decorator pattern a try for what it's worth. I don't know why a Listener is a child of a Panel either. We need to know what these objects are and what system this is.