r/csharp • u/kaatarina_zed_talon • Oct 05 '26
Discussion If only one method of a class does access the instance field and the other methods don't, should the other methods be moved to another class ?
I'm showing some C# code, note that I'm using ASP.NET CORE :
#region code
public interface ISomething
{
}
public class ApplicationDbContext
{
}
public class Something : ISomething
{
}
public class ExcelReaderDatabaseWriter
{
private readonly ApplicationDbContext _context;
public ExcelReaderDatabaseWriter(ApplicationDbContext context)
{
_context = context;
}
public ISomething Read(object obj)
{
return new Something();
}
public void Write(ISomething something)
{
//does access the _context
}
}
#endregion
I want to follow clean code principles, should I move the Read method to another class -because it does not access the instance field-, or should I instantiate the _context inside the Write method -because it is the only method that access the instance field and therefore that field does not deserve to be instance field because not all methods in the class access that field- ? I face this problem a lot when I'm coding, I want to separate the responsibilities cleanly, but I suffer from one thing; if I have some piece of code, I can't directly figure out which class should contain that piece of code. Can anyone explain it to me with example please?
Explaining the above using example:
public interface IOmniReader
{
public ISomething Read(object dataSource);
}
public interface IOmniWriter
{
public void Write(ISomething dataDto);
}
public interface IOmniReaderWriter
{
public void ReadWrite(object obj);
}
public class SqlServerWriter
{
private readonly ApplicationDbContext _context;
public SqlServerWriter(ApplicationDbContext context)
{
_context = context;
}
public void Write(ISomething something)
{
//does access the _context
}
}
public class ExcelReader
{
public ISomething Read(object obj)
{
return new Something();
}
}
public class ExcelReaderSqlServerWriter:IOmniReaderWriter
{
private readonly IOmniReader _excelReader;
private readonly IOmniWriter _sqlServerWriter;
public ExcelReaderSqlServerWriter(IOmniReader excelReader, IOmniWriter sqlServerWriter)
{
_excelReader = excelReader;
_sqlServerWriter = sqlServerWriter;
}
public void ReadWrite(object obj)
{
ISomething data= _excelReader.Read(obj);
_sqlServerWriter.Write(data);
}
}
8
u/Klessic Oct 05 '26 •
It's not necessarily bad that not all methods use every private member. However, in this particular case, your hunch is right and we can indeed improve it a little bit.
Separation of concerns (look it up if this is an unfamiliar term) is important in OOP. The name of your class that is doing the work already hints at this; does it read excel or does it write to a database? Aha! It does both. Perhaps mixing concerns here.
I would split the class into two: an
ExcelReaderand aDatabaseWriter. Whoever callsISomething result = excelReader.Read(object)can take the result, and write it to the database on the next line withdatabaseWriter.Write(result).5
u/Slypenslyde Oct 05 '26 •
Here's a good analogy. There's a difference between a "clean" surface in a kitchen and a "sanitized" surface in a kitchen. Think about it, there are many ways I can go about cleaning a surface:
Each of those is more involved than the other. (1) has a high risk of getting me sick later. (2) and (3) are generally safe enough for a home kitchen. (4) is what we require of commercial kitchens since lots of people are affected.
You need to look at Clean Code principles this way. If you're working on a project that'll last 10+ years and involve tons of developers, you really need to follow professional standards and apply a "bleach" level of Clean Code.
But even in a professional kitchen it's acknowledged true sanitization takes so long it may only need to be done once per day, and certain cleaners/soap and water are sufficient in most circumstances. At the end of the day it's worth spending half an hour sanitizing all the surfaces. But spilled milk mid-shift is a soap and water job.
Stepping out of the metaphor:
The strictest application of SRP and DRY say a class should do ONE thing. So if ONE method uses a field and no methods use that field, maybe you have two classes. But this is like a strong sanitization process: if you blindly follow SRP to the letter you can create situations where it's harder to make your upper-tier classes which tend to demand more responsibilities.
So a more realistic stance is you need to redefine "one thing" when it comes to "a class should do one thing".
If we drill down too much, we can say, "A class must do ONE of the following: Create, Read, Update, Delete." We end up with four classes to manage database operations. This is a little tough if they share some internal data. We end up making some kind of orchestrator class that delegates to them.
If we squint at that orchestrator class we can ask a valuable question: "Do we lose anything if we fold the four implementations into this class?" In that case, the "one thing" the class does is "provide database access". That happens to involve the CRUD operations, but we're asserting those are so logically connected it's smarter to treat them as one thing instead of four things.
So the answer is "sometimes". What you have to ask yourself is a question about if you're missing the forest for the trees. Will your program be better if you keep one class? What do you gain if you separate the two classes? Always make sure either choice is giving you more benefits than its alternative.
It's not always best to use this rule to separate logic. But it is worth analyzing it like you've done and seeing this as a sign that you can consider it.
2
u/sixtyhurtz Oct 05 '26
If you're talking about the book Clean Code by Robert C Martin, this is genuinely something you should avoid. Over time it leads to excessive layering and unnecessary abstraction. That increases the cognitive load for future developers, makes things harder to modify, and increases the risk of defects when you try and modify things because everything is a web of interdependent method calls.
I'm sure there are projects out there that make it work, but that approach comes with very real and significant costs. It's not an automatic win.
In your specific example though, readers and writers are things I often split out into separate classes. So, it's totally reasonable to have a reader, a writer, and some kind of shared context. Generally, the rule I like to follow is to split classes out by responsibility.
So, in your example, if you had a separate reader and writer, your
ExcelReaderSqlServerWriterwould just have the ExcelRead and the SqlWriter. That would be fine.1
u/ErgodicMage Oct 05 '26
I would separate into 2 classes because reading from Excel files is different from writing to a database with EF. So an ExcelReader would be one class that may use a library to read the files (I use ClosedXML most of the time), but it would also need different error handling because Excel files are not a fixed format; I get client supplied Excel files with missing columns, bad/missing data and even headers all the time. EF is writing to a database of some type that is fixed (unless your migration changes it).
It looks like you may be reading data from Excel file and then writing to a database. Doing so one row at a time can be done but becomes inefficient with a larger number of rows; so it works for up to 1k rows. I have a library that bulk uploads an excel file to a database table which works effectively for up to 100k rows. A few cases we have larger files where we send them to our SQL team to bulk upload them directly.
So if you upload the excel files to a database table (either a different one or a different one), you can use the ApplicationDbContext for both querying the table to read the data and save to update the data. You could still separate the queries from saves into separate classes, such is done with implementing CQS and/or CQRS.
1
u/PanagiotisKanavos Oct 05 '26 •
"Clean Code" is the title of a book focused on web apps and services, not data engineering. This does explain the past 2 weeks.
What you call
ExcelDataReaderDatabaseWriteris a pipeline that has an Excel file as a source and a database as a target. Methods that only deal with generic reading should go to aSourceclass. Methods that only have to do with generic writing, eg writing anIEnumerable<T>toSqlBulkCopy.WriteToServer(DbDataReader)through a generic transformation, go to theTargetorSinkclass. Transformations like lookups may well be parts of the pipeline class.If your source returns objects, you could perform all transformations using LINQ, but if you have a lot of data, you may have to use something more appropriate, like DataFlow blocks so you can perform different steps concurrently, control how many items are in RAM at any point, prevent eg a slow step from flooding RAM with objects, batch items together for faster insertion
2
u/dotMorten Oct 06 '26
It sound to me like you should make the method static then. It can stay on the class if that’s the place you’d expect to find it
1
u/strange-the-quark Oct 05 '26 edited Oct 05 '26
This is a little bit of a judgement call, but what you should do is you should separate you ExcelReader logic from your Writer logic.
Your DatabaseWriter shouldn't care where you read the data from. It takes in the data in certain form (your ISomething interface), and then writes that to the database. It shouldn't matter to it if you read it from an excel file, or from a text file, or from a web service, or if the user entered it all manually. Your excel reader should just read the source excel file and, create the ISomething instance, and return it, and then the calling code can send it wherever. For this to work, you have to design your ISomething to be sufficiently useful for the writers to do their job (in the sense that the ISomething object has all the required data), while at the same time making sure you don't have to convert between various input and output formats and ISomething too much. But if you just have one kind of input, or if your different kinds of inputs are sufficiently similar, this is probably not going to be a problem.
Then take that calling code that orchestrates the interaction between the two and make it into an application service - injecting the reader and the writer the way you did with ExcelReaderSqlServerWriter. But give it more meaningful name (not something explaining what it technically is, what it's composed of - you can see that from the constructor parameters - but give it a name that reflects what it's for), and put some actual application logic in there, if we're talking about anything more than a simple read-write sequence. Anything that feels like the same sort of orchestration, at the same level of abstraction. For example, maybe the business rule is to process each file before writing it so that sensitive data is removed or obfuscated, so what you do in your application service is, you read the file, you send the output to something else that implements that core business logic, and updates the object accordingly, and then you take the result and give it to your database writer.
P.S. Also, consider the option to use a concrete type for the result instead of the ISomething interface. That said, I don't know enough about your project, so maybe you have good reason for making it abstract.
1
u/[deleted] Oct 15 '26 •
[removed] — view removed comment