Why do we sometimes separate behaviour from classes in Java [closed] - java

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
Its a pretty basic question but I am new to Java designing to please excuse me. :)
I want to know in which scenarios we need to separate the class behavior from the class itself.
for e.g.
If I have an class Employee, I will have some data in it like - name, age etc. Also this class will have some behavior like doWork() etc. Now in what scenario we can have data and the behavior inside once class (Employee) only and in which scenario we need to have 2 different classes for Employee data (EmployeeDTO) and behavior (EmployeeService)
Very subjective question but am looking for some inputs on a design of a small application where I am taking data from a text file. Should I put the data and behavior in different classes or same? What will be your reason to justify this decision?
PS: Any links to information on this will also be very useful :)
Thankyou

Good object-oriented design advocates that each class obey the Single Responsibility Principle. Which I can't summarize any more eloquently than the wikipedia entry:
Martin defines a responsibility as a reason to change, and concludes
that a class or module should have one, and only one, reason to
change. As an example, consider a module that compiles and prints a
report. Such a module can be changed for two reasons. First, the
content of the report can change. Second, the format of the report can
change. These two things change for very different causes; one
substantive, and one cosmetic. The single responsibility principle
says that these two aspects of the problem are really two separate
responsibilities, and should therefore be in separate classes or
modules. It would be a bad design to couple two things that change for
different reasons at different times.
If you think about it, you could jam all of your Java code into one class file, but you don't. Why? Because you want to be able to change, maintain, adapt and test it. This principle says that instead of dividing your code up arbitrarily into different modules, you should take the tact that things should be broken up by their logical responsibilities. This generally means more, small modules which we know to be easier to change, maintain, adapt and test.
I personally would recommend that you factor your code out into smaller discrete classes and combine them later if this proves to be unreasonable -- this will become obvious to you. Its much easier to combine loosely-coupled code in the future than it is to factor out tightly-coupled code.

Do the simplest thing possible. You can always make your code more generalized later and there's a good chance you won't even have to do it.
Apply YAGNI principle every time you need to make a decision. Extreme Programming wiki is also a nice reading.
Put everything into one class right now. When you see your Employee is getting too fat then you can do some refactoring - for example, move method to another class. In statically typed languages like Java it is super easy because compiler helps a lot and IDE support is great.
Reading from file, for example, looks like an obvious candidate to extract to a separate loader class. On the other hand if you have a very common format as input such as XML or JSON you could just create static method List<Employee> Employee.loadFromFile(string fileName) and implement reading logic in a couple of lines of code. It's good enough right now: simple, short and works fine.
May The Real Ultimate Programming Power be with you!

By keeping business logics out of pojo, thus making it a pure transfer object, you have the benefit of loose coupling should one day you find yourself in the situation for the need to switch from Spring framework to EJB JavaBeans.
By putting data and business logic together, it becomes a domain object. The simplest form of managed bean usage promoted in JSF2 uses the domain model whereby the "action" is fused together with form data.
If you choose the first model, you can cleanly separate concerns for designing inheritence and polymorphism for your data objects, while not being bothered if the behaviors defined are making sense, and vice versa.

You use a DTO (like the acronym suggests) when you want to move data around using the lightest weight way possible, such as over the wire to a service.

For the record
Its the classic rich domain object vs anemic domain object.
In general, if you have an UI Object or a Library Object (for example the class Date or the class TextButton), and may be some other kind of Objects then may be you can wrap all in a single Class instead of relies in different classes just for commodity to have all the attributes and methods in the same class.
However, for a classic Business Object (BO) is different. Even if you want a rich domain object, excluding some other problems that i don't want to mention at this point, is the fact that the Business Service (BS) Layer acts as a "fat burning diet plan" and it turns every rich BO into a anemic BO.
Rich BO -------> BS ----------> Anemic BO.

Related

