In OOP reading from text file should be a Independent class method? - oop

I have a class that only have main which read in some txt and do the algorithms.
my class is look like:
class doThejob{
public static void main(String args[]){
//*****start part A******
//do the reading from text file, and tokenize it
// process into the form I need,
//about 10-30 lines of codes
//******End of part A*****
//then run the algorithms
algorithm alg=new aglorithm();
Object output = alg.x(input);
//****Part B**** output to txt, about 10~40 lines
}
}
class algorithm{
private void a(Object x){
//do something
return (Object)result;
}
}
Can anyone tell me should I extract those part A and part B to a new class ,and then setup them as a public method .like below
class Io{
public Object readFromTxt(String path){
}
public void outputToTxt(String path){
}
}
And if I setup them , and then use it like below, is that more OOP?
class doThejob{
public static void main(String args[]){
Io dataProcess= new Io();
Object input = dataProcess.readFromTxt(args[0]);
algorithm alg=new aglorithm();
Object output =alg.x(input);
dataProcess.readFromTxt(args[1],output);
}
}
class algorithm{
private Object a(Object x){
//do something
}
}

Do it the way you fill is more readable.
Separating this in another class is according to the Single Responsability Principle. It will help making the code more readable and easy to change later on.
If you want to expand more on this, you could create an interface (eg.: IIO) for input and output. This way you can implement this interface in the IO class, renaming it to FileIO. Anytime you want to create another form of IO, like database access, you just have to create a DatabaseIO class that implements this interface and change the instance in the main method for this new type:
public interface IIO
{
string Read();
void Write(string text);
}
public class FileIO : IIO
{
string path;
public FileIO(string filePath)
{
path = filePath;
}
public string Read()
{
// read from file and return contents
}
public void Write(string text)
{
// write to file
}
}
public class SqlServerIO : IIO
{
SqlConnection conn;
public SqlServerIO(string connectionStringName)
{
// create the connection
}
public string Read()
{
// read from database
}
public void Write(string text)
{
// write to database
}
}
Extracting interfaces makes the code more maintenable by alowing to switch implementations anytime without messing with working code. It also facilitates unit testing.

Related

How to see arguments when creating a new class?

When creating a new class or method I used to be able to see the parameters needed. But, now they don't come up anymore. How do I view parameters when creating a class?
Running the latest windows version.
public class Main {
public static void main(String args[]) {
Case theCase = new Case("Default", "Corsair", "500W");
}
}
public class Case {
private String model;
private String manufacturer;
private String powerSupply;
public Case(String model, String manufacturer, String powerSupply,) {
this.model = model;
this.manufacturer = manufacturer;
this.powerSupply = powerSupply;
}
public void pressPowerButton() {
System.out.println("Power button pressed");
}
public String getModel() {
return model;
}
public String getManufacturer() {
return manufacturer;
}
public String getPowerSupply() {
return powerSupply;
}
}
When making theCase I can't see what my parameters are and have to move to the "Case" class back and forth
You can explicitly call Parameter Info action which is usually mapped to Ctrl/(Cmd) - p.
Nevermind in order to see the parameters as you type you must type them while in the editor without moving your cursor.

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());
}
}

Can AspectJ replace "new X" with "new SubclassOfX" in third-party library code?

