I have a question regarding the structure of my code and how to keep classes simple. I am working on simplifying the service layer of a C# project. Much of the code has not taken into account OOP practices and there are few classes with methods over 200 lines. I have begun to extract out smaller methods but have a quick query regarding how to do this.
As an example, i have a method that retrieves file directories that are specific to a customer, then checks to see if they exist, creates them if they don't and finally returns an object with a list of these directories. I want to stick to the principle of not having private methods and extract out into new classes though traditional i would have created private methods for checking if directories exist, another for creating them, a third for retrieving the folder names and returning the object and a public method to call all of these in order with an associated interface with a single method.
Should i be creating new classes for each of these private methods and if so would they all need an interface? or perhaps keep them all public and call them from elsewhere?
Thanks in advance!
Short answer: you should do neither of those things.
If you want to approach the problem from an object-oriented perspective, forget for a while what the methods are doing. Think about what the code is about. You only mentioned "Customer" as a possible "business" relevant thing. Try to come up with other business relevant things. What are those files? Reports? ActivityLogs? Messages? CreditReports :) ?
The point is, object-orientation is not about just having methods in different classes. The classes and the methods must have some business meaning. If they don't mean anything, then there is no real reason to have them in the first place!
From that it is also clear that "StorageManager", "StorageUtil", and things like that shouldn't exist, because it doesn't have any business meaning at all.
So start with finding out what the application is about (the things), and then you can move certain responsibilities to the appropriate thing.
Related
I have a Business Layer, whose only one class should be visible to outer world. So, I have marked all classes as internal except that class. Since that class requires some internal class to instantiate, I need other classes to be marked as public and other classes depend on some other classes and so on. So ultimately almost all of my internal classes are made public.
How do You handle such scenarios?
Also today there is just one class exposed to outer world but in future there may be two or three, so it means I need three facades?
Thanks
Correct, all of your injected dependencies must be visible to your Composition Root. It sounds like you're asking this question: Ioc/DI - Why do I have to reference all layers/assemblies in entry application?
To quote part of that answer from Mark Seeman:
you don't have to add hard references to all required libraries. Instead, you can use late binding either in the form of convention-based assembly-scanning (preferred) or XML configuration.
Also this, from Steven:
If you are very strict about protecting your architectural boundaries using assemblies, you can simply move your Composition Root to a separate assembly.
However, you should ask yourself why doing so would be worth the effort. If it is merely to enforce architectural boundaries, there is no substitute for discipline. My experience is that that discipline is also more easily maintained when following the SOLID principles, for which dependency injection is the "glue".
After doing a lot of research I am writing my findings, so that it may be of some help to newcomers on Dependency Injection
Misunderstandings regarding my current design and Dependency Injection:
Initial approach and problem(s) associated with it:
My business layer was having a composition root inside it, where as
it should be outside the business layer and near to the application
entry point. In composition root I was essentially having a big factory referred as Poor Man's DI by Mark Seemann. In my application starting point, I was creating an instance of this factory class and then creating my only (intended to be) visible class to outside world. This decision clearly violates Liskov's Principle which says that every dependency should be replaceable. I was having a modular design, but my previous approach was tightly coupled, I wasn't able to reap more benefits out of it, despite only some code cleanliness and code maintainability.
A better approach is:
A very helplful link given by Facio Ratio
The Composition root should have been near the application root, all dependency classes should be made public which I referred initially as a problem; making them public I am introducing low coupling and following Liskov's substitution which is good.
You can change the public class to the interface and all other parts of the program will only know about the interface. Here's some sample code to illustrate this:
public interface IFacade
{
void DoSomething();
}
internal class FacadeImpl : IFacade
{
public FacadeImpl(Alfa alfa, Bravo bravo)
{
}
public void DoSomething()
{
}
}
internal class Alfa
{
}
internal class Bravo
{
}
I can see three solutions, none real good. You might want to combine them in someway. But...
First, put some simple parameters (numeric, perhaps) in the constructor that let the caller say what he wants to do, and that the new public class instance can use to grab internal class objects (to self-inject). (You could use special public classes/interfaces used solely to convey information here too.) This makes for an awkward and limited interface, but is great for encapsulation. If the caller prefers adding a few quick parameters to constructing complex injectable objects anyway this might work out well. (It's always a drag when a method wants five objects of classes you never heard of before when the only option you need, or even want, is "read-only" vs "editable".)
Second, you could make your internal classes public. Now the caller has immense power and can do anything. This is good if the calling code is really the heart of the system, but bad if you don't quite trust that code or if the caller really doesn't want to be bothered with all the picky details.
Third, you might find you can pull some classes from the calling code into your assembly. If you're really lucky, the class making the call might work better on the inside (hopefully without reintroducing this problem one level up).
Response to comments:
As I understand it, you have a service calling a method in a public class in your business layer. To make the call, it needs objects of other classes in the business layer. These other classes are and should be internal. For example, you want to call a method called GetAverage and pass it an instance of the (internal) class RoundingPolicy so it knows how to round. My first answer is that you should take an integer value instead of a class: a constant value such as ROUND_UP, ROUND_DOWN, NEAREST_INTEGER, etc. GetAverage would then use this number to generate the proper RoundingPolicy instance inside the business layer, keeping RoundingPolicy internal.
My first answer is the one I'm suggesting. However, it gives the service a rather primitive interface, so my second two answers suggest alternatives.
The second answer is actually what you are trying to avoid. My thinking was that if all those internal classes were needed by the service, maybe there was no way around the problem. In my example above, if the service is using 30 lines of code to construct just the right RoundingPolicy instance before passing it, you're not going to fix the problem with just a few integer parameters. You'd need to give the overall design a lot of thought.
The third answer is a forlorn hope, but you might find that the calling code is doing work that could just as easily be done inside the business layer. This is actually similar to my first answer. Here, however, the interface might be more elegant. My first answer limits what the service can do. This answer suggests the service doesn't want to do much anyway; it's always using one identical RoundingPolicy instance, so you don't even need to pass a parameter.
I may not fully understand your question, but I hope there's an idea here somewhere that you can use.
Still more: Forth Answer:
I considered this a sort of part of my first answer, but I've thought it through and think I should state it explicitly.
I don't think the class you're making the call to needs an interface, but you could make interfaces for all the classes you don't want to expose to the service. IRoundingPolicy, for instance. You will need some way to get real instances of these interfaces, because new IRoundingPolicy() isn't going to work. Now the service is exposed to all the complexities of the classes you were trying to hide (down side) but they can't see inside the classes (up side). You can control exactly what the service gets to work with--the original classes are still encapsulated. This perhaps makes a workable version of my second answer. This might be useful in one or two places where the service needs more elaborate options than my first answer allows.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm trying to learn the correct way to use classes in my code, when it's not something obvious like a set of customers, dogs inheriting from animals, etc.
I've broken off large sections of code into "features" such as Installer.cs, Downloader.cs, UiManager.cs. The only way I can find to have those classes interact with each others' properties and methods is to make them all static, which I've been told in another question is the wrong way to go.
So my problem is one of 3 things:
There is a way to make classes talk to each other that I just don't understand yet.
Classes should never try to talk to each other, but perform one-off actions and then return something back to main/form1, which the main class can then use to pass into another class for a one-off action.
Classes are really only useful for making lots of instances, and there's some other structure entirely I need to learn about for abstracting large chunks of functionality out from the main class.
All the tutorials I can find and lectures I watch seem to only tell you how classes work, but not when and how to use them in a real product.
EDIT - A more specific example:
Say I have one string that is central to the entire app, and needs to be seen and/or modified potentially by every class. How do I move that information around the code without either having everything in one class or making it static?
I can't see a way to let that string live in Form1 without making it static (because all the form events and functions would need to be able to see it to pass it to a class).
I can't see a way to put the string into another class without having to make the string and the whole class static, so other classes can see into it.
Maybe there's something I'm missing about actually instantiating the classes, and making objects interact with each other.
I think all your intuitions are right.
No, there's not. Static or instance.
It's a design choice (and there's a lot out there). I'm a pragmatic, so I consider a design pattern that generates spaguethi code a bad design pattern choice. But a bad design pattern for a project can be a good design pattern for another project. Try to read the Head First Design Pattern book.
Yes, there are interfaces and abstract classes.
A few more thoughts:
I don't think the use of static methods or classes must be avoided. What must be avoided is the miss use of a static method or class, like the miss use of everything inside a language. But is very hard to define what's a miss use of a static, and because static methods or classes are particulary dangerous, people like to say to avoid the static keyword at all. A static method will be in memory unless you end your application, so if you don't dispose a connection inside a static method, you will have a very bad day.
I have a utility project, and inside the utility project I have a data class. The data class provides access to the database. It's a static class. Why?
Well, first of all, it is static because the connection string comes from the webconfig. So I have a static constructor (runs once when the application starts and the class is mentioned) who reads the webconfig and store the string in a static private member variable. I think it's a lot better than read the webconfig file and create a scoped variable 10 bilion times day. The methods are static because they are simple enough, meaning that they don't need a lot of configuration to work, they just need a few parameters and they are used only in the data access project. All my website users are using the same instance of the method (the static one), but everyone uses the static method with different parameters, so they get different responses from it (they share the pipe, but they drink different water). It's only necessary extra care inside the method to clean everything (dispose every scoped instance), because if you don't they will stay in memory. And finally, my bussiness is about data manipulation, a non static data class means a lot more memory usage than a static one (the cpu usage is almost the same in both patterns).
public abstract class Data
{
[...]
static Data()
{
#if DEBUG
_Connection = ConfigurationManager.AppSettings["debug"];
#endif
#if RELEASE
_Connection = ConfigurationManager.AppSettings["release"];
#endif
[...]
}
[...]
}
In the end of the day I use static when:
If it is simple enough (that I can control every aspect);
If it is small enough (I use extension methods to validations, and they are static) and;
If it is heavy used.
Besides that, I use layers to organize my project (poco + factory pattern). I have a utility project, then a entity model project, then a access project, then a bussiness logic project, then a website, a api, a manager, and so on. The classes in the utility project don't interact each other, but the classes inside the entity model project do (a class can have a instance of another class inside it). The entity model project don't interact with the utility project because they have the same level, they interact each other in another level, in the access project, but it's more intuitive in a data manipulation project.
Classes talk to eachother when they have a reference, in order for A to pass a message to B, A needs a reference to B (either an instance or static reference)
Classes can either talk to each other, or return information to another class that controlls the whole process (this is actually a design pattern)
For abstracting information from the main class (or any class) you have interfaces and abstract classes
The Design patterns book from the Gang of Four it's a must read in this case.
Something else to keep in mind beside is the simplicity of your design, sometimes trying to fit to a design pattern just cause may end up creating more spaguethi code. As a rule of thumb always try to sepparate the presentation funcionality from the logic, and think of classes as persons talking to eachother and performing jobs (it's kinda weird iknow but sometimes it helps me to think this way)
I was hoping someone could help clarify my options regarding refactoring methods from code-behinds from ASP.NET webforms pages.
As background, we have spent some time recently implementing the repository pattern in both a generic and non generic sense, which has enabled us to move a lot of the DAL methods out of the codebehinds, which is great.
What I'm struggling to finalise, is a sensible approach to moving application logic methods out of the codebehinds which specific focus on the repository/DAL and how best to structure the BL classes.
Here are the two options I am considering at present:
1.Create a Business Logic class per codebehind and from this, expose
methods like getProject(int id) which would behind the scenes,
access a repository instance of repo.GetById(int id)
The benefit of this as far as I can see would be the following:
seperate app logic from the codebehinds, allowing them to be simple
allowing testable methods at the BLL (with some tweaking), kind of synonymous with controller classes in MVC (this is still webforms though)
Doesn't expose the repository directly
The downside would be:
A lot of wrapper methods in the BLL which don't really do anything
besides hide the repository methods
2.Write extension methods on my entity types, e.g. Project.getUsers() which would access a repository instance method allowing BL to be stored without the need for a specific BLL class, thereby reducing the duplication of the wrapper methods in each BL class.
The benefit of this would be:
No need to have a BL as such, storing methods with their entity type
Less wrapper methods, as there wouldn't be a need for ProjectBL.getUsers(projectid) and UserBL.getUsers(projectid) which both call repo.getProjectUsers(projectid) behind the scenes, simple Project.getUsers() from both codebehinds
The downside of this as far as I can tell:
If I introduce new types in the future, e.g. 'SubProject' getUsers() needs to be re-implimented
I'm not too keen on extension methods in general and not sure if this is the right place to use them!
I'm a little unsure which is 'better' practice, or if I've missed a better option all together. It may be worth knowing that initially the repository was being instantiated in the codebehind and accessed directly, but as I understand things, this is not ideal as we risk returning things like IQueryable from the repository and making DAL methods which can be manipulated in codebehind to produce inconsistent results.
The model I have found to be most effective with ASP.NET Webforms is the bind/unbind pattern. In this pattern, the only things you implement in the codebehind itself are event handlers (which will call back to more abstracted, logic-heavy methods in a BLL of some sort) and one method each to transfer data from (Bind) and to (Unbind) an instance of a domain object or DTO.
By structuring the codebehind in this way, the codebehind class becomes concerned only with the interop between logic and presentation, and so becomes quite thin in most cases. The data it will deal with will be primarily primitives and the DTO, and it will not require any knowledge of the DAL (at least, individual page codebehinds won't; you may set up your master page or a base class for your codebehinds to have DAL-touching methods common to wide swaths of your site, basically making this base class your Controller layer in code).
One other thing to keep in mind is that, depending on structure, it can be very simple to unit-test your codebehind classes. You can even TDD them, to a point; the declaration of basic GUI elements in the markup (and their object representations in the codebehind) is still best left to the IDE, but a public codebehind class with publicly-accessible members can be easily instantiated in a unit test, and the public methods exercised.
#KeithS I'm going to mark this one as accepted as no one else seems to have any suggestions! In case you curious I've opted to go more for the second approach, basically in my application I have some logical 'sections' such as 'Projects' or 'ApprovalForms' and I've gone with creating a single BL class per section rather than one per codebehind.
This does mean the class can contain methods which can be a bit varied (not a single purpose), but it does prevent me having tons of classes with basically the same method accessed from a different context. It is forcing me to write wrapper methods around the repository methods which feels a bit W.E.T. but it does mean that I can provide a common method for returning data to the front end, reducing the chance of having differing implementations.
Forgive the title, it's simpler than it sounds.
I've got a class, StickerBook. It contains some stickers, List<Sticker>.
When it's time to see if there any stickers waiting to be added, should StickerBook.CheckForNewStickers() handle the logic of looking for them and then adding them, or should a new class, NewStickerChecker check for and then add them to the StickerBook?
A pretty basic concept I know, I just can't wrap my head around it.
Pretty sure there's no right or wrong answer to this. Either way you seem to be encapsulating the logic rather than making the internals of the class (List) open to all which is generally a good thing.
Putting logic into a separate service class (and having this class implement an interface) could make unit testing easier if you then pass this interface to other pieces of code as a dependency. I think it's conceptually easier to mock up a service class and pass around the actual simple entities during testing rather than mock up entities with complex logic on them.
Well, it depends on what's your general approach to structuring the code and modelling of objects. That said, the Single Responsibility Principle states that object should have only one reason of existence, so I would favor the NewStickerChecker as a class.
there is no black and white and this could be subjective, in my experience if there is an entity which contains a collection of sub-entities, like in your case the book contains a list of stickers, you could load them inside the entity.
After all OOP defines that classes contain data and logic required to manipulate that data ;-)
P.S. just as disclaimer, you are talking of entities in the spirit of Business Entities and not in the Entity Framework light (... not that it would change too much anyway but just for the question's tagging ).
Never sure where to place functions like:
String PrettyPhone( String phoneNumber ) // return formatted (999) 999-9999
String EscapeInput( String inputString ) // gets rid of SQL-escapes like '
I create a Toolbox class for each application that serves as a repository for functions that don't neatly fit into another class. I've read that such classes are bad programming practice, specifically bad Object Oriented Design. However, said references seem more the opinion of individual designers and developers more than an over-arching consensus. So my question is, Is a catch-all Toolbox a poor design pattern? If so, why, and what alternative is there?
Great question. I always find that any sufficiently complex project require "utility" classes. I think this is simply because the nature of object-oriented programming forces us to place things in a neatly structured hierarchical taxonomy, when this isn't always feasible or appropriate (e.g. try creating an object model for mammals, and then squeeze the platypus in). This is the problem which motivates work into aspect oriented programming (c.f. cross cutting concern). Often what goes into a utility class are things that are cross-cutting concerns.
One alternative to using toolbox or utility classes, are to use extension methods to provide additional needed functionality to primitive types. However, the jury is still out on whether or not that constitutes good software design.
My final word on the subject is: go with it if you need, just make sure that you aren't short-cutting better designs. Of course, you can always refactor later on if you need to.
I think a static helper class is the first thing that comes to mind. It is so common that some even refer to it as part of the object-oriented design. However, the biggest problem with helper classes is that they tend to become a large dump. I think i saw this happen on a few of the larger projects i was involved in. You're working on a class and don't know where to stick this and that function so you put it in your helper class. At which point your helpers don't communicate well what they do. The name 'helper' or 'util' itself in the class name doesn't mean anything. I think nearly all OO gurus advocate against helpers since you can very easily replace them with more descriptive classes if you give it enough thought. I tend to agree with this approach as I believe that helpers violate the single responsibility principle. Honestly, take this with a grain of salt. I'm a little opinionated on OOP :)
In these examples I would be more inclined to extend String:
class PhoneNumber extends String
{
public override string ToString()
{
// return (999) 999-9999
}
}
If you write down all the places you need these functions you can figure out what actually uses it and then add it to the appropriate class. That can sometimes be difficult but still something you should aim for.
EDIT:
As pointed out below, you cannot override String in C#. The point I was trying to make is that this operation is made on a phone number so that is where the function belongs:
interface PhoneNumber
{
string Formatted();
}
If you have different formats you can interchange implementations of PhoneNumber without littering your code with if statements, e.g.,
Instead of:
if(country == Countries.UK) output = Toolbox.PhoneNumberUK(phoneNumber);
else ph = Toolbox.PhoneNumberUS(phoneNumber);
You can just use:
output = phoneNumber.Formatted();
There is nothing wrong with this. One thing is try to break it up into logical parts. By doing this you can keep your intellisense clean.
MyCore.Extensions.Formatting.People
MyCore.Extensions.Formatting.Xml
MyCore.Extensions.Formatting.Html
My experience has been that utility functions seldom occur in isolation. If you need a method for formatting telephone numbers, then you will also need one for validating phone numbers, and parsing phone numbers. Following the YAGNI principle, you certainly wouldn't want to write such things until they're actually needed, but I think it's helpful to just go ahead and separate such functionality into individual classes. The growth of those classes from single methods into minor subsystems will then happen naturally over time. I have found this to be the easiest way to keep the code organized, understandable, and maintainable over the long term.
When I create an application, I typically create a static class that contains static methods and properties that I can't figure out where to put anywhere else.
It's not an especially good design, but that's sort of the point: it gives me a place to localize a whole class of design decisions that I haven't thought out yet. Generally as the application grows and is refined through refactoring, it becomes clearer where these methods and properties actually ought to reside. Mercifully, the state of refactoring tools is such that those changes are usually not exceptionally painful to make.
I've tried doing it the other way, but the other way is basically implementing an object model before I know enough about my application to design the object model properly. If I do that, I spend a fair amount of time and energy coming up with a mediocre solution that I have to revisit and rebuild from the ground up at some point in the future. Well, okay, if I know I'm going to be refactoring this code, how about I skip the step of designing and building the unnecessarily complicated classes that don't really work?
For instance, I've built an application that is being used by multiple customers. I figured out pretty early on that I needed to have a way of separating out methods that need to work differently for different customers. I built a static utility method that I could call at any point in the program where I needed to call a customized method, and stuck it in my static class.
This worked fine for months. But there came a point at which it was just beginning to look ugly. And so I decided to refactor it out into its own class. And as I went through my code looking at all the places where this method was being called, it became extremely clear that all of the customized methods really needed to be members of an abstract class, the customers' assemblies needed to contain a single derived class that implements all of the abstract methods, and then the program just needed to get the name of the assembly and the namespace out of its configuration and create an instance of the custom features class at startup. It was really simple for me to find all of the methods that had to be customized, since all I needed to do was find every place that my load-a-custom-feature method was being called. It took me the better part of an afternoon to go through the entire codebase and rationalize this design, and the end result is really flexible and robust and solves the right problem.
The thing is, when I first implemented that method (actually it was three or four interrelated methods), I recognized that it wasn't the right answer. But I didn't know enough to decide what the right answer was. So I went with the simplest wrong answer until the right answer became clear.
I think the reason it's frowned upon is because the "toolbox" can grow and you will be loading a ton of resources every time you want to call a single function.
It's also more elegant to have the methods that apply to the objects in the actual class - just makes more sense.
That being said, I personally don't think it's a problem, but would avoid it simply for the reasons above.
I posted a comment, but thought I'd elaborate a bit more.
What I do is create a Common library with namespaces: [Organisation].[Product].Common as the root and a sub namespace Helpers.
A few people on here mention things like creating a class and shoving some stuff they don't know where else to put in there. Wrong. I'd say, even if you need one helper method, it is related to something, so create a properly named (IoHelper, StringHelper, etc.) static helper class and put it in the Helpers namespace. That way, you get some structure and you get some sort of separation of concerns.
In the root namespace, you can use instance utility classes that do require state (they exist!). And needless to say also use an appropriate class name, but don't suffix with Helper.