How many parameters is optimal for constructor? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a C# project that needs to refactor. Project uses WPF+MVVM Light toolkit. I found the MainViewModel(...) constructor that receives about 50 parameters (factories interfaces). I think not. Am I right? I'm interested, because I want to improve my OOP thinking. Thanks.
P.S. Sorry for my grammar. Check me if you find errors.

Clean Code: A Handbook of Agile Software Craftsmanship, page 40, states that...
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.
Consider the book as guidelines for software design, and as such, recommendations when thinking about your code structure.

50 factory interfaces means your ViewModel is way too big and trying to do too many things at the same time. You should break it into separate ViewModels that will appear as properties on the main view model.
WPF allows composition and any framework that allows ViewModel first (ie anything except PRISM) will compose the corresponding views form the ViewModel it encounters. I'm not sure about MVVM Light but with Caliburn.Micro this is almost a non-issue.
If MVVM Light doesn't automate this, you'll have to bind the WPF controls that will contain a specific child model's view to the child model property on the main view model.
Another option is to bundle multiple factory interfaces into parameter objects and pass these to the constructor, bringing the number of parameters to 4-5 instead of 50. This is the Introduce Parameter Object refactoring. Some tools like ReSharper provide automation support for this refactoring.
If you combine this with a DI container the parameter objects can get initialized automagically simply by registering the individual interfaces.
The best solution though is to break the main model into submodels

You might look into using a Dependency Injector like Unity. Register all your Service, Factory, and associated Classes you need with the Unity Container and then you only need a single parameter for your ViewModel constructor which is the Unity Container.
50 parameters for a constructor seems insane to me...

Related

Using interfaces as parameters instead of classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've seen a lot of different coding patterns over the last several years, and I was struck by vast differences between different shops and programmers. At my previous employer, nearly every single class had a defined interface, even if only a single class implemented that interface, and the interfaces were used as parameters instead of the classes themselves.
At my current employer, interfaces are practically unheard of, and I don't think I've ever seen a custom interface ever defined. As such, classes are pretty much exclusively passed around.
I understand that interfaces are a contract that defines what members and functions a class will implement, but are there any real reasons to define interfaces for some/most classes that will never share similarities to other classes?
For example, most of our operations are simple CRUD actions. While we handle reporting and other tasks, nearly every operation is either some sort of insert, update, delete, or select. Our data models tend to be pretty similar to our database structure at their base level. As we move higher through the application layers, we may combine or alter certain objects to contain related properties, but everything is pretty linear.
I'm just having a hard time seeing why interfaces would be such a good thing to implement in our situation, whereas my last company heavily relied upon them.
The primary benefit to all classes implementing an interface and then passing them around is that it greatly increases the ease of mocking them for unit tests.
If you always pass concrete classes around, the mocks have to derive from them. If they don't have virtual members, the mocks cannot override any behavior, and even if there are virtual members you may get side-effect code from the base class that you don't want in that environment.
None of these problems exist with interfaces, clean mocks are very easy (especially with a framework like NSubstitute). The interfaces also allow for implementing various patterns like Strategy, and help support the Open-Closed Principle (among others).
Granted, an interface for every class can seem to be a bit overkill, but at least interfaces around every process-external facing class is an excellent practice.