I am looking at AspectJ to see if perhaps we can use it in our test suite.
We have a rather large third party Java communications library hardwired to use its own classes (which do not implement any interfaces) which in turn mean that we need a physical backend present and correctly configured to be able to run tests.
I am looking at our options for removing this restriction. A possibility would be to create a subclass of the troublesome classes and then ask AspectJ to simply replace "new X" with "new OurSubclassOfX" when loading the third party library, but I am new to AspectJ and from my brief skimming of the documentation this is not a typical use case.
Can AspectJ do this? What would the configuration snippet be?
Yes, this is possible. Let us assume you have a hard-wired class, possibly fetching something from a database, and want to mock it via an aspect:
package de.scrum_master.aop.app;
public class HardWired {
private int id;
private String name;
public HardWired(int id, String name) {
this.id = id;
this.name = name;
}
public void doSomething() {
System.out.println("Fetching values from database");
}
public int getSomething() {
return 11;
}
#Override
public String toString() {
return "HardWired [id=" + id + ", name=" + name + "]";
}
}
Then there is a little driver application using that very class (not an interface):
package de.scrum_master.aop.app;
public class Application {
public static void main(String[] args) {
HardWired hw = new HardWired(999, "My object");
System.out.println(hw);
hw.doSomething();
System.out.println(hw.getSomething());
}
}
The output is as follows:
HardWired [id=999, name=My object]
Fetching values from database
11
Now you define your derived mock class which should replace the original for testing purposes:
package de.scrum_master.aop.mock;
import de.scrum_master.aop.app.HardWired;
public class HardWiredMock extends HardWired {
public HardWiredMock(int id, String name) {
super(id, name);
}
#Override
public void doSomething() {
System.out.println("Mocking database values");
}
#Override
public int getSomething() {
return 22;
}
#Override
public String toString() {
return "Mocked: " + super.toString();
}
}
And finally you define an aspect with a simple pointcut and advice to replace the original value during each constructor call:
package de.scrum_master.aop.aspect;
import de.scrum_master.aop.app.HardWired;
import de.scrum_master.aop.mock.HardWiredMock;
public aspect MockInjector {
HardWired around(int p1, String p2) : call(HardWired.new(int, String)) && args(p1, p2) {
return new HardWiredMock(p1, p2);
}
}
The output changes as desired:
Mocked: HardWired [id=999, name=My object]
Mocking database values
22
You do that once per class and constructor and are fine. In order to generalise the approach you would need joinpoint properties and, depending on how far you want to go, maybe reflection, but this here is pretty straightforward. Enjoy!

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.

How to design around lack of multiple inheritance?

