2 Classes with the same name, serving different purposes - java

The question I have is so weird that I couldn't even come up with a better title at the moment. Anyhow, I am looking for a way to name 2 classes but cannot figure out what would be the best way forward. I do understand this is an opinion based question but I'm stuck with this... so I would appreciate any opinion on this
Project: A
-> Class name: Call (This class will represent the call from one telephone to another) Other classes may/may not subclass this particular class and if so the name of these subclasses would probably relate somehow to the parent class (CallState, CallEndPoint, CallSomething). This Class will not know about the existence of the database, one could say this class will be part of the general telephony driver.
Project: B
-> Class name: Call? (This will represent the actual table in a database. The table will have some information about the call like call id, time it entered the system etc, but also other information that may/may not relate to the call). This class will serve essentially as a RowMapper.
Now, these 2 projects most likely will be combined down the line, and If I name the classes the same I would then end up with 2 same name classes in a single project serving 2 different purposes. Now if I was the only person to build this application I could probably digest this, but if multiple people start work on the application it will become confusing to others, especially if more classes will follow the same pattern.

I'm not entire sure what the question here is. Do you want to know if it's possible to give 2 classes the same name, or just whether it's a bad idea?
A convention that is often used for classes that are meant to model database entities, is to postfix the classname with Entity. So you could name the first class Call and the second CallEntity. This removes some ambiguity about the classes purposes. Most professional developers will also immediately make the assumption that the Entity class is supposed to represent something that is persisted.
However if you really insist on giving both classes the same name. That's perfectly possible, if you put them in separate packages. The package you put them in can also provide more clarity about the intent of the class. The first could be domain.model.Call, while the second could be domain.entity.Call
Hope this is somewhat helpful :)

Now, these 2 projects most likely will be combined down the line, and
If I name the classes the same I would then end up with 2 same name
classes in a single project serving 2 different purposes.
When inside a same application two classes with distinct responsibilities/data need to have the same simple name (that is without the package), you should indeed consider it as something to think of and very probably fix.
Of course you could define these classes in distinct packages but does it really solve your issue ? I don't think. It will make things less clear as client code could use the bad one and at each time developers manipulate/read Call in the code they have to wonder "which Call" they are currently copping with.
Today you have two distinct Call. With such permissive naming conventions, why not a new one in the future ?
Really, not a good idea.
The source of the problem is the way which you design your application.
You split the model in two pats : the agnostic persistence part in a class and the data persistence part in another class. It is a choice (that personally I avoid) but if you make this choice you have to go until the end : distinct clearly each class with a different name. This choice has to be visible and not hidden in a package name only.
For example :
Call (domain) and CallEntity (persistence) or in the reverse way CallDTO(domain) and Call(persistence)

Related

Using non-created classes in current class

