I'm working on a project that is split into several smaller Java Projects. I have this Account object that stores user credentials, etc. I want to create a function to return all characters that account has, e.g. findCharacters(); Where should I put that, inside an API or in the Account class itself?
It is better place that function inside Account class as it is related functionality to Account object.
public class Account {
//properties go here
int findCharacters() {
//method logic goes here
}
}
Since this is Java, I recommend using its Object Oriented nature and capabilities. Oracle has a decent tutorial on Java and OOP. Here are some references to get you started:
https://docs.oracle.com/javase/tutorial/java/concepts/
http://people.ucls.uchicago.edu/~bfranke/apcs_0809/downloads/BPJ_TextBook_3_0_5.pdf
Just go for the function: findCharacters() inside the Account class.
As the comments say: it depends.
From a pure OO point of view, the first place to look for would be the Account class itself.
But the important thing is: the Account should follow the SOLID principles - namely: single responsibility! Therefore one has to be careful to only have those methods inside a class that contribute to that single responsibility. In other words: you want to avoid adding all kinds of methods on a specific class - just because that method is mainly using objects of that class.
Domain Driven Design gives a hint what to do when the method "doesn't fit" into the "domain object": you turn to special service classes to wrap around that "service like" functionality.
Which model to pick/follow depends on the context of your application.
Related
I have the following class hierarchy
Promotion - abstract
- Coupon
- Sales
- Deals
(Coupons, Sales and Deals are all subclasses of Promotion).
and would like to determine the type of the object when exchanging data between the REST APIs (JSON) and the Client (Angular). Users can submit a Coupon or a Deal or a Sale. For instance when a coupon is sent from the client, I want to be able to know that this is coupon so that i can call the correct method.
To solve this problem I have declared a variable and an abstract method in Promotion.
protected String promotionType = getPromotionType();
protected abstract String getPromotionType();
In the subclasses for instance in Coupon I have something like this
protected String getPromotionType() {
return "coupon"
// OR return this.getClass().getSimpleName().toLowerCase();
}
This will automatically initialize the promotionType variable so that in the Controllers I can check if the object is Coupon or Sales or Deal. Remember that JSON send data in String formats so I must I have a way to determine the type of object coming.
In this case I will have a single controller to handle all my CRUD operations. In my controller method I will do something like::
#PostMapping public void create(#RequestBody Promotion){
// And inside here I will check the type of **promotionType**
}
Here am using Promotion as argument instead of any of the subclasses in the create() method.
My question is, is it the best way to solve this?
Or do I have to create a separate Controller for each of the subclass? I am looking for the best way to do it in the real world.
I am using Hibernate for my mappings.
My question is, is it the best way to solve this?
Answers to this question will always be opinion-based, especially, as we don't know about your entire application, not only technically but business-wise, and how the client-code consumes and displays the code.
Or do i have to create a separate Controller for each of the subclass?
No, not necessarily. If the code is and would probably stay simple - sometime you can anticipate this - it doesn't make sense to inflate the code. Having three Controllers instead of a single PromotionController will very likely increase redundant code. Otherwise, if the subclasseses are rather heterogeneous, three Controllers could be more advisable.
Another thought, you might have a (human) client that manages only the Deals and that client has special requirements leading to a bunch of customized rest interfaces only for the Deal, you'd probably like to have a separate Controller.
I am looking for the best way to do it in the real world.
There is no best way. Five developers have probably five opinions on how to solve this. And even if one is more reasonable for the time being, it may change on the next day due to or changed new business requirements.
The best way is to discuss this in the team, create a common sense and if unsure, let the lead architect decide which way to go. Imo, your approach seems quite ok. That's my 2 cents.
To illustrate the scenario, I have a class called com.test.A and the same class would be modified by different users (eg: DEV1 & DEV2) but they modify their respective classes, eg: com.test.DEV1.A , com.test.DEV2.A
If I use custom loader and load class A, is there any possibility that i can filter the reference of A to DEV1.A or DEV2.A based on some condition?
Without further knowledge of the problem I would say you are trying to solve this problem in the wrong place.
This looks more like a branching problem, that should be solved in the configuration management level, using the features that your SCM gives you. Please have a look at this article on how to handle properly different parallel developments https://thedailywtf.com/articles/Source-Control-Done-Right
The tone is quite accessible and I have used it with success in order to introduce branching to teams, I hope you enjoy it
Class A {
methodForUser1(params);
methodForUser2(params);
....
wrapperMethod(params) {
if (context.user.equals(user1))
methodForUser1(params);
else if (context.user.equals(user2))
methodForUser2(params)
....
}
}
Now every user only have to call wrapperMethod and it will in turn delegate to the right method you have for the user in context.
This is brute way of doing it. Additionally, you can load the method using reflection.
Another approach could be what #Jorge_B is suggesting in another answer (maintaining different CI pipelines)
I just try to get more into SOLID principles but get stuck by implementing new structures in my old (not SOLID) code.
I have this Room.Class
public class Room {
private String roomCode;
private String roomDescription;
// getter/setter
}
Now I need to have a translation for the roomDescription. I started to create an interface
public interface ITranslation {
String findTranslation();
}
and an implementation
public class RoomDescriptionTranslation implements ITranslation {
#Override
public String findTranslation() {
return "translated Room";
}
In the already existing code there is a service class which creates some Rooms with codes and descriptions. These Rooms are also used in the view (as jsp bean).
The new requirement is to have the translated description on the view.
So for me the question is where I should implement the logic of translation of the existing Rooms.
Should I implement it in the existing serivce class where the Rooms are created?
Or should RoomDescriptionTranslation be a field inside Room?
Or should I created a new service class where just the description gets translated?
Just need a pointer to go to the right direction.
It could be first or third option, but not the second option in my opinion. I think one important question, in general for designing any class is this:
For a property p and class C, is p a property of C?
So, in your case the question becomes: is translation a property of Room? Semantically, it sounds that it is not.
Then, you can ask the same question on Room Service class. The answer to that depends on how you defined your service class. Again, another rule that helps to decide whether a property belongs to a class, is this:
What is one singe word or phrase that describes this class?
This goes to the very idea of what a class is in OOP and also to S in SOLID. Once, you ask this question and can describe one single purpose for your class, then you can go back and ask the first question, whether certain property belongs to this class or not.
Now, if your service class is such that, "Handle all room related actions" (not saying this is right, but if this is the case) then you can add one more action to it, namely translation. But, if it is not then you may create a new service, translation.
Considering all this, I lean more towards having a new translation service as it looks
Something independent
Will be easily extendible (compared to other option) like adding more languages
Does not require changing existing code
Again, there might be other factors affecting the whole thing.
I would create a model TranslatedRoom extends Room to use only in view this L from SOLID and inside this new model would take care about translations.
Of course if it is possible to refactor service which creates model for views etc.
One more thing (maybe it is S from SOLID) this idea is good if we need to show translated room only in this/these views.
If you want to translate text you should use internationalization solutions which already exist in java.
In your solution you'll create painful maintenance problems and every string which you'll return will be surrounded by if.
I'm building an RPG with JavaFX and need to get some advice from the experts.
What is the proper way to load certain resources? I'm not talking about images and sound, that part is easy. I'm talking about classes. For instance; I have like some odd 400+ abilities that you can activate. I have a separate class for each ability (or arte as I call them). To access this ability I want to be able to call
Data.getArte(idOfArte);
and this should return an object of type Arte. All of the artes have a separte class file.
There are other resources that are this way as well like Heroes, Enemies, and such. What would be the best way to load and call these resources for use? Is there a better way of doing this?
Edit: I'm also very concerned with performance.
A more efficient approach might be to use Entity Component System or at least borrow the composition design. This allows you to have a single concrete class, say Ability, that will contain generic fields common to all abilities, e.g. skill points cost, duration of ability, target types, activation types, etc. Then you would have a component for each special value you need to add and a control for each special behavior you need to add to that generic ability. Example:
Ability ability = new Ability();
ability.addComponent(new DurationComponent(double seconds)); // specify how long effect lasts
ability.addControl(new DamagingControl(int damage, Object targetType, etc.)); // so ability can damage
ability.addControl(new ElementAugmentingControl(Element element, Object weapon/armor, etc.)); // so ability can change status effects / elements
This should give you the idea of composition. Based on the common behavior of your abilities, you should end up with about 10-30 classes, while your 400 abilities simply become configurations of the base generic ability. To give you an example here's an RPG with roughly 100 abilities (skills) which are implemented as 6 classes. The same design can also be used with any game items / characters.
As for object creation you can do:
public static final int ABILITY_ID_SOME_NAME = 1000;
ability.addComponent(new IDComponent(ABILITY_ID_SOME_NAME));
Then each of your abilities could be a part of a global data store, where only ability prototypes are stored:
Ability ability = DataStore.getByID(ABILITY_ID_SOME_NAME).clone();
Alternatively, make the data store return an already cloned ability so that you don't expose the prototypes.
Finally, you can consider using a scripting language, e.g. javascript, to change the behavior of the generic ability. In this case all of your abilities would be stored in a folder scripts/abilities/ which you load at runtime and only the ones you need. Some arbitrary example: (heal.js file)
function onUse(object, healValue) {
if (object.hasComponent(HP_COMPONENT)) {
val hp = object.getComponent(HP_COMPONENT);
hp.value += healValue;
}
}
Here's an article that shows how to call javascript functions inside java.
You are looking for the Factory Pattern. I've found a good article about it here: http://alvinalexander.com/java/java-factory-pattern-example
I assume that you do not have to sideload class files at runtime? If that were the case I'd suggest to take a look here: Method to dynamically load java class files
I have a number of GUI classes that is accessing the same information object which is set from its constructor.
Each GUI class displays the gui information object in a different way.
Is it better to initialise the object each time in the constructor or just add the object to memory and use it each time a GUI class requires it ? Does either method fall into a design pattern ?
Before even reading up on specific object design patterns, a good starting place is to read up on the MVC (Model View Controller) pattern. It's probably the most commonly used architecture pattern out there, and a google search will bring up tons of good material (Wikipedia would even be a good place to start in this case)
It's used to address the problem you've hinted at, where your various display logic has to frequently access the same information holding logic. In an application which uses an MVC architecture, your code is (more or less) separated into three categories, code which displays information in a UI, code which holds (or models) information, and code which controls the flow of the application and application events. MVC applications commonly use listeners and other event design patterns, like the ones mentioned above.
Take look at dependency injection, listeners and event bus.
I would suggest dependency injection, there are a lot of frameworks out there. My favorite is guice but YMMV.
How about using a strategy pattern?. Basically just define a set of classes that inherit from the same interface such as
public interface GUIBehavior {
}
//Set of classes
public behavior1 implementse GUIBehavior...
//In the clases that display the information simply set an attribute for the behavior
private GUIBehavior myCurrentBehavior;