Skip to content

Extract interface 2

Introduction

The module implements a light version of extract interface refactoring described in extract_interface.py

Pre and post-conditions

Pre-conditions:

  1. The interface should not be already exist.

  2. precondition is whether the package name, all the class names and method names in those classes exist.

  3. The parameter types and return types of each method should be the same across the classes.

Post-conditions:

No specific post-condition

main(class_path)

Parameters:

Name Type Description Default
class_path str

The java file path containing the public class

required
Source code in codart\refactorings\extract_interface2.py
def main(class_path):
    """

    Args:

        class_path (str): The java file path containing the public class

    """

    # Precondition 1: The interface should not be already exist.
    interface_path = os.path.join(
        os.path.dirname(class_path),
        f'I{os.path.splitext(os.path.basename(class_path))[0]}.java'
    )
    if os.path.exists(interface_path):
        return False

    stream = FileStream(class_path, encoding='utf-8', errors='ignore')
    lexer = JavaLexer(stream)
    tokens = CommonTokenStream(lexer)
    parser = JavaParserLabeled(tokens)
    tree = parser.compilationUnit()

    listener = InterfaceInfoListener()

    walker = ParseTreeWalker()
    walker.walk(listener=listener, t=tree)

    interface_info_ = listener.get_interface_info()
    interface_info_['name'] = 'I' + interface_info_['name']
    interface_info_['path'] = os.path.dirname(class_path)

    ic = InterfaceCreator(interface_info_, class_path)
    ic.add_implement_statement_to_class()
    ic.save()
    return True