Is every cyclic references between Java packages bad? [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 1 year ago.
Improve this question
I've been using Sonar code quality management platform for some time, and for the most cases I find it very helpful in revealing hidden design flaws of my code base.
However, there's one rule that gives me more annoyance than help and that is its check for 'cyclic package reference' violations.
I guess I fully understand where such a dependency between packages is a bad thing. For example, in a typical 3-tier presentation/service/persistence layered design, it's almost always a bad idea to let the database handling code have a reference back to UI related classes. I have no problem with calling it a 'violation'.
But let's consider other cases, i.e. like designing an IDE-like application. Say, we have a main package which contains an Application interface, which defines List<View> Application.getViews() method to reference application's views.
However, when the View interface has an Application getApplication() method to refer back to its parent application, which I believe is a quite common design, it will introduce a cyclic reference, provided each of the interfaces are separated in com.myapp.ui, and com.myapp.ui.view respectively.
Of course, you can just put the View interface into the com.myapp.ui to break the cycle. But when you have various other view related APIs in com.myapp.ui.view, many of them another abstract APIs like AbstractView, ContentView, AbstractContentView, etc. I wonder if it's more advisable to keep them in separate packages for a management purpose.
And consider the said application has many other similar cases like com.myapp.ui.action, com.myapp.ui.perspective, etc. which would really make com.myapp.ui package crowded if we are to put them all in there.
So, what approach do you suggest to handle such a situation? Are really every cyclic package references a bad thing? Or if I have to live with them, how do you configure Sonar to check only real, problematic cycles?

Every absolute -- except this one ;) -- is going to be wrong some of the time. So, is every cyclic reference bad? No. You have to use your judgement.
But if you do introduce a cyclic dependency, it's worth asking if you really need it, and why. The tl;dr is that more often than not, you may find that breaking the cycle can improve your modularity, and in particular your ability to test components separately.
To use your example, does a view really need a getApplication(), which presumably returns a relatively "heavy" object (ie, one that itself needs a database, network, etc etc)? Maybe... but maybe not. If what you really need from that getApplication is something with a few callbacks (such as when a user initiates some action), then it could be useful to create an interface in some common package for that callback. So, rather than:
com.foo.app.Application
com.foo.view.View
Application getApplication()
You'd have:
com.foo.common.Callback // maybe just a Callable, Runnable, etc?
com.foo.app.Application
provides a Callback for some action foo
com.foo.view.View
Callback getFooCallback()
The question you should be asking is: what does that give me? It could be that you have to stub out so much that it doesn't give you much -- though that may suggest you can break apart your classes some. But it could be that it actually makes it easier to test your view, because now your unit test can (1) test the view without spinning up a whole application, and (b) provide a "dummy" callback that does something like saving a string that describes the action, and then your unit test asserts that it saved the right string.

And indeed there is an open JIRA ticket to prevent considering a cycle between father/child packages as a quality flaw : http://jira.codehaus.org/browse/SONAR-3452

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")

BestPractices: Is it bad OOP to subclass standard classes into a new one that does same thing, but "presuming" future changes? [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 8 years ago.
Improve this question
I have had similar cases in the past, and this is just an example to illustrate:
I'm going to implement a new feature in my android app (but this applies to any kind of OO project), and at this point I need to implement some "action" in the "setVisibility" method from EVERY edittext in EVERY activity I have.
To do it, I have to subclass "EditView", and override "setVisibity" method:
#Override
public void setVisibility(int visibility)
{
super.setVisibility(visibility);
// --> do my stuff here! <--
}
So far, so good... the problem is to change all activities I have (more than 200, and thounsands code lines), and then I think: "why on earth didn't I start the project subclassing the standard EditText, 'cos I knew some point I'll need to implement something like this".
That's the point: Is it bad OOP to subclass a "standard class" into a new one that does exaclty same thing, but just "presuming" cases like that? I mean, subclass everything, like buttons, activities, etc.
AFAIK, desing pattern and OOP discourage the "presuming factor", but I'd to hear what you guys "do in real life" (or think about that), based on your programming experience.
Also, maybe this type of question ("what you think", "what your oppinion") isn't a good practice here in SO, but I can't find any better place to put it on.
There's no reason to stub out code unless you're actually making changes. It's wasted effort, and just bloats your codebase.
If you find yourself in a situation where you're repeatedly making the same modification, consider refactoring to share common code. Or in certain cases, there's merit to generating those pieces of code (for example, Avro does this).
No, it's not bad, and I recommend you always do it on any class you'll reasonably extend over time. For example in our iOS projects we always start with a UIViewController subclass called ViewControllerBase that does nothing but extend Apple's base class (the same can be said for Activity on Android).
When we need to add something in later that should apply to every view controller (analytics perhaps), it's easy to do.
Fortunately, even if you have a lot of classes in your code it's easy to inject your custom base class with a simple search and replace across your codebase.
Do be careful though as once you have a class that's in everything, small changes can of course have broad and possibly unexpected effects. Be sure to test thoroughly!
EDIT:
Regarding subclassing everything, I'd say no. You quickly reach a point of diminishing returns on your time and utility. A common view controller base is pretty standard, as for buttons and so on probably not so much. It depends entirely on what you want to do that you think might need custom functionality. If you want to log every user action, then maybe you do want to subclass every control, but in that case it might be better to just log touch events. At the end of the day though, are you really going to parse all the data that gets generated? Probably not. So make sure you have a solid use case before you go crazy subclassing.
In my opinion there are some cases in which it makes sense to derive classes of a Framework.
At work we used derived classes for the UI-Elements to have control over their behavior.

EE service design and OO modelling [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 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).

Why do we sometimes separate behaviour from classes in Java [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 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.

Categories