Not sure if the title captures what I'm trying to say here.
When designing in OO should I be splitting my objects up into their most specific areas - so if I have a factory object that deals with creating objects but later on i come across a way of creating objects for another purpose even though they may be the same objects is it worth creating a seperate fcatory or just add to the exsiting.
My biggest worry is bulking up classes with tons of stuff, or splitting objects and diluting my projects into a sea of classes.
Any help?
EDIT:
I guess on a side note/sub topic part of me wants to find out the level of granularity you should use in a program. Kind of, how low should you go?
My biggest worry is bulking up classes with tons of stuff, or
splitting objects and diluting my
projects into a sea of classes
This is a very valid point and in any even reasonably sized project, extremely difficult to get right up front especially because realistically, requirements themselves evolve over time in most cases.
This is where "Refactoring" come in. You design based on what you know at any given point and try not too make too many leaps of faith as to what you think the system MAY evolve to.
Given that you know what you are building right now, you design your classes trying to make the best possible use of OO concepts - eg encapsulation / polymorphism. This is itself, like others have noted as well, can be notoriously difficult to achieve and thats where experience, both in designing OO systems as well as knowledge of the domain can really come in handy.
Design based on what you know --> Build It --> Review it --> Refactor it --> Re-design --> and it goes on and on..
Finding the correct level of detail and responsibility is what makes OOP design so difficult. We can help you with a specific case but not with anything this general. If there were algorithms or strict methodologies of how to solve this, everyone could be an OOP designer.
A rule of thumb I like for deciding "is this getting too big now?" is "can I explain the purpose of it concisely?" If you start having to introduce caveats and lots of weasel words to explain the functions of a component of your design (be it class, member variable, method or whatever) it might be a good indicator that it's getting too complex and should be split up.
In your specific case, if you already have a factory object then the DRY Principle (Don't Repeat Yourself) would say that it's a bad idea to create another factory that does the same thing.
Is this an actual problem that you face? Or merely a fear about how your code might grow in the future?
If you are using the same type of object to solve drastically different problems then you may need to redesign the class to focus on seperation of concerns. If you need a more specific answer, you will need to provide an example of a type of class that would need this functionality.
I might have worded things badly in
the Q. I guess I wouldnt be repeating
myself its just more of a case of
where to put the code, it could be
added to an exsiting factory that
creates design objects for exporing
data to excel spreadsheets. On the
other hand I could see it could also
have its own factory for importing
excel data. Both factories would
produce the same objects but the inner
workings are completely different. –
If you aren't doing or plan on doing any class abstraction (subclassing or using interfaces) you may not need to use the factory pattern at all. The factory pattern is generally best suited for supplying objects of a base class type or that implement a specific interface.
Both
factories would produce the same
objects but the inner workings are
completely different.
Not sure if I've understood you correctly, but this sounds like a candidate for the AbstractFactory pattern.
Related
I am an android beginner developer. Currently, I am developing an application. However, my class is quite large because there are many UI components (to handle onClick, onProgressBarChanged, etc.).
Most of my components are dynamic. So, I have method to create those components.
Now I split some methods for initializing UI components into another class.
At this point, I am trying to think/search for a good reason to split my class into several classes.
Advantage: maintainability, testability, reusability
Disadvantage: reduce runtime performance
I am not sure that there is any advantage or disadvantage that I have missed?
Furthermore, I will divide a class when I find an overlap method
I am not sure that there is another situation when a class must be divided.
First, if you've never looked into refactoring, then I would strongly encourage you to do so. Martin Fowler has some excellent resources to get you started. But, I'm getting slightly ahead of myself.
To begin with, you split out classes to maintain a clear delineation of responsibilities. You can think of the SOLID principle here - each class does one thing, and one thing very clearly.
If you notice that a method, let alone a class, is doing more than one thing, then that is a good time to stop and refactor - that is, take the code you have, and apply a particular, focused refactoring to it to improve readability and flow, while maintaining the same functionality. You're essentially looking for code smells - parts of the code that are suspect, not following a specific contract or methodology, or are legitimate anti-patterns - which are, themselves, practices that developers strive to avoid.
Programs that deal with UI (especially in Java) tend to be pretty verbose. What you should avoid doing is placing any conditional business logic in the UI layer, for ease of separability, testing and clarity. Make use of the Model-View-Controller pattern to understand and abstract away the necessary separations between the UI (Views), and the actual work that's needed to be done (Controllers), while maintaining some semblance of state (Models).
We use OOPs Concept in Android(core java) Application Development. If we split our one class in many class it gives a good sense of maintainability, re-usability, Security and Easy change in Coding during Development.
As for example:- Util class for Database handling, Network Class for Internet connection , Dialog class for different type dialog and so...
This way we can categories our coding and change or re use it any time. So it is good practice to follow the OOPS concept during Development.
Thanks
I was going through an article about Object Oriented Programming and it stated that encapsulation means putting related items together, but I don't understand how the article's representative example: UserProfile.js. Though this example is in JavaScript, I'm looking to understand these concepts in Java.
Can anyone explain me these two questions with a pseudo code:
What is encapsulation?
Why do we need encapsulation with pseudo code?
Encapsulation isn't necessarily about putting related items together, it's a technique of hiding internal information of an object. I'm not sure if I agree with the premise of the author of the article you linked... I don't accept that a struct is really a method of encapsulation in the object-oriented sense of the word.
Encapsulation
Psudo [sic] code is a technique for explicitly writing coding logic without the need for syntactical constraints. Considering this context, I don't understand your second question.
Pseudocode
No, that is cohesion.
Encapsulation is hidding things from who doesn't need them.
Michael has it correct.
In Object Oriented programming Encapsulation is the first
pace. Encapsulation is the procedure of covering up of data and
functions into a single unit (called class). An encapsulated object is
often called an abstract data type.
ref: http://www.c-sharpcorner.com/UploadFile/ggaganesh/EncapsulationInCS11082005064310AM/EncapsulationInCS.aspx
Encapsulation is the hiding of the non-essential features.
So why do we need it.
Programing is about translating a solution to a problem into logical code to solve that problem. Because of this, there maybe many complicated methods and functions that we don't want Mr.Joe Blow developer to use. We will encapsulate (or BlackBox) those methods so they cannot be used (they are still used internally). This reduces complexity by only representing important functions and hiding others.
As for needing it in pseudo code, i'm not sure. Michael did a good job with explaining that.
I haven't had enough coffee to give a good example,Plus my Rubik's cube broke :(, i'll write one up for you.
The encapsulation stand for "hiding element for free usage", is a part of Object Oriented Programming paradigm.
It is used to specify the range of visibility elements of code.
Let assume that we have a class with field called password where the password is stored. If this password would be visible for everyone, then there would be no need for a password.
Additional thing is that this helps to maintain the code in order.
Encapsulation isn't goal in OODesign. It is only way to achieve the finest, needed abstraction.
What is encapsulation?
in specific - it means hiding properties from non-desirable access
in overall - it means hiding every project design decision which could be changed in future. Therefore in encapsulation we should consider also e.g. concrete method implementation. From this POV we encapsulate its behavior so that for some POV we don't want to know how it is doing it, knowing only what this method is doing. Encapsulation could be achieved also for example using inheritance mechanism!
How we use encapsulation/
Example - hide every class property. You could as why do we have to do so - it is much effort and unnecessary code! Consider simple example where you can set some int properties. In your scenario - this variable should be in specific range. If someone sets it wrong - how would you design workflow to prevent this action?
More sophisticated but still simple example are collections. In many cases we shouldn't provide full collections to your's object neighbourhood. Encapsulation allows you to provide every property client just a copy of your object. In some cases - it could be helpful.
I think to really understand and appreciate encapsulation you really need a little bit of history.
It used to be that if you wrote a program it would be kind of as though every line of code were printed on a single sheet of paper where everything has knowledge and access to everything else and there are no fancy constructs in which to hide or store variables out of site of your functions.
Lets say you are trying to write some program with 100 different functions and 100 variables. Can you imagine how disorganized and ugly that would get? Effectively, all that code is just a giant formless script that gets executed in some linear fashion and has no real structure, rhyme or reason to it other than that one line of code comes before another line of code and so on.
Encapsulation was invented to take a program like that and give it a skeletal structure, allowing you to hide and organize those 100 functions and variables into a sensible whole. In the case of your user info class here, they take everything that is relating to UserProfile and stick it in a "Capsule" so that it can only be accessed through a reference to to UserProfile. It might look like overkill in this context, but if you have a much larger program, you will be extremely happy to be able to do this.
Its a fancy word for something that is extremely obvious once you understand where the people who created these terms were coming from.
I think encapsulation is closely related to information hiding and abstraction. It is simply the practice of hiding implementation details and object internals from the outside world. It helps both with clarity as well as reducing coupling.
The capabilities of a class are declared in the interface of methods it defines, not in the detail of how they are implemented. Good encapsulation ensures the public interface is sufficient for callers to use without revealing internal implementation details. A well encapsulated design reduces coupling, as the internals can be replaced without affecting everything else that uses that class (through its interface).
I have a complex system to design.
I have two ways:
Top-down: I will design many interfaces and contracts. Afterwords, I will implement these interfaces, and write a prototype to verify the design.
Bottom-up: I will write code to make the system run. Afterwords, I will extract interfaces and contracts from solid code. The distilled interfaces and contracts is my design. It's rule "make it run, make it right".
What is better way? From my opinion, I will choose Bottom-up. Because Top-down is very difficult, no one can design many interfaces at high abstract level,at least it's hard for me. When I write solid implementation to verify the initial design, there are many unreasonable things which force me to re-design from scratch. While I use Bottom-up, I feel quite "safe", it can run at least.
As others have said, it's usually a mix. On a more practical level, the following approach usually helps:
Start by going ABSTRACT Top-Down. Namely, break the system/design into logical components to solve tasks. But don't design precise finalized interfaces for those components. Proceed recursively till some components you arrive at are of "implementation-possible" size (e.g. are the size of a single function/method/class)
Then, go through the resultant component list Bottom-Up, and start designing first draft of interfaces/contracts.
Then, go through the resultant component list Bottom-Up, and start implementing them. This will allow you to:
Have a working and testable code immediately (no need to wait for underlying components to be implemented to test)
You can synthesize the final version of interfaces/contracts for higher level components based on the needs of the already-completed lower level components.
Except in most trivial designs nothing is ever this simplistic. I find that most designs require a mixture of both methodologies to refine.
In my opinion, top-down design is more natural than bottom-up one. E.g.: when you are designing a system, primarly you define its functionality(design interfaces and contracts), then you specify the entities of the system, implement relations among them and so on... Certainly, top-down design is more difficult than bottom-up one, and it requires experienced developers.
I personally also prefer Bottom up - first because you always forget something when doing top-down and then have to fix that and second because at least in my case I get lots of good ideas for the complete system while designing the single components from bottom.
Greetings,
Lorenz
In the real world is nearly impossibile to use these simplistic methodologies to design systems. You usally have to use both of them in multiple iterations.
But this is a simplistic answer, too.
Whilst there are many good examples on this forum that contain examples of coupling and cohesion, I am struggling to apply it to my code fully. I can identify parts in my code that may need changing. Would any Java experts be able to take a look at my code and explain to me what aspects are good and bad. I don't mind changing it myself at all. It's just that many people seem to disagree with each other and I'm finding it hard to actually understand what principles to follow...
First, I'd like to say that the primary reason you get such varying answers is that this really does become an art over time. Many of the opinions you get don't boil down to a hard fast rule or fact, more it comes down to general experience. After 10-20 years doing this, you start to remember what things you did that caused pain, and how you avoided doing them again. Many answers work for some problems, but it's the individual's experience that determines their opinion.
There is really only 1 really big thing I would change in your code. I would consider looking into what's called the Command Pattern. Information on this shouldn't be difficult to find either on the web or in the GoF book.
The primary idea is that each of your commands "add child", "add parent" become a separate class. The logic for a single command is enclosed in a single small class that is easy to test and modify. That class should then be "executed" to do the work from your main class. In this way, your main class only has to deal with command line parsing, and can lose most of it's knowledge of a FamilyTree. It just has to know what command line maps into which Command classes and kick them off.
That's my 2 cents.
I can recommend Alan's and James's book Design Patterns explained -- A new perspective on object-oriented design (ISBN-13: 978-0321247148):
It's a great book about has-a and is-a decissions, including cohesion and coupling in object-oriented design.
In short:
Cohesion in software engineering, as in real life, is how much the elements consisting a whole(in our case let's say a class) can be said that they actually belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.
One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes.
Now the discussion is bigger than this but High Cohesion (or the cohesion's best type - the functional cohesion) is when parts of a module are grouped because they all contribute to a single well-defined task of the module.
Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.
Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…
In long:
I wrote a blog post about this. It discusses all this in much detail, with examples etc. It also explains the benefits of why you should follow these principles. I think it could help...
Coupling defines the degree to which each component depends on other components in the system. Given two components A and B ,how much code in B must change if A changes.
Cohesion defines the measure of how coherent or strongly related the various functions of a single software component are.It refers to what the class does.
Low cohesion would mean that the class does a great variety of actions and is not focused on what it should do. High cohesion would then mean that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.
Note: Good APIs exhibit loose coupling and high cohesion.
One particularly abhorrent form of tight coupling that should always be avoided is having two components that depend on each other directly or indirectly, that is, a dependency cycle or circular dependency.
Detailed info in below link
http://softwarematerial.blogspot.sg/2015/12/coupling-and-cohesion.html
We are following Domain Driven Design for the implementation of a large website.
However by putting the behaviour on the domain objects we are ending up with some very large classes.
For example on our WebsiteUser object, we have many many methods - e.g. dealing with passwords, order history, refunds, customer segmentation. All of these methods are directly related to the user. Many of these methods delegate internally to other child object but
this still results in some very large classes.
I'm keen to avoid exposing lots of child objects
e.g. user.getOrderHistory().getLatestOrder().
What other strategies can be used to avoid this problems?
The issues you are seeing aren't caused by Domain Driven Design, but rather by a lack of separation of concerns. Domain Driven Design isn't just about placing data and behavior together.
The first thing I would recommend is taking a day or so and reading Domain Driven Design Quickly available as a free download from Info-Q. This will provide an overview of the different types of domain objects: entities, value objects, services, repositories, and factories.
The second thing I would recommend is to go read up on the Single Responsibility Principle.
The third thing I would recommend is that you begin to immerse yourself in Test Driven Development. While learning to design by writing tests first won't necessarily make you designs great, they tend to guide you toward loosely coupled designs and reveal design issues earlier.
In the example you provided, WebsiteUser definitely has way too many responsibilities. In fact, you may not have a need for WebsiteUser at all as users are generally represented by an ISecurityPrincipal.
It's a bit hard to suggest exactly how you should approach your design given the lack of business context, but I would first recommend doing some brain-storming by creating some index cards representing each of the major nouns you have in your system (e.g. Customer, Order, Receipt, Product, etc.). Write down candidate class names at the top, what responsibilities you feel are inherent to the class off to the left, and the classes it will collaborate with to the right. If some behavior doesn't feel like it belongs on any of the objects, it's probably a good service candidate (i.e. AuthenticationService). Spread the cards out on the table with your colleges and discuss. Don't make too much of this though, as this is really only intended as a brainstorming design exercise. It can be a little easier to do this at times than using a whiteboard because you can move things around.
Long term, you should really pick up the book Domain Driven Design by Eric Evans. It's a big read, but well worth your time. I'd also recommend you pick up either
Agile Software Development, Principles, Patterns, and Practices or Agile Principles, Patterns, and Practices in C# depending on your language preference.
Although real humans have lots of responsibilities, you're heading towards the God object anti-pattern.
As others have hinted, you should extract those responsibilities into separate Repositories and/or Domain Services. E.g.:
SecurityService.Authenticate(credentials, customer)
OrderRepository.GetOrderHistoryFor(Customer)
RefundsService.StartRefundProcess(order)
Be specific with naming conventions (i.e. use OrderRepository or OrderService, instead of OrderManager)
You've run into this problem because of convenience. i.e. it's convenient to treat a WebsiteUser as an aggregate root, and to access everything through it.
If you place more emphasis on clarity instead of convenience, it should help separate these concerns. Unfortunately, it does mean that team members must now be aware of the new Services.
Another way to think of it: just as Entities shouldn't perform their own persistence (which is why we use Repositories), your WebsiteUser should not handle Refunds/Segmentation/etc.
Hope that helps!
A very simple rule of thumb to follow is "most of the methods in your class HAVE to use most of the instance variables in your class" - if you follow this rule the classes will be automatically of the right size.
I ran into the same problem, and I found that using child "manager" objects was the best solution in our case.
For example, in your case, you might have:
User u = ...;
OrderHistoryManager histMan = user.getOrderHistoryManager();
Then you can use the histMan for anything you want. Obviously you thought of this, but I don't know why you want to avoid it. It seperates concerns when you have objects which seem to do too much.
Think about it this way. If you had a "Human" object, and you had to implement the chew() method. Would you put it on the Human object or the Mouth child object.
You may want to consider inversing some things. For example, a Customer doesn't need to have an Order property (or a history of orders) - you can leave those out of the Customer class. So instead of
public void doSomethingWithOrders(Customer customer, Calendar from, Calendar to) {
List = customer.getOrders(from, to);
for (Order order : orders) {
order.doSomething();
}
}
you could instead do:
public void doSomethingWithOrders(Customer customer, Calendar from, Calendar to) {
List = orderService.getOrders(customer, from, to);
for (Order order : orders) {
order.doSomething();
}
}
This is 'looser' coupling, but still you can get all the orders belonging to a customer. I'm sure there's smarter people than me that have the right names and links referring to the above.
I believe that your problem is actually related to Bounded Contexts. For what I see, "dealing with passwords, order history, refunds, customer segmentation", each one of these can be a bounded context. Therefore, you might consider splitting your WebsiteUser into multiple entities, each one corresponding to a context. There may arise some duplication, but you gain focus on your domain and get rid off very large classes with multiple responsibilities.