Is this a common design pattern? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
i use the following pattern/style alot in my applications/programs and want to know if this is a common pattern that i don't know.
When i must write an app that is like a big function that get the input data from different sources, do the processing and create the output. Like the IPO Model (input-process-output).
I have one class/type that represents only my state/data which has no logic. Most of the time i name it Context, ExecutionContext or RuntimeContext. I also have multiple classes/types that contains only logic as stateless funtions (in C# static methods in static classes). After my entrypoint of the app, i create the context at first and use it then as arguments for my functions. The context holds the complate state/data of the app and all my static functions/methods manipulate the context. At the end of the functions chain and the call/execution is done and the context holds the final state if i need outputdata.
I try to create a picture that visualize these approach
The advantage of these pattern is
i can simple test my logic (small pieces of static functions) with
unittest
it is not so hard to use concurrent code (only the context need threadsafe code)
dependencies to other systems a mostly decoupled as abstractions (interfaces) in the context (for example an IDbContext). That make the testing of a bigger scope simple
And here is now my question. Is this a common pattern? When yes, how is it called?
Thanks for every hint! :)
regards
This looks like a Dataflow.
The functions are black boxes which act on the data provided to it. Dataflows are turing complete, and can even model traditional imperative flow control structures.
When you issue a request to ASP.NET MVC, it has an entry and at the end it returns an output. ASP.NET MVC is open source and there are tons of diagrams which explain the whole pipeline and how it works. It is also very customizable so developers can plug their own classes in, intercept certain events, hook into certain parts (filters, authentication, authorization etc.)
If I were you I would start looking into that and borrow some ideas from it. You don't event have to look at the source code. You can start by looking at the diagrams for the pipeline and see what it is doing and how it is doing it.
Right now your code is just functions which are executed in a serial manner. If you want to use Object Orientation, take advantage of interfaces and allow customization, event interception, hooking etc. then it will be difficult.
Here is the diagram in case you are interested.
Well, it's common in IoC-style apps, where services/repositories are singletons and, as so, stateless.
The advantage of this approach is that it saves a lot of memory and some time (no need for new instances of components to be spawned). Disadvantage is that you somehow lose the OOP aproach and also is hard to maintance in bigger picture without strong interfaces support and IoC/Dependency Injection container.
Also look at ThreadLocal<> mechanism build into .NET - that way you don't need to pass your context explicit, but rather than that access thred-scoped global variable that contains it (but then - you need to watch out when branching threads, another topic that IoC/DI handles).

