Naming public static final in lowercase? - naming-conventions

I have a hierarchy of classes:
class Page {
}
class ChildPage1 extends Page {
private static final String URL;
}
class ChildPage2 extends Page {
private final String url;
}
Some pages have static urls but other don't. I need some methods like load() in parent class Page that will use url of it's descendant. I thought about implementing it in these ways:
using reflection api
naming static final URLs in lowercase (in conroversary to naming conventions).
Is it worth to not follow naming conventions in this case?

You can solve your problem by adding an abstract method getUrl() to Page that has to be implemented in ChildPage1 and ChildPage2.
class Page {
protected abstract String getUrl();
}
class ChildPage1 extends Page {
private static final String URL;
protected String getUrl() {
return URL;
}
}
class ChildPage2 extends Page {
private final String url;
protected String getUrl() {
return url;
}
}

Related

Immutables wrapper as string in Jackson

How can I jackson serialize a wrapper type to and from a string?
I merged the following from two different examples their website. But the HostName type is serialized/deserialized as
{ "name" : "my.host.name.com" }
when I want it to be simply the string
"my.host.name.com"
Note that I have a lot of XName types, hence the use of the Immutables wrapper. So I would prefer a solution that keeps the amount of boiler plate down.
#Value.Immutable #AbstractName.Wrapper
public abstract class _HostName extends AbstractName { }
...
public abstract class AbstractName {
#JsonSerialize
#JsonDeserialize
#Value.Style(
// Detect names starting with underscore
typeAbstract = "_*",
// Generate without any suffix, just raw detected name
typeImmutable = "*",
// Make generated public, leave underscored as package private
visibility = Value.Style.ImplementationVisibility.PUBLIC,
// Seems unnecessary to have builder or superfluous copy method
defaults = #Value.Immutable(builder = false, copy = false))
public #interface Wrapper {}
#Value.Parameter
public abstract String name();
#Override
public String toString() { return name(); }
}
I've got this to work like below. There's an extra annotation on my name types. It's not my favorite, but it works.
#JsonDeserialize(as=HostName.class)
#Value.Immutable #AbstractName.Wrapper
public abstract class _HostName extends AbstractName { }
...
public abstract class AbstractName {
#Value.Style(
// Detect names starting with underscore
typeAbstract = "_*",
// Generate without any suffix, just raw detected name
typeImmutable = "*",
// Make generated public, leave underscored as package private
visibility = Value.Style.ImplementationVisibility.PUBLIC,
// Seems unnecessary to have builder or superfluous copy method
defaults = #Value.Immutable(builder = false, copy = false))
public #interface Wrapper {}
#JsonValue
#Value.Parameter
public abstract String name();
#Override
public String toString() { return name(); }
}
Here's a little program to run it:
public static void main(String... args) throws IOException {
ObjectMapper json = new ObjectMapper();
String text = json.writeValueAsString(HostName.of("my.host.name.com"));
System.out.println(text);
HostName hostName = json.readValue(text, HostName.class);
System.out.println(hostName);
}

Test method of Singleton object using Powermock

I would like to test a public method1 as well as mock the private method createJSON of Singleton class.
public class SingletonClass {
private static SingletonClass singletonInstance = new SingletonClass();
private SingletonClass() {
}
public static SingletonClass getInstance() {
return singletonInstance;
}
public JSONObject method1(int id, String str)
throws JSONException {
JSONObject loginJSON = createJSON(id, str);
return loginJSON;
}
private JSONObject createJSON(int id, String str){
return new JSONObject().put("id", id).put("str", str);
}
}
Could anyone help on this?
It sounds like you need a partial mock. A partial mock will allow you to mock a subset of the methods of the class you are working with, but not others.
This SO post explains how to use partial mocks.

Which design pattern should I use to output different content using one template?

I need to extend a piece of code that writes a paragraph using constant strings defined in an interface:
public class paragraphGenerator implements EnglishParaGraph(){
public StringBuffer outputParagraph = new StringBuffer();
public void generate(){
writeParagraph(PARA1);
//some long and complicated logic here
writeParagraph(PARA2);
//some long and complicated logic here
writeParagraph(PARA3);
}
public void writeParagraph(String content){
//manipulates the paragraph and puts it in stringbuffer
}
}
public interface EnglishParaGraph{
public static final String PARA1 = "Hello";
public static final String PARA2 = "Thank you";
public static final String PARA3 = "Goodbye";
}
Running generate() should write something like "Hello Thank you Goodbye".
Now I want to generate a French equivalent so the output looks something like "Bonjour Merci Salut".
According to Template Method Pattern can overwrite generate() in a subclass and change each writeParagraph's input argument, but that will repeat most of the code which is not desirable.
What's the most suitable design pattern to use here? I was told to use as little replicating code as possible.
The design of the interface and extending class is simply wrong. To be clear, interfaces are specifically used to avoid defining implementation details. The code you posted does the exact opposite of that and defines implementation details using an interface.
At worst, you want to make the interface define something like this:
public interface ParagraphSource{
public String getParagraph1Text();
public String getParagraph2Text();
public String getParagraph3Text();
}
public class EnglishSource extends ParagraphSource {
public String getParagraph1Text() {
return "Hello";
}
public String getParagraph2Text() {
return "Thank you";
}
public String getParagraph3Text() {
return "Goodbye";
}
}
public class FrenchSource extends ParagraphSource {
public String getParagraph1Text() {
return "Bonjour";
}
public String getParagraph2Text() {
return "Merci";
}
public String getParagraph3Text() {
return "Au revoir";
}
}
Then your paragraph generator can use different sources:
public class ParagraphGenerator {
public StringBuffer outputParagraph = new StringBuffer();
public void generate(ParagraphSource source){
writeParagraph(source.getParagraph1Text());
//some long and complicated logic here
writeParagraph(source.getParagraph2Text());
//some long and complicated logic here
writeParagraph(source.getParagraph3Text());
}
}

