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 9 years ago.
Improve this question
Increasingly in our spring (or equivalent) wired world of services, the Java code I see seems more & more procedural, with not much emphasis on modelling the problem in OO.
For example, a service that has stuff to do may well inline that in the service method in the singleton service class – maybe over several hundred lines. Alternatively, local methods may be created, but because the service is stateless, these are invariably called with a stack (no pun intended) of needed args. It’s noisy.
Guess this maybe my original OO background in Smalltalk to the fore here, but modelling the problem in OO has always seemed to me to be the way to go. That is, modelling with objects which have state as well as behaviour.
An alternative approach might be to create a stateful prototype delegate invoked from the service, which is either wired or loaded with the necessary (entities, singleton DAO/services etc) In addition some other decorators might be created to wrap entities (esp collections) to provide some model list behaviour (I have a list af accounts, I have some list based behaviour – this must be a class holding the list, it must not be just the technical List class and its usage behaviour inlined in the service (but usually is))
But.
Creating some objects of this kind uses memory, and in a high throughput environment, this might result in the creation of thousands of small strategy/decorator instances.
So what is the real world impact of that? Will the extra GC screw the performance or, assuming a JVM instance around a couple of GB, can Java cope?
Has anyone delivered a Java SOA based on these principles? Are there any papers on the subject?
Thanks for reading this far.
Real-world problems usually are a mix of object-based and procedural logic, especially in the business world where transactions involve needing to manipulate a number of distinct objects simultaneously. Certainly most real code could use improvement and refactoring, especially after a few years of moving-target requirements, and better understanding and use of AspectJ could clean up a lot of the procedural boilerplate, but it doesn't make sense to force all logic into a strong OOP pattern if it doesn't match the way that a real-world instructor would describe it to a trainee.
What you're describing is basically the Command pattern, and while there are situations where it is useful (it's essentially the role of Runnable), it's usually not worth using unless there are time-based considerations (serial execution, parallelism) or the transaction itself needs to be persistent (such as for banking).
Related
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 3 months ago.
Improve this question
Can a Plain Old Java Object have methods that deal with business logic other than just the getter/setter methods?
I see possibly mixed answers for this so is there no rigorous definition for this? I know a POJO cannot implement an interface, extend a class, and not use annotation.
You seem to be getting caught up in details of a formal definition that does not exist.
“POJO” is not a precise formal term. “POJO” is a catchy casual term coined by Martin Fowler, Rebecca Parsons, and Josh MacKenzie back in 2000.
The idea of a POJO is an object that is not enmeshed in a complicated framework. Any experienced Java programmer should be able to read and understand the source code of a POJO without needing to learn some framework, and without needing to look up third-party documentation.
Annotations
So, a POJO will generally have few annotations only because because Java bundles few annotation classes. Most annotations come from external frameworks. So if we are avoiding the complications of external frameworks, we are avoiding most annotations.
Personally, I would add an exception for one framework: Jakarta Bean Validation (Wikipedia). This framework is relatively simple, does not involve any elaborate involvement, and focuses on the validity/integrity of the POJO’s own internal field values. The validation rules are applied as annotations.
Logging might be another framework exception. And maybe Java Management Extensions (JMX) monitoring too. Notice that all three of my own personal choice in framework exceptions are focused on the POJOs themselves, as opposed to orchestrating some elaborate involvement with other objects.
Business logic
And, yes, a POJO can have business logic, especially regarding its own internal state, and regarding its need to communicate its changes with the outside world such as persisting data and notifying other interested parties.
Indeed, you can learn about:
Hexagonal Architecture by Dr. Alistair Cockburn(and related variations, Onion Architecture, etc.)
Domain-driven design (see book by Eric Evans)
… to see how you can use POJOs as domain objects (“business objects”, with core business logic) while keeping them separate and protected from various elaborate frameworks operating in other parts of your app.
Data-only objects
Some classes are intended to simply carry data. All such data-only classes are POJOs. But not all POJOs are data-only classes.
I suggest you learn about Data Transfer Objects and Value Objects, as kinds of data-only classes.
If the main purpose of your class is to communicate data transparently and immutably, use the records feature in Java 16+. In a record, by default, the compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
And let me be clear: there is nothing wrong necessarily with elaborate complicated frameworks. They can be exquisitely useful, obviously. That's why they were invented. Each framework has a purpose and a place.
The term POJO was invented so that in discussions about programming and system architecture/design we can make the distinction between classes that are simple and not entwined versus those classes that are complicated and entwined.
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!
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 know that it is more time consuming to find an object in the heap than in stack. And I have also seen that people advising to create more classes for different tasks. May be the code can be more understandable and clean if there are more classes. But,what about the time? can anyone please explain that to me.
Object-oriented programming means more separation of concerns and a good segregation of concepts.
It tries to address problems closer to how our mind works. Real world has uncountable objects and things. Each one has a definition and properties, and also behaviors.
Clearly object-oriented programming may use more memory and even CPU power, but more than 2 decades ago everyone thought that, once computer raw power and memory were increased every year, optimization was still important but productivity became the priority.
There're still some corner cases where object-oriented programming isn't the answer, but almost any business or home-use application in the world is developed using object-oriented programming because companies want to ease maintanability and be able to respond to change in a meaningful and productive way (to do more and reduce costs).
Your code, more often than not, will be a solution to a problem. The number of classes isn't something that you predetermine. It depends on the complexity of the problem to be solved and the complexity of its solution. If the raison d'etre of your code is just to find the nth fibonacci number and nothing else then the code may reside in just a single class(or none at all) but if your code is, say, an enterprise software designed to tackle a complex problem like banking then there are many factors that decide your design and thereby the number of classes. Two of the biggest factors are maintainability and extensibility of your code.
You should have a look at the SOLID principles for Object Oriented design, first named by Robert C. Martin.
Once you go through them and more on OO design I hope "more classes vs less classes" won't be a question for you.
I don't think it's a decision being made in order to boost performance, being the difference irrelevant at runtime IMHO. Neither I think the developing time is going to differ a lot. I think what it's important to understand here is the Single Responsibility Principle. So I think the criteria isn't "create more classes" but "do not use the same class for two different things", (what in the end makes you create more classes, but isn't the same).
What I've realized on the time I've been working is that, while the system grows up, the most important thing is how it does it. If you create less classes you will end up with 30k lines classes that are completely impossible to debug efficently. The same applies with 400 lines methods doing 20 different things. This means a lot of extra time wasted as adding new functionalities and fixing existing ones become more and more complex. In the end you need to apply a certain criteria to separate your code and avoid ending up on tha situation and the Single Responsibility Principle seems a good one.
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.
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
A friend of mine is talking about these design techniques regarding state transitions of an object (he's a Java guru, btw), performed without having a boolean myState member, but rather declaring the myState member as an object that implements the same interface of the "owner" one.
Ok, I've been too much cryptic, so you can find the discussion here, with code samples.
Personally, I'm excited with the approach, as my friend explained me the philosophy behind it; I also think it is pretty coherent, from a design perspective. My concerns, by the way, are mainly about performance and memory usage, as maybe compile-time and run-time optimizations enter the game. Since I don't know JIT compiler and JVM internals, I'm curious to have a wider opinion.
What do you think about?
I have to disagree - useful design patterns aside, this particular example is ridiculous overkill:
a 15-line class with an easily-understandable process
became a 50-line class with an obfuscated purpose
I fail to see how this is an improvement - it violates YAGNI1 and ASAP2, bloats the code, and reduces efficiency (multiple objects instantiated to do the job when not required).
As an intellectual exercise, mildly interesting. As a programming habit, terrifying! ;-)
1 YANGI = You Ain't Gonna Need It
2 ASAP = As Simple As Possible
It sounds like you're asking whether there's a "concretely useful" benefit to using the state design pattern, to which I'd say definitely yes, particularly if your app actually relies heavily on the "state" of its objects. A popular canonical example is that of the video player, which is always in one state, and can only transition into different states depending on the state it's currently in (e.g., it can't stop if it's already stopped, but it can play, and it can rewind, and so on).
While that particular example can be managed relatively easily with a handful of if/else/switch-type conditions (if (isStopped()), play(), etc.) because there aren't that many states to deal with, when states or their transition rules start to become more numerous or complicated, the state pattern absolutely becomes quite valuable, as without it, your code tends to accumulate elseifs like crazy, and things become less and less readable and manageable over time.
So yes, in general, if you find your objects' behaviors varying according to their states (if isStopped() play() / elseif isPlaying() stop() / elseif (isBroken() fix()), etc.), then yes, do consider using the State pattern. It's a bit more work up front, but generally well worth the effort, and done right I doubt you'd notice any significant overhead simply for the using of it.
Head First Design Patterns offers a great description of its hows and whys, too -- I highly recommend picking up that book to pretty much anyone writing object-oriented code.
The state/strategy patterns are tried and true. They aren't just an intellectual exercise. If you're thinking about performance and memory usage now...you are probably shooting yourself in the foot. Get code...then profile.
Its a very useful technique.
You don't propagate if(myState) statements around your class.
You can extend the technique to many states and only have to change what you assign to the myState member.
As for performance and memory usage, wait until you've got something to measure - maybe you need to try both ways and measure them both when they're working.
Yes, this works, and is cool ... up to a point (the point where it becomes silly). You can even use anonymous inner classes, if you must, even enums.