Who should create UI elements? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've got an WinForms application that uses MVP and I'm not entirely sure how to approach the scenario of when I need to create new UI elements.
For the sake of example, let's say my view has a button which is supposed to open a new view (Form) as a dialog. Is the view or the presenter supposed to create the new view or is it the job of the presenter?
This is my thought process:
The view should create it as it as a UI specific operation. But...
The presenter should do it because the view is just supposed to be passive. But the presenter shouldn't know the specifics of the UI.
Which is the correct way to approach this?
I've seen this done a couple different ways. It's funny how all the patterns seem perfect on paper and then implementation details show how it's not that simple. I'm going to give examples as a MVW (model-view-whatever) because it should be similar in any pattern.
Option 1:
Bind to a property. This is a little more difficult with WinForms but works great with WPF. Have your button set a bool property on your presenter/controller/viewmodel. Your view then simply shows or hides it's UI based on this value. The UI can overlay all existing UI to have the appearance of a modal.
Option 2:
Services. Introduce a DialogService (hopefully you have dependency injection set up so it's trivial to add). This service has a method of ShowDialog(options). Options could be title, message, commands (with titles and actions for button). Have your button set a property or fire a command on your presenter that then calls it's dialogService's ShowDialog method. This way your view is still just simply calling your presenter and it is using the service. Views shouldn't know about services. This allows your DialogSevice to construct the appropriate UI and then launch the new form. This is also how I like to wrap up the native MessageBox.Show calls so you can replace all these with a DialogService.
Option 3:
Don't be a purist. If your modal doesn't need to interact with a presenter or you simply want basic data back (say a color picker or something like that) then just let your view take care of it. Your button can simply open the modal, the modal has values that are sent back to the view. Then your view uses them. If the data has no reason to make it back to a presenter, don't over complicate things to be a purist. Views can still perform UI based logic. I use the view for many UI only things such as moving elements around with mouse/touch events or pinch to zoom calculations. If logic is UI only, keep it in the view's code behind. If it's repeated UI logic move it to a service or user control or custom view.
In all the MVP/MVC/MVVM docs, they are always missing crucial details. To me, Services is the missing link. They allow loosely coupled logic to be plugged in and you can wrap up some of the ugly UI bindings or UI events into services and keep things tidy.
Hope this helps.

Visual Studio C# - Tier Separation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm learning about the different tiers in software development, such as the presentation tier, logic tier..etc.
So I have this RaceTrackSimulator project which is a Windows Forms Application. I want to separate all the classes (logic) from the GUI (presentation) and I did so like this:
But now the problem is, I don't know how to allow the classes to access and modify components of the GUI such as textboxes and labels. I think this is just a simple namespace issue, but that doesn't make sense because in each class it says:
namespace RaceTrackSimulator.BusinessLogic
How do I resolve such an issue?
Thanks!
You have just separated the business tier classes in separate folder which doesn't actually qualify as separate tier altogether. You should rather move all this classes in a separate project (example, class library project) and use the dll of that class library to your presentation tier form application.
You can as well choose, to write your business tier as WCF service and deploy them. In turn, your client/presentation layer will consume the service then to access business layer; which is one way good cause then for all different client's (UI or other) you don't have to ship the dll exclusively.
In your specific case, the problem could be that the namesspaces are different and in which case make sure, you are importing the correct namespace.
A few things it could be without looking at the actual code. The namespaces would be different from the 3 classes compared to your Form as they are in a different folder.
Also ensure that the components visibilty level is set to "Public" in the properties tab on the Form Designer. Once they are public, you should be able to access them in any of the 3 classes that you have created.
Did you put a
using RaceTrackSimulator.BusinessLogic;
At the top of the file where you are referencing your objects?
Where your code resides in terms of namespacing is irrelevant. You've done that fine. All you need to do is supply a means of accessing the components from your business logic classes. There's a multitude of ways of doing that depending on your requirements. You could supply a post(Object state) method in your form, and instantiate your logic class passing a reference to the form object. Your business logic can then simply post anything it likes back to the form and it's up to the form how it then handles the UI logic based on the data/message it receives from the logic layer. Or you could make your components more publicly visible to the logic layer. Or you provide an interface that allows access to the components directly.
Also, what you are calling Business Logic in your example above is not really logic. It's business model classes, by the looks of it.

Where would you place a method that has the same functionality but is inside 2 subclasses and has different parameters? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am trying to restructure an application, and right now there are two classes which are subclasses of another class.
Both of these classes have a method. This method essentially does the same thing (get user information) but from different data sources and parses them differently (say one uses the Facebook API and the other a database). They also take in different parameters.
Does it structurally make sense to leave both methods in the subclasses with the same method name? Or is there a cleaner way of organizing the methods within the subclasses?
Even though both methods are logically GetUserInfo, it is also correct that one is logically GetUserInfoFromFB and the other GetUserInfoFromDB.
You could create an abstract GetUserInfo method, but since the methods get different parameters, it could easily get messy. It is easily feasible, however, if the parameters can be logically refactored as properties of the subclass (or properties of logical class to hold them together, that being a property of the subclass).
Edit: The strategy pattern is applicable here, but is what I would consider "messy". Your case as you presented it is small in scale, so the the strategy pattern just might be an overkill.
tl;dr If you do not think your case justifies the strategy design pattern, it is perfectly fine to leave it as it is.
This is a perfect place to apply the strategy pattern.
Rather than having a different GetUserInformationMethod call for each class, create a new class (or a delegate type) that exists just to get user information. Have a UserInformationGetter attribute which is an instance of your user information fetching class/delgate in the base class, and have the base class's GetUserInformation method invoke the delegate/class to get user information.
The challenge of different parameters could be handled in a number of different ways, which depends on the parameters. If the parameters are related to the details of implementation (e.g. database connection strings), and not variant across users then you should tie that information to the UserInformationGetter class.
If the information is dependent on the user, there are a number of strategies. I would suggest you create a type that encapsulates all the information about the user that is used to fetch user data in either case. Then you can pass this object to the methods, rather than parameters that vary accoridng to the method of data access.
This way, you can vary the user information fetching strategy of your base classes independently of anything else which might vary between the classes. Additionally, you can vary the way you get user information at runtime, allowing your program to adapt to changing requirements easily.

Categories

Resources