Design pattern to save/load an object in various format

I have an object: X, that can be saved or loaded in various formats: TXT, PDF, HTML, etc..
What is the best way to manage this situation? Add a pair of method to X for each format, create a new Class for each format, or exists (as I trust) a better solution?
I'd choose the strategy pattern. For example:
interface XStartegy {
X load();
void save(X x);
}
class TxtStrategy implements XStartegy {
//...implementation...
}
class PdfStrategy implements XStartegy {
//...implementation...
}
class HtmlStrategy implements XStartegy {
//...implementation...
}
class XContext {
private XStartegy strategy;
public XContext(XStartegy strategy) {
this.strategy = strategy;
}
public X load() {
return strategy.load();
}
public void save(X x) {
strategy.save(x);
}
}
I agree with #DarthVader , though in Java you'd better write
public class XDocument implements IDocument { ...
You could also use an abstract class, if much behavior is common to the documents, and in the common methods of base class call an abstract save(), which is only implemented in the subclasses.
I would go with Factory pattern. It looks like you can use inheritance/polymorphism with generics. You can even do dependency injection if you go with the similar design as follows.
public interface IDocument
{
void Save();
}
public class Document : IDocument
{
}
public class PdfDocument: IDocument
{
public void Save(){//...}
}
public class TxtDocument: IDocument
{
public void Save(){//...}
}
public class HtmlDocument : IDocument
{
public void Save(){//...}
}
then in another class you can do this:
public void SaveDocument(T document) where T : IDocument
{
document.save();
}
It depends on your objects, but it is possible, that visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) can be used here.
There are different visitors (PDFVisitor, HHTMLVisitor etc) that knows how to serialize parts of your objects that they visit.
I would instead suggest the Strategy pattern. You're always saving and restoring, the only difference is how you do it (your strategy). So you have save() and restore() methods that defer to various FormatStrategy objects you can plug and play with at run time.

Avoiding Service Locator with AutoFac 2

I'm building an application which uses AutoFac 2 for DI. I've been reading that using a static IoCHelper (Service Locator) should be avoided.
IoCHelper.cs
public static class IoCHelper
{
private static AutofacDependencyResolver _resolver;
public static void InitializeWith(AutofacDependencyResolver resolver)
{
_resolver = resolver;
}
public static T Resolve<T>()
{
return _resolver.Resolve<T>();
}
}
From answers to a previous question, I found a way to help reduce the need for using my IoCHelper in my UnitOfWork through the use of Auto-generated Factories. Continuing down this path, I'm curious if I can completely eliminate my IoCHelper.
Here is the scenario:
I have a static Settings class that serves as a wrapper around my configuration implementation. Since the Settings class is a dependency to a majority of my other classes, the wrapper keeps me from having to inject the settings class all over my application.
Settings.cs
public static class Settings
{
public static IAppSettings AppSettings
{
get
{
return IoCHelper.Resolve<IAppSettings>();
}
}
}
public interface IAppSettings
{
string Setting1 { get; }
string Setting2 { get; }
}
public class AppSettings : IAppSettings
{
public string Setting1
{
get
{
return GetSettings().AppSettings["setting1"];
}
}
public string Setting2
{
get
{
return GetSettings().AppSettings["setting2"];
}
}
protected static IConfigurationSettings GetSettings()
{
return IoCHelper.Resolve<IConfigurationSettings>();
}
}
Is there a way to handle this without using a service locator and without having to resort to injecting AppSettings into each and every class? Listed below are the 3 areas in which I keep leaning on ServiceLocator instead of constructor injection:
AppSettings
Logging
Caching
I would rather inject IAppSettings into every class that needs it just to keep them clean from the hidden dependency on Settings. Question is, do you really need to sprinkle that dependency into each and every class?
If you really want to go with a static Settings class I would at least try to make it test-friendly/fakeable. Consider this:
public static class Settings
{
public static Func<IAppSettings> AppSettings { get; set; }
}
And where you build your container:
var builder = new ContainerBuilder();
...
var container = builder.Build();
Settings.AppSettings = () => container.Resolve<IAppSettings>();
This would allow to swap out with fakes during test:
Settings.AppSettings = () => new Mock<IAppSettings>().Object;
Now the AppSettings class (which I assume there is only one of) you could do with regular constructor injection. I assume also that you really want to do a resolve on each call to your settings properties, thus injecting a factory delegate that retrieves an instance when needed. If this is not needed you should of course inject the IConfigurationSettings service directly.
public class AppSettings : IAppSettings
{
private readonly Func<IConfigurationSettings> _configurationSettings;
public AppSettings(Func<IConfigurationSettings> configurationSettings)
{
_configurationSettings = configurationSettings;
}
public string Setting1
{
get
{
return _configurationSettings().AppSettings["setting1"];
}
}
public string Setting2
{
get
{
return _configurationSettings().AppSettings["setting2"];
}
}
}