Should try/catch be kept out of class methods? [closed] - oop

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 9 years ago.
Improve this question
From a best practices perspective, should try / catch statements be used when implementing an object's method(s), or is it OK to code them into the methods themselves?
For example, I'm going to code a database class in C#. When I call my runCommand() method, is it considered best practice to do something like this?
//inside class method 'runCommand()'
try
{
_command = new MySqlCommand(query, _connection);
return _command;
}
catch (MySqlException e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
return _command;
}
... or something like this?
//inside a Windows form and assuming an object 'myDB'
private void btnRunCommand_Click(object sender, EventArgs e) {
try {
myDB.runCommand("SELECT * FROM test");
}
catch (MySqlException e) {
MessageBox.Show(e.ToString());
}

It depends on the goals of your exception handling.
If the goal is to display an error message when there's an error, as in your example, the exception handling belongs in the view (the Windows form). This is helpful when user interaction is required to resolve the issue.
However, if your data model should return some default value, or attempt to recover from the exception by loading new data from a remote server, for example, this logic does not belong in the view.

Data access code should generally not interact directly with the user. In the event that user interaction may be required within a data-access method, the caller should supply one or more delegates which can be used to request such interaction. In that way, user-interface code which calls the data access code can define methods to perform user interaction in a way consistent with the rest of the UI, and pass such methods to the data-access code.

Related

Ownership responsibility and reusability

I had a disscusion with a collegue about approaches to these topics in our project.
Im making a Progress System, in short a ProgressMonitor class and a Task class, ProgressMonitor handles an array of tasks. All pretty straight forward stuff. But when it came to the tasks ui, we had to opinions.
Each task has his own UI. We agree we should have an HUD class for handling UI.
The difference in opinion is, he wants the HUD to handle each specific task's UI and so the HUD class would grow quite big and the task would have near to no logic about its UI.
My opinion, The HUD would only handle the logic that is the same for all things in our project that need UI's, and all specific logic is handle by the objects that need UI.
Advantage of his is some ownership (objects that need to acces some ui info can easily get it from HUD)
My advantages, HUD stay light clean and reusable.
What would be more correct acording to OOP?
I'll start with questions that will affect the implementation:
Question 1: Is the Task closely related to it's UI?
Question 2: Is the UI for all tasks the same or has minor differences?
Question 3: Do you need to show different UI for each task based on the specific task?
If the answer to Question 1 is Yes and separating the two responsibilies is hard, adding the UI logic to the Task can simply things a lot.
If the answer to Question 2 is Yes then using the classic model/view separation will make writing new tasks easier as you only need to add the task logic to the Task class.
You can have a TasksHUD class who's responsibility will be to handle a list of TaskUI class. Eeach TaskUI class will have a Task associated with it and handle the rendering of UI and presentation logic for this specific task.
This way your TasksHUD class will manage how the list is shown to the user, while each list entry will be handled by the TaskUI class. The task presentation code will be reused.
Task will only have the responsibilities of executing, changing it's status and other things that a task must do in your app (if you give a more details I can a more detaildd and probably more accurate description), while the responsibility of presenting a task will be given to a TaskUI.
This way if you need to change the logic how a task is rendered, you have to change only the TaskUI class.
You can write as many tasks as you wan't without having the need to write a UI related code for those tasks.
If you need to change the Task class you may or may not have to change TaskUI class as the dependecy goes from TaskUI to Task. Some changes will affect the UI some won't.
If the answer to Question 3 is Yes then:
You can add the responsibility of handling it's UI to the Task. This way it would be easier to change them as they are in the same class. One problem here is that the Task class can grow having multiple responsibilies. Also sharing rendering code for similar tasks etc.
Event in this case you can decouple the Task from it's UI in two classes Task and TaskUI but you will need a mechanism in your app that will associate a specific Task class with it's TaskUI class. This can lead to more classes and a complexity that may not wan't to manage. In the long run it may save you time (mostly from chaising bugs).
Here is a pseudo code example:
interface TaskObserver {
void onTaskChanged(t);
}
interface TaskUI {
void render();
}
interface TaskUIFactory {
register(TaskUIFactoryRegistry registry);
TaskUI create(Task task);
}
interface Task {
TaskStatus status;
execute();
addEventListener(TaskObserver o);
}
class TaskA : Task {
// implementation.....
}
class TaskA_UI : TaskUI, TaskObserver {
TaskA mTask;
TaskA_UI(TaskA task) {
mTask = task;
mTask.addEventListener(this);
}
render() {
// rendering goes here
}
onTaskChanged(t) {
// raise an event or signal to the TaskHUD that a refresh is needed
}
}
class TaskA_UIFactory : TaskUIFactory {
void register(TaskUIFactoryRegistry registry) {
registry.Register(typeof(TaskA), this);
}
TaskUI createUI(Task task) {
return new TaskA_UI((TaskA)task);
}
}
When a task is added your TasksHUD can use the TaskUIFactoryRegistry to get a TaskUIFactory that will create a TaskUI.
Here are some resources that you can check that discuss these kind of issues:
Presentation Model
GUI architectures

Why doesn't ASP.NET Core force the Startup type to implement an interface [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 4 years ago.
Improve this question
The ASP.NET Core configuration relies on a Startup class that should have one Configure method and that can optionally include a ConfigureServices method.
I was wondering why not force this class to implement an interface containing those two methods to get all the benefits of strong typing.
I know that the true reason lies unreachable in the mind of the designers of the framework, but can anybody give a good reason about why they might have chosen not to use an interface?
One possibility is due to dependency injection. Let's say there was an interface, it might look something like this:
public interface IStartup
{
void ConfigureServices(IServiceCollection services);
void Configure(IApplicationBuilder app);
}
However, the Configure method can take extra parameters as part of the dependency injection framework. For example I have an app here that looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//etc...
}
So it's now impossible to make this an interface because there could be any number of things passed in.
Additionally, the ConfigureServices is actually optional.
Finally, there actually does exist an interface called IStartup, but due to the above reasons, I've yet to see it used anywhere.
Bonus: You don't even need to have a startup class at all, all the work can be done when building the web host by calling ConfigureServices and Configure methods.
Besides for the reasons #DavidG pointed out, it is also possible to use startup method conventions to adjust registration of services and middleware based on the environment the application is hosted in.
For example, you can add this method beside the regular ConfigureServices method and it will only be called when running in the Staging environment:
public void ConfigureStagingServices(IServiceCollection services)
{
// ...
}
The same conventions works for Configure(IApplicationBuilder app). See the documentation for further reference.

