OOP interaction with database [closed] - c#

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 7 years ago.
Improve this question
If object oriented programming is focused on objects, which consist of methods and data, what is the best OOP-focused approach to working with databases, using C#?
For example, I want to log something using C# classes, and record the logs in a SQL table. All other factors being neutral, would it be more "proper," object-oriented speaking, to do:
Create a class for what's being logged, and include methods for database access
(The methods are tied closely to data)
public class Activity
{
public string ActivityProperty { get; set; }
public void SQLMethod1() {}
public void SQLMethod2() {}
}
...or,
Create a class for what's being logged, and create a class for database access
(Methods are not closely tied to data, but the way data is accessed is treated itself as an object, i.e. referencing EF or another ORM)
public class Activity
{
public string ActivityProperty { get; set; }
}
public class SQLMethods
{
public string SQLProperty { get; set; }
public void SQLMethod1(Activity activityParam) { }
public void SQLMethod2(Activity activityParam) { }
}
...or, perhaps a better design would be more "object-oriented"?

Generally speaking, I prefer not to put database access logic into classes because it hinders your ability to use them in other scenarios in which data access is not required. So I think your second option is the more flexible one.
However, if you are already aware of ORM solutions such as Entity Framework, I would suggest using one of those. EF takes an approach closer to your second one in which you use POCOs (plain old C# classes) and other EF classes take care of moving data from those objects into the database and back.
So overall my suggestion would be to use Entity Framework with the code first methodology.

Related

Class Responsibilities [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 4 years ago.
Improve this question
I want to create an application that maintains a list of Computer objects, checks those objects for availability (using Ping) and if they're available use PSExec to add or remove users to/from the list of administrators.
Currently I can not figure out how to build my classes - which class should be responsible for what (I want to use the common patterns, such as SRP, as good as possible without "overkilling" it.).
When looking at the availability-check, should there be an "extra" class doing the ping request or should this be done by the computer object (instance) itself? If an extra class should be used, how should the computer (and other) object(s) be notified about the changed availability? With a Property?
Tho thoughts regarding this kind of stuff drives me crazy and prevents me from getting any further...
I know there is no correct answer as this is obviously a design and opinion question but I'd appreciate it if I could get an experts opinion here - hopefully this brings me back on track.
Hi I have come up with the following according to the description provided. The Computer class is adhering to SRP as it is only concerned with Computer objects. All the operations are delegated to specialized classes. Currently I have added only a class to check availability. We can also add a specialized class for adding removing users.
Open for discussion and refinement.
public class Computer
{
// properties of the computer class
public IList<User> Users;
// IAvailabiity checker
private readonly IAvailabilityChecker _checker;
// constructor
public Computer(IAvailabilityChecker checker)
{
this._checker = checker;
}
// operations
public void AddUser()
{
if (this._checker.IsAvailable())
{
// add user
}
}
public void RemoveUser()
{
}
}
public class User
{
}
public interface IAvailabilityChecker
{
bool IsAvailable();
}
public class AvailabilityChecker
{
public bool IsAvailable()
{
// availability checker logic
return true;
}
}

Trying to properly organize huge class [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 5 years ago.
Improve this question
I have huge class that implements usage of some client:
public class Client : IClient
{
internal Client(string username, string password){
//login process here
}
//some private methods that make sure connection stays alive, etc
public void Action1(string param1){
//something here...
}
public void Action2(string param1, string param2){
//something else here...
}
}
As it currently is, it's 5000+ lines long mainly because of lots of different public methods.
I'm wondering what is the best practice to properly organize and refactor this, preferably without making method calls more complicated?
Use partial classes and group things into logical sets per each partial class.
Also, if some methods make logical set, consider wrapping them into separate class.
Those 2 should reduce your lines of code per file dramatically.
Usually big class are "hiding" inside other classes (see uncle Bob on "Clean Code").
In your case I'd split the class creating Action classes and making some machanics that lets the Client use some sort of IAction or BaseAction. Thus splitting the logic of every action into a separate class.
To be more precise I'd rather need some more info and code.

Bad practises in abstract classes C# [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'm trying to improve my coding standards by implementing interfaces and abstract classes when necessary, however I would like to ask about practises regarding abstract classes.
I'm creating a web application and one aspect of the site I need to do some data processing, I have created an abstract class and it looks something like this.
public abstract class TestAbstractClass
{
public abstract void doDataProcessing();
}
And I need to implement this 'doDataProcessing' method a few times throughout the application dependent on where the user is on my site, it will do VERY similar data processing, just with one or two different things.
For example:
User is on certain page:
public Page1Class: TestAbstractClass
{
public override void doDataProcessing()
{
//do data processing
}
}
User is on another page
public Page2Class: TestAbstractClass
{
public override void doDataProcessing()
{
//do data processing but with slight change
}
}
User is on another page
public Page3Class: TestAbstractClass
{
public override void doDataProcessing()
{
//do data processing but with another change
}
}
Would this be best practise? Or is it better just making one class, and just doing various conditional statements on what is being passed into the 'doDataProcessing()' method?
I feel if I do it using the method I have posted, I will be having a lot of duplicate code in these 3 classes, is that OK?
I hope this makes sense.
This feels like you need to decompose the solution a bit more. doDataProcessing sounds like it is something that could be broken into smaller pieces. There are high-level design patterns that could help you structure this.
If doDataProcessing is a similar thing but with small changes, then look at the Strategy pattern or the Decorator pattern.
If you are not going to have any implementation in the base doDataProcessing then just go with an interface as #phuzi recommended. Abstract classes are best used if you have some logic that is exactly the same in most cases, and in odd scenarios you can override and/or extend the base logic in the inherited classes.
EDIT
From the information you gave me I would probably do the following:
public abstract class TestAbstractClass
{
public void Process()
{
MethodThatGetsCalledEveryTime();
doDataProcessing();
}
public virtual void doDataProcessing()
{
// can add frequent logic here
}
protected void MethodThatGetsCalledEveryTime()
{
// do stuff here
}
}
this way you can ensure that the "MethodThatGetsCalledEveryTime" will always be called, and if you add additional logic to doDataProcessing that will run as well from the appropriate place.

Not exposing IQueryable and not violating OC principle [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 was reading about the repository pattern the last few days and everyone talking about it do not expose IQueryable from repository like this (like here and here):
public interface ICustomersRepository
{
IQueryable<Customer> Customers{ get; }
}
And it is accepted by large amount of developers to avoid this.
But when it comes to filtering large amount of data and custom filters from UI (like a report with over 10 filter options for searching in data over 1 million records) is IQueryable?
Especially when there is a framework and other low-level developers are using the repository for developing custom reports. They can not always use GetAll for this purpose.
So as mentioned in other threads like this or this, I should have methods for each one of the reports that I have in my repositories, and they should return IEnumerable. Here is what is not clear to me:
If I have a new report I have to change my repository for that and add a new method. And if I change my repository I've violated the Open/Close principle.
Here is my problem: I don't want to expose Iqueryable and on the other hand, I don't want to change my repository for every report.
A repository is an abstraction over your Data Access Layer (DAL). In Java, they are also known as DAOs (Data Access Objects). So, exposing IQueryable<T> in a repository is bad practice because of this reason, you are tying LINQ queries to the client code.
So, to fix it you should create an object which would follow the command pattern with all the filtering options you support. Then return a List<T> or any sorted collection you want to use (maybe IList<T> is more appropriate).
An example
class BookFilter
{
public string NameStartsWith { get; set; }
public string ISBN { get; set; }
public DateTime PublishedAfter { get; set; }
// ....
}
public interface IBookRepository
{
IList<Book> Filter(BookFilter filter);
}

Storing arbitrary complex objects in c# to database [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 8 years ago.
Improve this question
I am currently programming to multiple API's. Till now I have created classes that use EF syntax (id = classNameId etc...) and convert whatever item is being returned to EF object. Since I'm using the C# Wrappers (created by whatever company created the API) for the API's I can't simply alter whatever class it is that I want to store to the database to use EF Syntax. Is there any project that would allow me to dynamically generate tables and columns for any generic object using run time reflection?
Keep in mind that many of the complex objects have within them complex objects.
As of right now I'm considering writing a script to generate inherited classes for each of the Complex Types (identified via reflection) and inserting a Id (and whetever other information EF would need to generate DB) into the inherited class. This would get a little complicated as it would require implicit conversions for Ienumerable to Ienumerable.
Any help would be greatly appreciated.
Thank You.
What you actually need is some schema-less database, like MongoDB or RavenDb instead of relational. These allows to do exactly what you said in the title: to store arbitraty complex objects in db.
You may want to look at OrmLite and see if it meets your reqs.
public class SimpleExample
{
public int Id { get; set; }
public string Name { get; set; }
}
//Set once before use (i.e. in a static constructor).
OrmLiteConfig.DialectProvider = new SqliteOrmLiteDialectProvider();
using (IDbConnection db = "/path/to/db.sqlite".OpenDbConnection())
using (IDbCommand dbConn = db.CreateCommand())
{
dbConn.CreateTable<SimpleExample>(true);
dbConn.Insert(new SimpleExample { Id=1, Name="Hello, World!"});
var rows = dbConn.Select<SimpleExample>();
Assert.That(rows, Has.Count(1));
Assert.That(rows[0].Id, Is.EqualTo(1));
}

Categories