Using interfaces won't work because I want a single implementation. Using this solution would end in a lot of redundant code because I plan on having quite a few sub classes (composition vs inheritance). I've decided that a problem-specific design solution is what I'm looking for, and I can't think of anything elegant.
Basically I want classes to have separate properties, and for those properties to be attached at design time to any sub class I choose. Say, I have class 'ninja'. I would like to be able to make arbitrary sub classes such as 'grayNinja' where a gray ninja will always have a sword and throwing stars. Then possibly 'redNinja' who will always have a sword and a cape. Obviously swords, stars, and capes will each have their own implementation - and this is where I can't use interfaces. The closest solution I could find was the decorator pattern, but I don't want that functionality at runtime. Is the best solution an offshoot of that? Where inside the Black Ninja class constructor, I pass it through the constructors of sword and throwingStar? (those being abstract classes)
haven't coded in a while and reading hasn't gotten me too far - forgive me if the answer is simple.
Edit: Answered my own question. I can't mark it as 'answer' until tomorrow. Please let me know if there's a problem with it that I didn't catch. All the reading this problem forced me to do has been awesome. Learned quite a bit.
You want classes to have separate properties. Have you considered coding exactly that?
For example, you want a RedNinja that is-a Ninja that has-a sword and cape. Okay, so define Ninja to have an inventory, make it accessible through Ninja, and pass in an inventory through RedNinja's constructor. You can do the same thing for behaviors.
I've done once a similar app. with a earlier "C++" compiler that supported only single inheritance and no interfaces, at all.
// base class for all ninjas
public class Ninja {
// default constructor
public Ninja() { ... }
// default destructor
public ~Ninja() { ... }
} // class
public class StarNinja: public Ninja {
// default constructor
public StarNinja() { ... }
// default destructor
public ~StarNinja() { ... }
public void throwStars() { ... }
} // class
public class KatannaNinja: public Ninja {
// default constructor
public KatannaNinja() { ... }
// default destructor
public ~KatannaNinja() { ... }
public void useKatanna() { ... }
} // class
public class InvisibleNinja: public Ninja {
// default constructor
public InvisibleNinja() { ... }
// default destructor
public ~InvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class FlyNinja: public Ninja {
// default constructor
public FlyNinja() { ... }
// default destructor
public ~FlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class InvincibleNinja: public Ninja {
// default constructor
public InvincibleNinja() { ... }
// default destructor
public ~InvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class SuperNinja: public Ninja {
StarNinja* LeftArm;
InvincibleNinja* RightArm;
FlyNinja* LeftLeg;
KatannaNinja* RightLeg;
InvisibleNinja* Body;
// default constructor
public SuperNinja() {
// -> there is no rule to call composed classes,
LeftArm = new StarNinja();
RightArm = new InvincibleNinja();
LeftLeg = new FlyNinja();
RightLeg = new KatannaNinja();
Body = new InvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
Im afraid, that the most close example is the composition design pattern. In order, to become more similar to inheritance, I make a generic base class that all composite classes share, and I make a main class that will be the result of the multiple inheritance, that has a copy of all the public methods of the component classes.
If you want to use interfaces, to enforce that main class have all important methods,
then make an interface that matches each composing class, and implemented in the main class.
public interface INinja {
public void NinjaScream() { ... }
} // class
public interface IStarNinja {
void throwStars();
} // class
public interface IKatannaNinja {
void useKatanna();
} // class
public interface IInvisibleNinja {
void becomeVisible();
void becomeInvisible();
} // class
public interface CFlyNinja {
void fly();
void land();
} // class
public interface IInvincibleNinja {
void turnToStone() { ... }
void turnToHuman() { ... }
} // class
// base class for all ninjas
public class CNinja: public INinja {
// default constructor
public CNinja() { ... }
// default destructor
public ~CNinja() { ... }
public void NinjaScream() { ... }
} // class
public class CStarNinja: public CNinja, INinja {
// default constructor
public CStarNinja() { ... }
// default destructor
public ~CStarNinja() { ... }
public void NinjaScream() { ... }
public void throwStars() { ... }
} // class
public class CKatannaNinja: public CNinja, IKatannaNinja {
// default constructor
public CKatannaNinja() { ... }
// default destructor
public ~CKatannaNinja() { ... }
public void NinjaScream() { ... }
public void useKatanna() { ... }
} // class
public class CInvisibleNinja: public CNinja, IInvisibleNinja {
// default constructor
public CInvisibleNinja() { ... }
// default destructor
public ~CInvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class CFlyNinja: public CNinja, IFlyNinja {
// default constructor
public CFlyNinja() { ... }
// default destructor
public ~CFlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class CInvincibleNinja: public CNinja, IInvincibleNinja {
// default constructor
public CInvincibleNinja() { ... }
// default destructor
public ~CInvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class CSuperNinja: public CNinja,
IKatannaNinja,
IInvisibleNinja,
IFlyNinja,
IInvincibleNinja
{
CStarNinja* LeftArm;
CInvincibleNinja* RightArm;
CFlyNinja* LeftLeg;
CKatannaNinja* RightLeg;
CInvisibleNinja* Body;
// default constructor
public CSuperNinja() {
// -> there is no rule to call composed classes
LeftArm = new CStarNinja();
RightArm = new CInvincibleNinja();
LeftLeg = new CFlyNinja();
RightLeg = new CKatannaNinja();
Body = new CInvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
I know this solution is complex, but, seems that there is not another way.
Cheers.
Alright so mix-ins through extension methods are going to be my preferred route. I couldn't figure out how to use dynamic proxies in vb.net (seemed to require libraries with lots of documentation that didn't cover specifically what I needed). Dynamic proxies also seems to be a bit dirtier of a solution than using extension methods. Composition would have been what I defaulted to if the previous two didn't work.
So one problem with extension methods, is that the code gets a little dirtier if you want to hold variables. Not much though. Another problem is that all the extension methods must be defined in modules, so the code might look a little goofy to a new eye. I will solve this by defining my interface and module with the corresponding extension method in the same file.
finally, here's some sample vb.net code if you don't want to see a full fledged example through the link.
Imports System.Runtime.CompilerServices 'for extension methods
Public Interface ISword
End Interface
Public Interface IThrowingStar
End Interface
Module ExtensionMethods
<Extension()>
Public Sub swingSword(ByVal hasASword As ISword)
Console.WriteLine("Sword has been swung")
End Sub
<Extension()>
Public Sub throwStar(ByVal hasAStar As IThrowingStar)
Console.WriteLine("Star has been thrown")
End Sub
End Module
Public Class RedNinja
Inherits Ninja
Implements IThrowingStar, ISword
Public Sub New()
End Sub
End Class
Public MustInherit Class Ninja
private curHealth as Integer
Public Sub New()
curHealth = 100
End Sub
Public Function getHP() As Integer
Return curHealth
End Function
End Class
Module Module1
Sub main()
Console.WriteLine("Type any character to continue.")
Console.ReadKey()
Dim a As New RedNinja
a.swingSword() 'prints "Sword has been swung"
a.throwStar() 'prints "Star has been thrown"
Console.WriteLine("End of program - Type any key to exit")
Console.ReadKey()
End Sub
End Module
Dirty solution, if you simply must have multiple inheritance, is using something like dynamic proxies in Java.
But I guess you're probably programming in C#, and this is language agnostic question, so here goes language agnostic answer: check out composite and factory design patterns, that should give you some ideas.
Also, it might not be needed to pass everything in constructor. Check out IoC pattern as well.