Scenario
This question may be a question about conventions, but Java might have a built-in way to do this. I'm explaining my problem with a scenario:
We are three people working on a project, and we're all doing different parts, and working on different git branches, all of which will be needed in the end project.
My part of the program runs the TUI (let's call the class Startmenu), which requires to run functions from an instance of the Database class. In my switch cases, I know the future code from the other branch will allow me to simply run db.printElements(), as an example.
Problem
Nevertheless, this is the problem: I cannot define Database db; in the class structure, nor can I assign my Startmenu() constructor to take a Database db as an input such as Startmenu(Database db), because it does not yet exist.
In practice, how do I solve this issue? Currently, I'm commenting out the parts that require parts of the other code, and replace it with poisoned code instead, as a placeholder. This doesn't seem like the best idea.
I know a solution is to create the Database class, with empty functions for those functions I will be needing right now, but this will mess with git instead.
tl; dr: How can I prepare my own files to use code that does not yet exist, which will appear "magically" by other people over time?
All components in your project should have specified an interface to exchange information across layers and other Java components during the design phase.
You can early commit and share these interfaces, so other colleagues can provide their own testing implementations or mock behaviours.

How to split a Java library source into two blocks, keeping one package?

We are creating an android library for use with Android. That means an Eclipse-like IDE and an Ant-like build process.
The nature of the library is that it has two distinct parts, representing different levels of abstraction - let's say 'upper' and 'lower'.
Assume, for the purposes of this question, that we need to call methods in one part from the other, but would like to keep those methods hidden from the library user. I've scoured the usual references but they all stop at the point of explaining package name conventions and scope rules. I've failed to find anything that answers this on SO, though this was useful.
The immediate solution is to simply have everything in one package and for those methods to be package-private. However, for reasons of maintainability, clarity, and not-having-100-files-in-one-folder we'd prefer to split the parts into different folders.
The obvious splitting point is to split the (let's say 'wibble') package into com.me.wibble.upper and com.me.wibble.lower packages/folders, but that makes any interconnecting methods undesirably public. In mitigation they could be hidden from the javadoc with #hide.
Another thought is whether could we split the parts at the top level and instead of the classic /main and /test folders have /upper, /lower and /test and all parts share the same com.me.wibble namespace. I'm unsure if/how Eclipse would cope with that.
Is there a conventional way of doing this, or is it just not done? If there are ways, what are the pro's and con's?
hmmm......Instead of asking for the solution, sometimes it is better to give the question. WHY you want library users to have a restricted view may generate a better answer than the HOWTO. There are a few answers I thought of but didn't give because I don't know the motivation behind the question (I don't want to waste your time with an answer that is not applicable).
/upper,/lower/,/test doesn't make your situation any nicer. It just makes the project more organized. Whether they are all in the same folder or separate it doesn't affect much.
It sounds like you need public 'interfaces' for library users while having private 'interfaces' for your own use. This is possible with hacking but can be painful if this is large pre-existing collection of code.

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.

Forcing to use a class from another package with the same name of a class in the current package

since you guys helped me out, I stumbled upon a strange 'issue' while programming Java.
I'm programming in the Play framework. It uses a lot of equally named classes among a number of packages. It makes your code look pretty, but I encountered a rather nasty side-effect:
I have a class 'User' in my controller package. But of course, 'User' is also a model.
While I'm writing in another controller, I need to create a new User object.
User u = User.find(...);
Because the controller User hasn't got such a method, this fails.
Am I correct if the only way to solve this is to write
models.users.User u = models.users.User.find(...);
After a little discussion with a Scala enthusiast, it seems that Java has no support to fix this kind of issues. Or is he wrong?
Kind regards
If I understand your question correct, if you do:
import models.users.User;
you will have access to the object without the full package. That's assuming you don't need the controller and the model in the same class.
If you need both, then yes, you have to fully qualify (add the package) one of them.
That said, it's a good convention to name all controllers XXXXController (or something like that). More generally, your own code should not have 2 different classes with the same name. The reason is that makes code readability lower, as User in one place behaves in a way and in some other piece of code behaves in a different way.
So the best solution would be to rename your controller.
He is right. You don't have any other way out of this.
It makes your code look pretty
I wouldn't say that. It makes my code convoluted and insanely difficult to comprehend.
You are correct. If you need to use both the User in your controller and the User class in the framework in the same class, then you can import one and then use the full package name for the other.
This can get confusing of course and I would reccomend one of two things:
1) one rename your class to something else.
2) do not import either and use the full package name for both. That way when reading the code it is less confusing.
I reccomend option 1.

how to organize interfaces and classes

I know this question has been asked and answered many times, but I am still asking the same question again...
I have started working on a travelling application and for which currently I am working on creating on the creation of the underlying DAO so I am planning to create a generic DAO, its implementation and again an interface for each entity class.
My query is what is the best way to organise all these interfaces as well as their Implementation.
Thanks in advance
If I understand the question correctly your looking for suggestions on organising your packages?
I'd split then between. com.yyy.zzzz.dao.interfaces and com.yyy.zzzz.dao.impl
You're the only one who can take decisions on how your application should be organized. You can, of course, follow some recommandations such as the Java Naming Convention for packages, or even try to split your packages for each tier implied in your application; but in the end, you have to choose for yourself.
#Kevin D's solution is correct, you could use the com.company.project.dao.interfaces (I wouldn't use interfaces as it's a plural and I avoid plural in package names, but again it depends on you) and com.company.project.dao.impl or you could use packages to split different implementations. It's as you want. And no one should tell you how to split your own application (except your team).
The only (but still facultative) rule I would tell you to follow is "Have coherent names".
That means choose your project convention, but stick to it, and of course the names you choose for your packages (but it also applies on classes, variables) must represent their content (but I suppose this is common sense).
On another note, I don't know the context of your work, but you should really read Adam bien's Weblog, you'll see some articles on best practices regarding DAO and "default implementation", maybe it will concern your project.
Resources :
DAO's aren't dead - but they either collapsed or disappeared
Service s = new ServiceImpl() - Why are you doing that ? (not really related to DAO but still your "default implementation" made me think of this)
JPA/EJB3 killed the DAO

Categories