Search code examples
javadesign-patternsjava-8interfaceapi-design

How do I use interfaces with "fallback" parameters in the methods?


I am writing some code in java, and am struggling with deciding if this is Ok code since I've never had any real education. I want to force use save(ConfigurationSection) in my classes, but if not available allow for using save(String). I realize I could just do this conversion before I'd call this method. Is that what I am supposed to be doing?

public interface Serializable {

    default void save(String path){
        save(Claims.getDataManager().getData().createSection(path));
    }
    void save(ConfigurationSection section);

}

I'd like to know if I am allowed to do this. Also any good resources that are relatively comprehendable for someone without any real knowledge of jargon.


Solution

  • I want to force use save(ConfigurationSection) in my classes

    It's difficult to force the user to use one overloaded method over another. If I have two options, I choose the simplest one and let the API do all the dirty work for me. I will not be constructing a ConfigurationSection on my own if there is an enticing String option unless the former offers me a more flexible/fine-grained/performant way.

    You may document these methods well, though. Stating clearly which method is preferable, and why.

    if not available allow for using save(String)

    I didn't get it. There is either one method or two methods. If the user can't build a ConfigurationSection, it doesn't mean save(ConfigurationSection) magically disappears, and save(String) appears. Your interface is still these two methods.

    I'd like to know if I am allowed to do this.

    Yes, you are. Your code looks absolutely fine to me.

    Claims.getDataManager().getData().createSection(path)
    

    is OK as a default way to turn a String into a ConfigurationSection as long as it doesn't bring any side-effects, and is transparent to the caller. It's like a shortcut that the user is (or can get) familiar with.

    I like your question, by the way. It looks simple and humble.