문제

I have to maintain a code to add more flexibility to a final static variable in a class.

The variable is no more a global constant and may be changed.

The problem is that the class is in a common library and used in different projects.

Do you have an approach or a design pattern better than copying and pasting the class code from the common library to my specific application and refactoring it?

Example:

Commons project

Class CommonClass {

    public final static var globalSomething = somethingGlobal;

    public static method(){ //CommonClass.globalSomething is used here}
}

In my App (and other apps that reference commons) we can use the static attribute and also call the method:

---> var b = CommonClass.somethingGlobal;

---> var c = CommonClass.method() //we know that CommonClass.globalSomething is used here

Expectations:

  • Ability to change CommonClass.somethingGlobal in my app and take these changes in call CommonClass.method()
  • I can modify (add methods) in the common class but i have to keep the same initial behavior (not to break other project referencing common project)
도움이 되었습니까?

해결책

If I got you right, you want to implement this as a parameter.

Looking at your example:

var c = CommonClass.method() //we know that CommonClass.globalSomething is used here

there is already something wrong with it. You shouldn't have to know that you have to set CommonClass.somethingGlobal correctly before calling the method. This way the client has to know the implementation, violating the principle of information hiding. If the value is required, introduce it as parameter:

Class CommonClass {

    public static void method(var globalSomething){}
}

An alternative would be making both your variable and your method non-static and use a constructor:

Class CommonClass {

    public var globalSomething = somethingGlobal;

    public CommonClass(var globalSomething) {
        this.globalSomething = globalSomething;
    }

    public void method(){}
}

PS: Your example code is not java. I corrected it partially in my answer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top