I'm developing a library in Java which contains some functionality where some values will have to be run through some function in order to transform or map them in a way. If you want more detail, it's a robotics library where sets of motor output levels will need to be mathematically changed.
Currently, the way I've implemented this is through a Mapper interface with a run method which the map method accepts. Users use it like this:
wheelValues.map(new Mapper() {
#Override
public double run(double input) { ••• }
});
The thing is, I want to include some default implementations of the Mapper interface for user convenience, for example, an absolute value Mapper. I want to make it a property of the Mapper interface some how. What is the best way to approach this, a static inner class or static public fields?
public interface Mapper {
// This?
static final Mapper ABS = new Mapper() {...}
// Or this?
static class Abs implements Mapper {...}
}
Start by using standard library interfaces wherever possible; for example, your Mapper seems like a duplicate of DoubleFunction (or Function<Double, Double>). Absolute value is provided by Math.abs, and you can already refer to it saying Math::abs, no "default implementation" required.
Regarding the question of out-of-the-box implementations, there are two general categories:
Completely pure functions (that have no knobs or settings) are generally implemented as constants somewhere. A good example of this is String.CASE_INSENSITIVE_ORDER, which is a constant of Comparator<String> that does what its name says.
Functions that need a private copy because they have some sort of parameter are implemented as static methods that return an instance of that functional interface. A good example here is Predicate.isEqual(target), which returns a Predicate (object->boolean) instance which returns true if the value examined is equal to the target value (provided when the instance is created): private static final Predicate IS_CORRECT = Predicate.isEqual(correctAnswer).
Make the API as small a reasonably practical. So don't add a extra class where a static method or final field will suffice.
An enum would make a bad choice. As, for example, java.nio.file.StandardCopyOption.
OTOH, you can't allow varying type parameters if you use enum constants or static fields, so a method may be preferable, if only for consistency. As, for example, java.util.Collections.emptySet or java.util.stream.collectors.toSet.
In order not to create too many instances you may want a private static field behind any method.
Avoid the naming classes Default, or other poorly descriptive names. Even if it is the class returned by a default method.
Related
I am writing a rather complicated translation module which essentially translates between a form of logical representation and Java code. It spans several classes which are all decoupled from each other.
My problem is that I need to keep track of a rather extensive set of keywords which need to be inserted, for example, into variable names. These keywords must be accessible to all classes in the module, and be easy to change.
I understand that the use of globals is a red flag as far as design goes, but would it be acceptable in this case to create a class which does nothing but provide static access to said keywords? For example:
public final class KeyWords {
public static final String SELF = "self";
public static final String RESULT = "callResult";
// etc
}
My own thoughts is that it would work somewhat like a simple config class. I find this a lot more reasonable than using, for example, a mediator or passing some other bucket class between method calls, since the data is rather well defined and, importantly, not subject to modifcation during runtime.
OR, would it be better to put all these keywords into an interface instead, and let all my class inherit this? While it could work, it just does not feel right.
This isn't the worst thing ever, but it's somewhat out of date. If you're using Java 1.5 or above, an enum would be better; it gives you type safety, for instance.
public enum KeyWord {
SELF("self"),
RESULT("callResult")
;
public String getKeyword() {
return keyword;
}
private KeyWord(String keyword) {
this.keyword = keyword;
}
private final String keyword;
}
You're right that the "tuck them into an interface" approach doesn't feel right; an interface is about specifying behavior, which a methodless interface with static finals does not provide. Since Java 1.5, you can use static imports to get the same benefit without that "code pollution."
If you are going to be using the same set of keywords, across multiple classes that don't inherit from each other then I would suggest just creating a static class that reads in a text file that has all of these keywords in it.
If you use this method then you can use the "code once use everywhere" ideology that the pros always drone on about.
-Create a static class
-Read in a text file that has all your keywords saved in it
-write a couple functions that retrieve and compare keywords
-Use it in every class you want without worry of fragmentation.
Using this method also makes updating a snap because you can simply open the text file change add or delete what you want then it is fixed in every single class that implements it.
I'm looking for a way to add some methods into exists class like this:
String s = "";
s.doSomething();
In objective C, I can use category to do this.
#interface NSString( Stuff)
-(void)doSomething();
#end
Is android has something like that? Or another hack?
Update: Actually, I got this problem: I use a class (not final) from jar file (so, I can't touch its source code). Then I want to add methods( or something like that) into this class without using inheritance. For example:
public class Provider{
// many methods and fields go here...
public String getName(){}
}
All I want to do is:
provider.print(); //that call getName() method;
I also tried proxy pattern, it worked, but I don't like that way (because it like a wrapper class, I must store an object with many fields and methods to use only one method):
public class ProxyProvider{
Provider provider;
public ProxyProvider(Provider provider){
this.provider = provider;
}
public void print(){
String name = provider.getName();
//do something
}
}
Is there any way to solve that?
You could create a utility class with static methods:
public final class ProviderUtils {
private ProviderUtils() {} // not instantiable, it is a utility class
public static void print(Provider provider) {
String name = provider.getName();
// print the name
}
}
In your code, you can then call it:
Provider p = new Provider(...);
ProviderUtils.print(p);
And if that class only has one print method, you can maybe call it ProviderPrinter instead of ProviderUtils.
In the end you don't have thousands of possibilities - you can:
extend the class and whatever method you need in the sub class => you said you don't want that
modify the source code of the class and recompile your own version of the jar
wrap the class in a wrapper that adds the methods you need (your ProxyProvider example)
put the methods you need in a static utility class (what I proposed above)
modify the class at runtime and add a method, but that's a complicated path because you need to play with classloaders.
It is not possible, however, there is a java like DSL available called Xtend that can be used as a compelling replacement for JAVA that might be work looking at which supports extension methods like this.
http://www.eclipse.org/xtend/
DISCLAIMER: I am in no way associated to this I am just an avid user of the core technology that was used to create xtend called xtext. I have considered using xtend on an Android project
In Java, a class can be extended using regular inheritence unless it final. String is final, because Strings are immutable, and therefore are intentionally protected against subclassing.
Also, adding behaviour by subclassing is considered bad practice in many cases - the coupling is simply too strong and sticks with you for instances of your objects you are ever going to create. The rule of thumb is "favour composition over inheritance".
Having said this, there are many approaches / patterns to solve your special problem. Decorator might be the pattern you are looking for.
Please update your question or post a new one with more information.
Try to extend the class in question and add your methods to it. if that can't be done (like it's been said, String is final) then just write a wrapper around it with the methods you want and the object you want to extend.
Like
public class MyString
{
private String internal;
//your methods
}
try to further elaborate your problem so i can give a better answer. like whats the real object in question and what you really wanna do, if you can disclose it that is.
I have seen that if I have interface named interfaceABC.
Example:
public class ABController extends AbstractCOntroller {
private interfaceABC inter;
I am confused that why we make object from interface not from class that implemented it.
private interfaceABC inter;
i am confused that why we make object from interface not from class that implemented it
We haven't created an object/instance yet. We simply declared a variable to hold it. We don't make objects from interfaces (you have to use a concrete class to do that), but we will often use interface types instead of the actual concrete class for variable declarations, method parameter types, and method return types.
Take this for exmaple:
List<Example> examples = new ArrayList<Example>();
...
public List<Example> getExamples() { return examples; }
Using the interface List here instead of the concrete class ArrayList follows a common best practice: to use interfaces instead of concrete classes whenever possible, e.g. in variable declarations, parameters types, and method return types. The reason this is considered a best practice is:
Using the interface for declarations and for return types hides an implementation detail, making it easier to modify in the future. For example, we may find that the code works better using a LinkedList rather than ArrayList. We can easily make this change in one place now, just where the list is instantiated. This practice is especially key for method parameter types and method return types, so that external users of the class won't see this implementation detail of your class and are free to change it without affecting their code.
By using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an ArrayList. If this class relied on some ArrayList-specific property, i.e. it needs to use an ArrayList method, than using ArrayList<Example> examples = ... instead of List<Example> examples = ... may be a hint that this code relies on something specific to an ArrayList.
It may simplify testing/mocking to use the more abstract List than to use the concrete class ArrayList.
We haven't made an object, we've made a reference.
By using a reference to the interface rather than a concrete class, we are free to swap in a different implementation of the interface, with no changes to this code. This improves encapsulation, and also facilitates e.g. testing (because we can use mock objects). See also dependency injection.
This is actually very useful. Take the example that we're using a list.
public class A {
private List<String> list;
public A(List<String> list) {
this.list = list;
}
}
This allows class A to work with all operations defined by the list interface. The class constructing A can now give any implementation without changing the code of class A, hence promoting encapsulation, code reuse, testing etc. For instance:
new A(new ArrayList<String>());
For a private field, it does not really matter too much, as that's an implementation detail anyway. Many people will still on principle use the interface everywhere they can.
On the other hand, protected fields (and of course the parameters of public methods) form an API that becomes much more flexible by using interfaces, because that allows subclasses/clients to choose which implementation class they want to use, even classes they supply themselves and which didn't even exist when the API was created.
Of course, if you have a public set method or constructor that sets the private field, then you have to use the interface type for the field as well.
Imagine a gift-wrapping stall in a shop that has a machine which will wrap any box.
The machine is simply designed and built to wrap a rectangular box, it shouldn't matter whether there's chocolate in the box or a toy car. If it mattered, the machine would quite obviously be flawed.
But even before you get to that stall, you have to buy that gift: so the cashier scans the barcode first. The barcode scanner is another example of the same principle: it will scan anything as long as it has a recognisable barcode on it. A barcode scanner that only scanned newspapers would be useless.
These observations led to the concept of encapsulation in software design, which you can see in action when a class refers to an object by an interface only, and not its concrete class.
Lets say you have a class SomeClass which has its own implementation of toString(), and also has the ability to parse a new instance of itself by reading that same string.
Which of these methods do you prefer, or find better to use?
You can either define it as another constructor:
public SomeClass(String serializedString);
or you can define it as a static method, which in turn creates a new instance (by one of the other constructors, does some with it, and returns the new instance:
public static SomeClass toObject(String serializedString);
Does it even matter? (my hunch is there is no case this matters, but I am trying to make sure)
My own preference is to keep the parsing logic out of the constructor. That way it can call the appropriate constructors (possibly private) as necessary. It doesn't have to depend on default object construction and so on. So I would go with the toSomeClass() method.
Also, it is not immediately clear that SomeClass(String) will parse an object based on the serialization string. There may be many other meanings to a constructor which takes a String. The toSomeClass() static method makes this clear.
I agree with Avi's recommendation. I'd like to add two more advantages:
A static factory method allows you to return null, which a constructor can't.
A static factory method allows you to return a subclass of its defined return type, which can help provide forward compatibility.
One exception: if you're writing a simple value type and using the immutable pattern, I see no reason to use a static factory method.
The static method has the advantage that you can then use the string-reading constructor for something else. Also in general it's better to use static factories than constructors in any nontrivial classes. It gives you more flexibility.
A Java convention for such static methods is:
public class Foo {
// ...
public Foo parseFoo (String s) {...}
// ...
}
as in the standard parseInt(...), parseLong(...), parseDouble(...), etc. Unfortunately, Sun also gave us a different convention with the wrapper classes, as in Boolean.valueOf(...). However, I'd pick one of those conventions and follow it consistently.
To keep some specific logic (like parsing from string) out of constructor is good design policy.
Constructor job is mainly object creation. Initialization and creation of it's fields.
Serialization logic need to be separated from creation. Firstly you may wan't to create separate static method, secondly in evolution of your class you may want to implement some kind of Serializable interface and delegate reading/writing job to another class.
Another advantage to a static constructor is that you can give it a meaningful name. In this case, I would suggest parse:
SomeClass inst = SomeClass.parse("wibble");
I have an abstract superclass and various subclasses. Each subclass contains a value that I would like to use statically but it is not possible to create an abstract static method. I want to get a value from them dynamically without having to create instances. What do I do?
Another question would be: How would I loop through subclasses? Is it it even possible?
One attempt involved mapping class names (Subclass.class) to the value and trying to use the newInstance on them so I could use a method to get the value but this doesn't work.
Where am I going wrong in my approach?
Why not go about it the other way? Put the data someplace statically accessible and have the subclasses get it from there?
Of course, the feasibility of this depends on the nature of the data but when you find yourself hitting this sort of barrier it often helps to step back and reexamine your assumptions.
-- MarkusQ
You can reference static members/methods via reflection, but there is not automatic way to find all subclasses of a class.
Consider providing the subclasses/instance factories/metadata classes via some other mechanism, such as ServiceLoader services or some other plugin framework.
Maybe you are looking for enums?
public enum Planet
{
MERCURY (2.4397e6),
VENUS (6.0518e6),
EARTH (6.37814e6);
private final double radius;
Planet(double radius)
{
this.radius = radius;
}
public double radius()
{
return radius;
}
}
You don't have to create enum instances yourself. Enums can have values, e.g. radius() in the example. You can add behaviour to them so they can act like normal classes, by defining abstract methods on them, e.g.
public enum Planet
{
...
abstract double weightOnSurface(double weight);
...
}
You can loop through enums, like this:
for (Planet p : Planet.values())
{
System.out.println(p.radius());
}
So they seem to meet all your criteria.
Creating a second class for each of your subclasses which represents the type of that subclass might work.
For example, create a factory class for each subclass (a class that is responsible for creating instances of that subclass). There only needs to be one instance of each factory class.
Each factory class can then be responsible for knowing the subclass-specific data you describe. You then just need to loop over a fixed set of factory classes.
If you have a fixed set of subclasses then you can put the data in the superclass. If you subclasses can be added, then there is no way to list them all. You might get subclasses let the superclass know of their existence from the static initialiser (or use an agent!).
Generally superclasses should not be aware of their subclasses. However you might want to think (or better refactor) your superclass into a supertype and some other class responsible for your subclasses.
You will need to to scan package(s) and clasess to find ones that extend your superclass - unfortunately, this cannot be done with the Reflection API, but must be done through URLs (file system classes, jar files etc). Annotation use is probably better in this case, and lots of open source products use this method (Hibernate etc).
Then you can have a static method in each (either consistent naming or annotated) which you should be able to invoke with as method.invoke(MyObject.class, arguments)
The other option is to put a registry map in the abstract class - if you need to mandate it, the abstract constructor takes the static value (or just stores the subclass if calculations are needed). If you're controlling all subclasses, just make sure you have a static block in each one to add it to the registry.
Mapping subclasses... you can do it via reflection (but it won't be fun).
newInstance() (likely) won't work unless:
the class is public
the constructor is public
the constructor takes no arguments
The last one is mandatory, the other two depend on what package you are doing things from (I think, been a while since I cared). Using the Constructor class is better.
Can you give a short code example of what it is you are thinking of doing? Based on that I (and others) might be able to give you better answers. If you do need to do the mapping subclass thing I can dig up some code that does it...