Doubts spring mvc [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 5 years ago.
Improve this question
I'm developing a Spring Boot MVC application and, after reading many guides and comments, I still have some doubts that I have not unmarked.
1: I do not want an anemic pattern, so I do not have a monolithic service where all the services are called each other, but these communicate only with repository instantiating entity, inside which I put the business logic, correct?
2: where to put the conversion functions entitiy-> dto? I read that someone puts them in the Controller, others in the Service, others on the same domain .. at the moment the cleanest solution and I prefer to have a Builder of the DTO that lends the entity input, okay I have contraindications?
3: polymorphism and inheritance: I have a service that composes some menu levels according to an attribute of the entity in question. I do not want to have blocks of if anywhere, I wanted to be able to put this logic in a single point, to instantiate the correct class (which I do not know a priori) and to exploit the polymorphism, how can I do? considered to involve service, entity and related logic ..
thank you so much
Your questions are more related to software design in general rather than specific to the Spring framework. Allowing the framework to dictate how to organize your code, has some downsides.
But to answer your questions:
Depending on how complex and interrelated your model is, there are different options, for the cases where there is not big interdependence between the entities in the model, the 3 layer approach is simple and good enough, but if your model is more complex, you could take a look into the concept of Aggregates, and keep the invariants hidden inside.
Constructing the DTO with the Entity as parameter is a good solution, whenever changes needs to be made to either the DTO or the Entity, the amount of code to maintain is not as much as with other approaches, it is not just about the conversion code, it is also about methods signatures, and all of the usages. This approach also follows the Dependency Inversion principle which states that low level modules (presentation in this case) should depend on high level policies (business logic) and not the other way around. But it is not the only valid solution, it always depends on your concrete case.
If you want to return an object from your service that can be an instance of different types, there are different ways to do so, a way to do so (but not the only one, and again, the best way always depends on your concrete case):
For the type control, one option would be to make the method return type an interface, and then have the possible different objects that can be returned to extend that interface.
For the construction of the different objects, you can encapsulate it inside of the service in a private function if that is the only place you are going to use it, or if you are going to use it in more places, then you could extract it to a factory and use it as a colaborator of the service. For the construction you won't be able to avoid the if checks, but outside the service, once you serve the different instances, then you won't need to do more if checks.
and finally in the service return the instance that you constructed, as it implements the interface, the compiler will still be happy about it.
Hope it helps!

Is private necessary for a standalone Java app? [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 have read through a bunch of best practices online for JUnit and Java in general, and a big one that people like to point out is that fields and methods should be private unless you really need to let users access them. Class variables should be private with getters and setters, and the only methods you should expose should be ones that users will call directly.
My question: how strictly necessary are these rules when you have things like standalone apps that don't have any users? I'm currently working on something that will get run on a server maybe once a month. There are config files that the app uses that can be modified, but otherwise there is no real user interaction once it runs. I have mostly been following best practices but have run into issues with unit testing. A lot of the time it feels like I am just jumping through hoops with my unit testing getting things just right, and it would be much easier if the method or whatever was public or even protected instead.
I understand that encapsulation will make it easier to make changes behind the scenes without needing to change code all over, but without users to impact that seems a bit more flimsy. I am just making my current job harder on the off-chance it will save me time later. I've also seen all of the answers on this site saying that if you need to unit test a private method you are doing something wrong. But that is predicated on the idea that those methods should always be private, which is what I am questioning.
If I know that no one will be using the application (calling its methods from a jar or API or whatever) is there anything wrong with making everything protected? Or even public? What about keeping private fields but making every method public? Where is the balance between "correct" accessibility on pieces of code, and ease of use?
It is not "necessary", but applying standards of good design and coding principles even in the "small" projects will help you in the long run.
Yes, it takes discipline to write good software. Languages are tools that help you accomplish a goal. Like any tool, they can be misused, and when misused can be dangerous. Power tools, like a table saw, can be very dangerous if misused, so if you care about your own safety you always follow proper procedure, even if it might feel a little inconvenient (or you end up nicknamed "stubby").
I'd argue that it's on the small projects, where you want to cut corners and "just write the code", that adhering to the best practices is most important. You are training yourself in the proper use of your tools, so when it really matters you do the right thing automatically.
Also consider that projects that start out "small" can evolve over time to become quite large as you keep adding enhancements and new functionality. This is the nature of agile software development. If you followed best practices from the start you'll find it much easier to adapt as the project grows.
Another factor is that using OOP principles is a way of taming complexity. If you have a well-defined API and, for example, use only getters and setters, you can partition off the API from the implementation in your own mind. After writing class A, when writing a client of A, say B, you can think only about the API. Later when you need to enhance A you can easily tell what parts of A affect the API vs what parts are purely internal. If you didn't use encapsulation you'd have to scan your entire codebase to see if a change to A would break something else.
Do I apply this to EVERYTHING I write? No, of course not. I don't do this with short single-use scripts in dynamic languages (Perl, AWK, etc) but when writing Java I make it a point to always write "good" code, if only to keep my skills sharp.
There is generally no necessity to follow any rules as long as your code compiles and runs correctly.
However code style "best practices" have proven to enhance code quality, especially over time when a project develops/matures. Making fields private makes your code more resilient to later changes; if you ommit the getters/setters and access fields directly, any changes to a field impact related code much more directly.
While there is seemingly no advantange in a getter/setter at first, the advantage lies in the future: A getter forces any code working with the attribute through a single point of control which in case of any changes related to that field helps either mask the concrete representation/location of the field and/or allows for polymorphism when required whithout changes/checking all the existing callers.
Finally the less surface (accessible methods/fields) a class exposes to other classes (users) the less you have to maintain. Reducing the exposed API to the absolute minimum reduces coupling between classes, which again is an advantage when something needs to be changed. Striving to hide the inner workings of every object as good as possible is not a goal by itself, its the advantages that result from it that are the goal.
As always, good balancing is always required. But when in doubt, it is better to error/lean on the side of "source code quality" practices; instead of taking too many shortcuts; as there are many different aspects in your "simple" question one should consider:
It is hard to anticipate what will happen to some piece of software over time. Yes, you don't have any users today. But you know what: one major property of great tools is ... as soon as other people see them, they want to use them, too. And all of a sudden, you have users. And feature requests, bug reports, ... and make no mistake: first people will love you for the productivity gain from your tool; and then they will start to put pressure on you because all of a sudden your tool is essential for other people to make their goals.
Many things are fine to be addressed via convention. Example: sometimes, if I would only be using public methods of my "class under test", unit tests become more complicated than necessary. In such a case, I absolutely have no problem about putting a getter here or there that allows me to inspect the internal state of my "class under test"; so that my test can trigger some activity; and then call the getter. I make those methods "package protected"; and I put a // used for unit testing above them. I have not seen problems coming out of that informal practice. Please note: those methods should only be used in test cases. No other production class is supposed to call them.
Regarding the core of your question on private stuff: I think, one should always hide implementation details from the outside. Whenever you write a piece of code that is supposed to live longer than the next hour, you should do the right thing - and try to write code with very high quality. And making the internals of your objects visible on the outside
comes only with drawbacks; there is nothing positive in doing so.
Good OO is about using models that come with certain behavior.
Internal state should stay internal; there is no benefit in
exposing. For the record: sometimes, you have simple data
containers. Classes that only have some fields, but no methods on
them. In that case, yeah, make the fields public; there is (not
much) advantage in providing getters/setters. ( See "Clean Code" by
Robert Martin, chapter 6 on "Objects and Data structures")

OOP design - creation strategies/patterns

For OOP practice I am working on a hobby project, a quiz program which reads a table from txt file and asks questions about entries in the table. The idea is to have this facilitate learning of the material given for a course in our dept.
So far I wrote the I/O bit, put together a pretty modest GUI and the classes to represent the different types of entities in the datatable. I am not sure about how to proceed with the core of the program though, I mean question generation and validation.
My first idea was to have a class AbstractQuestion which pretty much defines what a question is and what fields it has (a string representation, an answer and a difficulty level). Then I thought I could write classes for different types of questions, for instance one class for simple value inquiries (like giving the name of an entity and asking for a particular property), another class for more complicated questions (for instance inquiring about interactions of entities etc).
I am not sure if this is the best way to go however. Can't really express why but I have a feeling that this is not the neatest way to go about it. Would it make sense to work on a Factory class? Essentially I need to:
provide means for a question to be generated based on one, or more, entities randomly picked from the datatable
different types of questions need to be created on the runtime, based on input from the user (desired difficulty level)
questions need to be validated and the user needs to be notified by the main Quiz class (so the questions need to be accessible).
I could start simple and implement only one type of question, get it to work and add new features in time but I think it's good practice to improve my understanding of OOP, and besides I'm afraid if it works and I start giving it out for people to test it out, I'll eventually end up working on something else. I'd like to be able to conceptualize my project better, and I think this could be a good opportunity to improve that.
PS: In case it wasn't obvious, I am not a programmer by educational background :)
You could use an Abstract Factory to create factories that know how to create questions based on specific parameters.
As for the notification you could use Observer Pattern. Study them and see examples in the language of your preference
Think in terms of two things:
What objects use Question objects? What do they need Questions to do? That is we talk about the Interface(s) of the Question.
How do Questions do those things? The Behaviour of the Question.
Initially, think only about the Interfaces. I'm not clear what we need the question to do. Seems to me that a question whose answer is free-form text and a question which offers a "Pick one of A to D" and a question which asks "Pick one or more of A to D" might well loom very different in a UI. So are you thinking in terms of "Question: please display yourself, get your answer and tell me the user's score" or "Question: what is your text? Question: what kind of answer do you take? Question : what are your four options? Question: the user entered 'a' what did they score?"
Once you've got the idea of the question's responsibilities clear, then you can consider the appropriate number of different Question interfaces and classes, and hence decide whether you need a creational pattern such as Factory. Factory works well when you have a number of different classes all implementing the same interface.
Factory: go make me a question. Question: go and ask the user.
I've got simple quiz application running on production =) There are different type of questions, with different behaviours (they should be asked, answered and tipped in different fashion). Questions have different complexity etc.
In my situation, the most appropriate solution, was creation Question superclass with some abstract methods (it could be an interface as well) and different implementation. And there were QuestionGenerator (works as a factory), factory, based on some input return different implementation.
Think, about your interface (common part) of your question and use factory pattern.
There could be more complicated scenario, where you can find some advantages of using AbstractFactory or Builder patter.
In my simple case, extracting interface was enought

Splitting objects into their most fundamental parts

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.

How much business logic should Value objects contain? [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 2 years ago.
Improve this question
One mentor I respect suggests that a simple bean is a waste of time - that value objects 'MUST' contain some business logic to be useful.
Another says such code is difficult to maintain and that all business logic must be externalized.
I realize this question is subjective. Asking anyway - want to know answers from more perspectives.
The idea of putting data and business logic together is to promote encapsulation, and to expose as little internal state as possible to other objects. That way, clients can rely on an interface rather than on an implementation. See the "Tell, Don't Ask" principle and the Law of Demeter. Encapsulation makes it easier to understand the states data can be in, easier to read code, easier to decouple classes and generally easier to unit test.
Externalising business logic (generally into "Service" or "Manager" classes) makes questions like "where is this data used?" and "What states can it be in?" a lot more difficult to answer. It's also a procedural way of thinking, wrapped up in an object. This can lead to an anemic domain model.
Externalising behaviour isn't always bad. For example, a service layer might orchestrate domain objects, but without taking over their state-manipulating responsibilities. Or, when you are mostly doing reads/writes to a DB that map nicely to input forms, maybe you don't need a domain model - or the painful object/relational mapping overhead it entails - at all.
Transfer Objects often serve to decouple architectural layers from each other (or from an external system) by providing the minimum state information the calling layer needs, without exposing any business logic.
This can be useful, for example when preparing information for the view: just give the view the information it needs, and nothing else, so that it can concentrate on how to display the information, rather than what information to display. For example, the TO might be an aggregation of several sources of data.
One advantage is that your views and your domain objects are decoupled. Using your domain objects in JSPs can make your domain harder to refactor and promotes the indiscriminate use of getters and setters (hence breaking encapsulation).
However, there's also an overhead associated with having a lot of Transfer Objects and often a lot of duplication, too. Some projects I've been on end up with TO's that basically mirror other domain objects (which I consider an anti-pattern).
You should better call them Transfer Objects or Data transfer objects (DTO).
Earlier this same j2ee pattern was called 'Value object' but they changed the name because it was confused with this
http://dddcommunity.org/discussion/messageboardarchive/ValueObjects.html
To answer your question, I would only put minimal logic to my DTOs, logic that is required for display reasons.
Even better, if we are talking about a database based web application, I would go beyond the core j2ee patterns and use Hibernate or the Java Persistence API to create a domain model that supports lazy loading of relations and use this in the view.
See the Open session in view.
In this way, you don't have to program a set of DTOs and you have all the business logic available to use in your views/controllers etc.
It depends.
oops, did I just blurt out a cliche?
The basic question to ask for designing an object is: will the logic governing the object's data be different or the same when used/consumed by other objects?
If different areas of usage call for different logic, externalise it. If it is the same no matter where the object travels to, place it together with the class.
My personal preference is to put all business logic in the domain model itself, that is in the "true" domain objects. So when Data Transfer Objects are created they are mostly just a (immutable) state representation of domain objects and hence contain no business logic. They can contain methods for cloning and comparing though, but the meat of the business logic code stays in the domain objects.
What Korros said.
Value Object := A small simple object, like money or a date range, whose equality isn't based on identity.
DTO := An object that carries data between processes in order to reduce the number of method calls.
These are the defintions proposed by Martin Fowler and I'd like to popularize them.
I agree with Panagiotis: the open session in view pattern is much better than using DTOs. Put otherwise, I've found that an application is much much simpler if you traffic in your domain objects(or some composite thereof) from your view layer all the way down.
That said, it's hard to pull off, because you will need to make your HttpSession coincident with your persistence layer's unit of work. Then you will need to ensure that all database modifications (i.e. create, updates and deletes) are intentional. In other words, you do not want it be the case that the view layer has a domain object, a field gets modified and the modification gets persisted without the application code intentionally saving the change. Another problem that is important to deal with is to ensure that your transactional semantics are satisfactory. Usually fetching and modifying one domain object will take place in one transactional context and it's not difficult to make your ORM layer require a new transaction. What is challenging is is a nested transaction, where you want to include a second transactional context within the first one opened.
If you don't mind investigating how a non-Java API handles these problems, it's worth looking at Rails' Active Record, which allows Ruby server pages to work directly with the domain model and traverse its associations.

Categories