Objective C Asynchronous to Synchronous Database Access [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have found an open source Objective-C library for connecting to Microsoft SQL Server databases.
The problem is, that I would like to use it synchronously.
This is how my Swift project uses the library.
func execute(query: String) {
self.client.connect(host + ":" + port, username: username, password: password, database: database) { (connected) -> Void in
if connected {
self.client.execute(query, completion: { (results: Array<AnyObject>!) -> Void in
self.result = results[0] as! Array<AnyObject>
})
}
}
}
The block passed is execute asynchronously by the library. Is there a way to make the code execute synchronously so that whenever I call execute, that thread waits for the library work to complete before execute returns?
So, I have some experience with the github library you're using.
It seems most likely that you might want to make this call synchronously because of some of the problems this library has (you can't make multiple queries at once, and can't open multiple connections to the server because the library does all of its SQL work through a singleton). To resolve some of these problems, I highly recommend you check out the SQLConnect library that I wrote (after spending some time trying to use Martin's library that you're using). My library steps away from the singleton approach and you can make as many connections on as many different threads as you want.
With that said... you can make this library (and mine as well) perform synchronously.
If you notice in the SQLClient.h file, the SQLClient object specifies a workerQueue and a callbackQueue. Martin has set the callbackQueue to be on whatever queue the singleton is first instantiated on, and the workerQueue is a queue he specifies. However, these are public properties which can be set perfectly fine.
If you really want the query to perform synchronously, just set the workerQueue and callbackQueue to operate on the current queue.
SQLClient.sharedInstance.workerQueue = NSOperationQueue.currentQueue()
SQLClient.sharedInstance.callbackQueue = NSOperationQueue.currentQueue()
And then perform your query.
All of the code will execute on the same NSOperationQueue, and as such, will by synchronous.
Of course, you can do the same thing using my SQLConnect library, as the SQLConnection object similarly specifies a workerQueue and callbackQueue which you can specify to any queue you want.
With all of this said, I highly, highly, highly recommend that you allow the operation to remain asynchronous and come up with some other solution to whatever problem makes you think it should be performing synchronously. And even if you still think it should by synchronous, please be sure it's not blocking the UI thread.

Design best practice - should an object own what is passed to its constructor? [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 4 years ago.
Improve this question
I have the following class:
public class SqlCeEventStore: EventStore
{
private EventStoreDB db;
public SqlCeEventStore(EventStoreDB db)
{
this.db = db;
}
public void Dispose()
{
db.Dispose();
}
}
My problem is this: am I correct in disposing the EventStoreDB in the Dispose method of my class, given that it was passed to it in the constructor (and thus, might conceivably be reused after my class is disposed)?
That is, if I dispose it I mandate that the correct usage of my class is:
using (var store = new SqlCeEventStore(new EventStoreDB)){
{
//...
}
but I can see this alternative call being used:
using (var db = new EventStoreDB())
using (var store = new SqlCeEventStore(db))
{
//...
}
in which case I should not dispose of the EventStoreDB from the SqlCeEventStore class.
Are there any arguments for one style or the other? I want to pick one and stick to it, and I'd rather not flip a coin :)
In general there is no rule to this, but yes I would agree that since the object was created outside your scope and was passed to you, you don't own it.
If you had created it, then you should have all rights to do whatever you like to (with documenting the expected behavior for the callers)
This is the classical composition vs aggregation stuff.
If the EventStoreDB is owned by SqlEventStore (ie is part of its composition), it should be constructed by or be merged with the SqlEventStore class.
If it has uses outside the scope of the SqlEventStore lifetime then it should be created and disposed by the external code.
There is no general rule here, and IMHO, there should not be one either. Different objects have different lifespans, and the most general guideline would be to make sure that objects are managed consistently according to their lifespans, and that lifespans are as short as possible.
You could try to use the following as a guideline (but don't be afraid to deviate when you need to): Dispose of an object in the same scope as you allocate it. This guideline is suitable for many scenarios, and it is exactly what the using statement simplifies.
If you have long-lived objects without an obvious disposal point, don't worry. That's normal. However, ask yourself this: Do I really need this object to live for as long as it does? Is there some other way I can model this to make the lifespan shorter? If you can find another way that makes the lifespan shorter, that generally makes the object more manageable, and should be preferred.
But again, there is not any "one true rule" here.
You can not pick one and stick to it. The user can always choose what ever he wants.
However, keep in mind that you are not responsible as a class of disposing objects passed through the constructor.
note
The coming is really silly to discuss because if you want to impose initiation of the class using *new SqlCeEventStore(new EventStoreDB))* then why don't you remove this EventStoreDB parameter and instantiate the variable db inside your constructor.
Workaround
There is a workaround -check this:
public myClass {
//do not make the constructor public //hide it
private myClass(EventStoreDB db){
this.db = db;
}
//make a public constructor that will call the private one in the way you want
public myClass(){
this(myClass(new EventStoreDB()));
}
}
I would suggest that if one can reasonably imagine situations in which the constructed object would be the last thing in the universe that's interested in the passed-in object, as well as situations in which other things will want to keep using the passed-in object after the constructor is done with it, it may be desirable to have a constructor parameter which specifies whether the new object should take ownership of the object that was passed in.
Note that if the constructed object will be taking ownership of the passed-in object, it's important to make certain that object will be disposed even if the constructor throws an exception. One way to do this would be to wrap the constructor call in a routine which will, in a "finally" block, dispose the passed-in object unless the constructor had completed successfully.

How to document the Main method? [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
Okay, so I've got a .NET console application with it's Main method, contained in a Program class. You know, the usual:
class Program
{
static void Main(string[] args)
{
// Do something spectactular
}
}
Since I've started using StyleCop and FxCop so rigorously, I've become kind of nit-picky about making sure everything is properly documented.
Then it hit me. I have absolutely no idea how to properly document Program and Program.Main.
I suppose, in the long run, that you could go with the following:
/// <summary>
/// Encapsulates the application's main entry point.
/// </summary>
class Program
{
/// <summary>
/// The application's main entry point.
/// </summary>
static void Main(string[] args)
{
// Do something spectactular
}
}
But that seems woefully inadequate (despite the fact that my Main routines always delegate to other classes to do the work).
How do you folks document these things? Is there a recommendation or standard?
In my humble opinion, it's not worth the trouble to document the main function, especially if you are just going to say "The application's main entry point." If someone doesn't know that Main is the application's main entry point, you don't want them anywhere near your code :-)
If you were to put anything there, you might document what the expected or accepted arguments are, but I think there are better places to document program options (like, a usage function that prints usage, the users manual, a readme file, or elsewhere), since that information is useful not only to developers but also to users of the software.
Documentation is there to add something that's not obvious from the code. And tools are there to help you, not to dictate you what should and should not be documented.
"The application's main entry point" does not add anything, so don't write it.
If there's anything non-obvious like parameters, document this.
Add documentation at the class level that describes what the console program actually does, so it's purpose.
In the Main method, document the required arguments etc., unless if you hand that off, 'main entry point' does suffice.
I tend to hand it off to an instance method in Program called Run(string[] args), so in that case, document the Run method with the arguments/switches options.
The body of my Main() method then simply looks like:
Program prog = new Program();
prog.Run(args);
Don't, just don't.
Just look at those 2 samples you created and compare which is more readable?
I'll bet you'll choose the one without comments.