Kikou
Kikou

Reputation: 1973

better modeling design java

I have to supply a class by another with regulatory management.

I suppose these two classes:

Class A:

public class A {
    private String attributeA1;
    ...
    private String attributeA50; 
    ...
    // getters and setters 
} 

Class B:

public class B {
    private String attributeB1;
    ...
    private String attributeB50; 
    ...
    // getters and setters 
} 

Each attribute from Class A will supply attribute from B.

Exemple:

public Class Supplying {
    public B elementB;
    public A elementA;

    public void supplyAttributeB1( String toto){
        String tata =  elementA.getattributeA1(); 
        // Example of regulatory management "Substring"
        elementB.setAttributeB1(tata.substring(5));
    }

    public void supplyAttributeB2(String toto){
        ...
    }

    ...
    public void supplyAttributeB50(String toto){
        ...
    }
}

When I see my code, it's not very pretty, I think I have a modeling problem because the class supplying will have over 150 lines of code.

Is there another way to make this concept by using interface or inheritance or a design pattern? I'm trying to learn how to code better.

Upvotes: 1

Views: 111

Answers (1)

biziclop
biziclop

Reputation: 49744

If your operations fall into some broad categories, you can use the Strategy pattern:

public interface DataConverter<F,T> {
    public T convert( F from );
}

public class SubstringConverter implements DataConverter<String,String> {

    private final int start;

    public SubstringConverter( int start ) { this.start = start; }

    public String convert( String from ) {
        return from.substring( start );
    }

}

And in your supplying class

public class Supplying {
     private static final DataConverter<String,String> b1Converter = new SubstringConverter( 5 );
     // and so on ...


     public void supplyAttributeB1() {
         elementB.setAttributeB1( b1Converter.convert( elementA.getAttributeA1() ) );
     }

}

This will make it easy to change the logic (so long as field Ax always converts into field Bx, all you need is plug in a new converter), and easy to see what's going on.

This is about as far as you can go without building a full-size data conversion framework, where you'll probably use reflection to access the fields and have external config files to drive the mapping between entities.

Upvotes: 1

Related Questions