I think I might answer my own question here but lets say I understand the SRP on the method level to mean that a method serves one role. If I have methods that each individually cover one specific role in my class, but a method that uses lots of those methods to accomplish one role like a save() would everything still adhere to SRP?
Here is an example:
public void saveCertificationToDB(Cert cert){
if(certificateIsNotExpired(cert){
setCertProperties(cert);
openConnectionToDB();
overwriteCertificateInDB(cert);
closeConnectionToDB();
notifyUserSaveSuccessful();
}
}
Single Responsibility Principle:
There is no specific rule , just SRP is a guideline. But if you want to think for SRP then you should keep in mind always
Single reason to change a code block like class, function etc.
But as per your given function, there are many reason to change your function code block.
Example:
if properties setting function modify for any reason then you have to be change your saveCertificationToDB()
And same way if any changes in other calling function for any other reason then also your saveCertificationToDB() need to change
so, Generally there are lot of lacks
Related
I'm kind of new to Java and have a rather simple question:
I have an interface, with a method:
public interface Interface_Updatable {
public void updateViewModel();
}
I implement this interface in several classes. Each class then of course has that method updateViewModel.
Edit: I instantiate these classes in a main function. Here I need code that calls updateViewModel for all objects that implement the interface.
Is there an easy way to do it combined? I don't want to call every method from every object instance separately and keep that updated. Keeping it updated might lead to errors in the long run.
The short form is: no, there's no simple way to "call this method on all instances of classes that implement this interface".
At least not in a way that's sane and maintainable.
So what should you do instead?
In reality you almost never want to just "call it on all instances", but you have some kind of relation between the thing that should trigger the update and the instances for which it should be triggered.
For example, the naming of the method suggests that instances of Interface_Updatable are related to the view model. So if they "care" about changes to the view model, they could register themselves as interested parties by doing something like theViewModel.registerForUpdates(this), the view model could hold on to a list of all objects that registered like this and then loop over all the instances and calls updateViewModel on each one (of course one would need to make sure that unregistration also happens, where appropriate).
This is the classical listener pattern at work.
But the high-level answer is: you almost never want to call something on "all instances", instead the instances you want to call it on have some relation to each other and you would need to make that relation explicit (via some registration mechanism like the one described above).
There is no easy way to call this method on all classes that implement this interface. The problem is that you need to somehow keep track of all the classes that implement this interface.
A possible object-oriented way to do this would be passing a list containing objects that are instances of classes that implement the Interface_Updateable interface to a function, and then calling updateViewModel on each object in that list:
public void updateViewModels(List<Interface_Updateable> instances) {
for(var instance : instances) {
instance.updateViewModel();
}
}
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.
There is a pattern which is widely used in my current project:
private Collection<Converter<T>> converters = new HashSet<>();
#Inject
private void init(#Any Instance<Converter<T>> converters) {
for (Converter<T> converter : converters) {
this.converters.add(converter);
}
}
This way I can create as many converters as I want and they are automatically injected to my bean.
My problem is now with testing: the converters collection is used in my code, but Junit doesn't call the init(..) method and I need to call it to set the mocked converters.
I could make the method protected, but I don't feel OK with it because I would be changing the visibility scope of the method.
I could also call the method using reflection, but this also doesn't feel right.
This brings me to the conclusion that this code could be improved to be more testable.
Is there anyway I change this code so the testability is improved but the references are still automatically injected?
Just go ahead and make it 'public' or 'protected'.
You are not actually gaining any protection from someone changing the collection post-instantiation this way (you've just made it a little more awkward), so you don't lose anything by exposing that method (in fact I'd argue you make your class slightly better, because than you let people chose how they want to construct, rather than forcing a use of injection/reflection).
If you did want to fully prevent post-instantiation modification, than you're going to have to go to a 'final' variable anyway, with an unmodifiable collection type and change to constructor injection, but I don't get the impression that this is what you want to do.
Thing is: if you can't "trust" the people who can write code within your "package" ... I guess having "private" on a method doesn't really help you anyway. Because if people want to mess up, and they can write code in your package, they will find ways to mess up anyway.
Meaning: if you drop the "private" on your method, yes it becomes package-visible. But you can place a javadoc on it that says: "Don't call directly; used for unit test/auto-wiring only" or something like that.
I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html
I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().
My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.
Aspect J will solve your problem.
Try to define a pointcut like this:
pointcut profilling(): execution(public * *(..)) && (
within(com.myPackage..*) ||
In this way you will catch all the call to any public method within the package com.myPackage. Add as many within clauses you need.
Then add the following code:
Object around(): profilling() {
//Do wherever you need before method call
proceed();
//Do wherever you need after method call
}
IF you want to learn something more about aspectJ follow this guide.
I'd expect BCEL to be able to do this. From the web site:
The Byte Code Engineering Library is
intended to give users a convenient
possibility to analyze, create, and
manipulate (binary) Java class files
(those ending with .class).
The "analyze" part being the important bit here. The JavaDoc isn't visible on the web site (as far as I can see) so I can't easily be sure whether or not it'll help you, but it's a reasonable starting point.
BCEL should offer this capability, but ...
... your requirements sound a lot like Aspect-Oriented Programming (AOP), so you should probably also look at AspectJ (with Eclipse tooling).
The main advantage of AspectJ is that it offers a well-designed way to express your specific conditions.