Skip to content

Commit

Permalink
add Visibility Metrics by Herbert Dowalil
Browse files Browse the repository at this point in the history
These metrics are defined by Herbert Dowalil in his book "Modulare Softwarearchitektur: Nachhaltiger Entwurf durch Microservices, Modulithen und SOA 2.0" and measure the relationship of visible/public classes to hidden/non-public classes within components (and thus provide a measure for the degree of information hiding).

Signed-off-by: Peter Gafert <[email protected]>
  • Loading branch information
codecholeric committed Apr 13, 2021
1 parent e8ac8df commit c8ec061
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
import com.google.common.collect.FluentIterable;
import com.tngtech.archunit.PublicAPI;
import com.tngtech.archunit.base.Function;
import com.tngtech.archunit.base.Predicate;
import com.tngtech.archunit.core.domain.JavaClass;

import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
import static com.tngtech.archunit.base.Guava.toGuava;
import static com.tngtech.archunit.core.domain.Dependency.Functions.GET_TARGET_CLASS;
import static com.tngtech.archunit.core.domain.JavaModifier.PUBLIC;
import static com.tngtech.archunit.core.domain.properties.HasModifiers.Predicates.modifier;

@PublicAPI(usage = ACCESS)
public final class ArchitectureMetrics {
Expand Down Expand Up @@ -67,6 +70,30 @@ public static ComponentDependencyMetrics componentDependencyMetrics(MetricsCompo
return new ComponentDependencyMetrics(components, GET_JAVA_CLASS_DEPENDENCIES);
}

/**
* Calculates system component visibility metrics as defined by Herbert Dowalil.
* This method is a specific version of {@link #visibilityMetrics(MetricsComponents, Predicate)} where the
* elements can only be of type {@link JavaClass} and a class is considered visible, if and only if it is public.
*
* @param components The components to calculate the metrics for
* @return The calculated {@link VisibilityMetrics}
*/
@PublicAPI(usage = ACCESS)
public static VisibilityMetrics visibilityMetrics(MetricsComponents<JavaClass> components) {
return visibilityMetrics(components, modifier(PUBLIC));
}

/**
* Calculates system component visibility metrics as defined by Herbert Dowalil.
*
* @param components The components to calculate the metrics for
* @return The calculated {@link VisibilityMetrics}
*/
@PublicAPI(usage = ACCESS)
public static <T> VisibilityMetrics visibilityMetrics(MetricsComponents<T> components, Predicate<? super T> isVisible) {
return new VisibilityMetrics(components, isVisible);
}

private static final Function<JavaClass, Collection<JavaClass>> GET_JAVA_CLASS_DEPENDENCIES = new Function<JavaClass, Collection<JavaClass>>() {
@Override
public Collection<JavaClass> apply(JavaClass javaClass) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Copyright 2014-2021 TNG Technology Consulting GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tngtech.archunit.library.metrics;

import java.util.Collection;

import com.google.common.collect.ImmutableMap;
import com.tngtech.archunit.PublicAPI;
import com.tngtech.archunit.base.Predicate;

import static com.google.common.base.Preconditions.checkArgument;
import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;

/**
* Calculates visibility metrics as defined by Herbert Dowalil in his book
* "Modulare Softwarearchitektur: Nachhaltiger Entwurf durch Microservices, Modulithen und SOA 2.0".
* <br>
* Visibility refers to the property, if an element of a component is accessible from outside of the component.
* An example would be a package, where public classes are visible from outside of the package, while package-private,
* protected and private classes are not. The metrics are calculated by introducing the following definitions:
* <ul>
* <li>Relative Visibility (<b>RV</b>): {@code num(visible_elements) / num(all_elements)} for each component</li>
* <li>Average Relative Visibility (<b>ARV</b>): The average of all {@code RV} values</li>
* <li>Global Relative Visibility (<b>GRV</b>): {@code num(visible_elements) / num(all_elements)} over all components</li>
* </ul>
* <br>
* Consider the following example:
* <pre><code>
* Component1 (Visible: 2 / Invisible: 4)
* Component2 (Visible: 3 / Invisible: 3)
* Component3 (Visible 1 / Invisible: 9)
* </code></pre>
* Then<br>
* {@code RV(Component1) = 2 / 6 = 0.33}<br>
* {@code RV(Component2) = 3 / 6 = 0.5}<br>
* {@code RV(Component3) = 1 / 10 = 0.1}<br>
* {@code ARV = (0.33 + 0.5 + 0.1) / 3 = 0.31}<br>
* {@code GRV = 6 / 22 = 0.27}.
*/
@PublicAPI(usage = ACCESS)
public final class VisibilityMetrics {
private final ImmutableMap<String, ComponentVisibility> relativeVisibilityByComponentIdentifier;
private final double averageRelativeVisibility;
private final double globalRelativeVisibility;

<T> VisibilityMetrics(MetricsComponents<T> components, Predicate<? super T> isVisible) {
ImmutableMap.Builder<String, ComponentVisibility> relativeVisibilityByComponentIdentifierBuilder = ImmutableMap.builder();
for (MetricsComponent<T> component : components) {
relativeVisibilityByComponentIdentifierBuilder.put(component.getIdentifier(), new ComponentVisibility(component, isVisible));
}
relativeVisibilityByComponentIdentifier = relativeVisibilityByComponentIdentifierBuilder.build();
averageRelativeVisibility = calculateAverageRelativeVisibility(relativeVisibilityByComponentIdentifier.values());
globalRelativeVisibility = calculateGlobalRelativeVisibility(relativeVisibilityByComponentIdentifier.values());
}

private static double calculateAverageRelativeVisibility(Collection<ComponentVisibility> componentVisibilities) {
double sum = 0;
for (ComponentVisibility componentVisibility : componentVisibilities) {
sum += componentVisibility.relativeVisibility;
}
return sum / componentVisibilities.size();
}

private static double calculateGlobalRelativeVisibility(Collection<ComponentVisibility> componentVisibilities) {
double numberOfVisibleElements = 0;
double numberOfAllElements = 0;
for (ComponentVisibility componentVisibility : componentVisibilities) {
numberOfVisibleElements += componentVisibility.numberOfVisibleElements;
numberOfAllElements += componentVisibility.numberOfAllElements;
}
return numberOfVisibleElements / numberOfAllElements;
}

/**
* The {@link VisibilityMetrics Relative Visibility (RV)} of the component.
*
* @see VisibilityMetrics
*/
@PublicAPI(usage = ACCESS)
public double getRelativeVisibility(String componentIdentifier) {
checkComponentExists(componentIdentifier);
return relativeVisibilityByComponentIdentifier.get(componentIdentifier).relativeVisibility;
}

/**
* The {@link VisibilityMetrics Average Relative Visibility (ARV)} of the components.
*
* @see VisibilityMetrics
*/
@PublicAPI(usage = ACCESS)
public double getAverageRelativeVisibility() {
return averageRelativeVisibility;
}

/**
* The {@link VisibilityMetrics Global Relative Visibility (GRV)} of the components.
*
* @see VisibilityMetrics
*/
@PublicAPI(usage = ACCESS)
public double getGlobalRelativeVisibility() {
return globalRelativeVisibility;
}

private void checkComponentExists(String componentIdentifier) {
checkArgument(relativeVisibilityByComponentIdentifier.containsKey(componentIdentifier),
"Unknown component with identifier '" + componentIdentifier + "'");
}

private static class ComponentVisibility {
final int numberOfVisibleElements;
final int numberOfAllElements;
final double relativeVisibility;

<T> ComponentVisibility(MetricsComponent<T> component, Predicate<? super T> isVisible) {
int numberOfVisibleElements = 0;
for (T element : component) {
if (isVisible.apply(element)) {
numberOfVisibleElements++;
}
}
this.numberOfVisibleElements = numberOfVisibleElements;
this.numberOfAllElements = component.size();
this.relativeVisibility = ((double) numberOfVisibleElements) / numberOfAllElements;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,20 @@
import com.tngtech.archunit.base.Function;

class TestElement {
final Set<TestElement> dependencies = new HashSet<>();
private final String name;
private final Set<TestElement> dependencies = new HashSet<>();

TestElement() {
this("irrelevant");
}

TestElement(String name) {
this.name = name;
}

String getName() {
return name;
}

void addDependency(TestElement element) {
dependencies.add(element);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.tngtech.archunit.library.metrics;

import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.ImmutableSet;
import com.tngtech.archunit.base.Predicate;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.JavaPackage;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.library.metrics.testobjects.visibility.one.VisibleOne;
import com.tngtech.archunit.library.metrics.testobjects.visibility.two.VisibleTwo;
import org.junit.Test;

import static com.google.common.base.Preconditions.checkArgument;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset;

public class VisibilityMetricsTest {

@Test
public void relative_visibility_with_single_element_reflects_element_visibility() {
MetricsComponent<TestElement> visible = MetricsComponent.of("visible", new TestElement("isVisible"));
MetricsComponent<TestElement> invisible = MetricsComponent.of("invisible", new TestElement("isNotVisible"));

VisibilityMetrics metrics = ArchitectureMetrics.visibilityMetrics(MetricsComponents.of(visible, invisible), visibleIfNameContainsIsVisible);

assertThat(metrics.getRelativeVisibility(visible.getIdentifier())).isEqualTo(1.0);
assertThat(metrics.getRelativeVisibility(invisible.getIdentifier())).isEqualTo(0.0);
}

@Test
public void relative_visibility_of_mixed_components_is_calculated_as_relation_of_visible_elements_to_all_elements() {
MetricsComponent<TestElement> oneThird = componentWithVisibilityPercentage(33);
MetricsComponent<TestElement> twoThirds = componentWithVisibilityPercentage(66);

VisibilityMetrics metrics = ArchitectureMetrics.visibilityMetrics(MetricsComponents.of(oneThird, twoThirds), visibleIfNameContainsIsVisible);

assertThat(metrics.getRelativeVisibility(oneThird.getIdentifier())).isCloseTo(0.33, offset(0.01));
assertThat(metrics.getRelativeVisibility(twoThirds.getIdentifier())).isCloseTo(0.66, offset(0.01));
}

@Test
public void average_relative_visibility_is_calculated_as_the_average_of_all_relative_visibilities() {
MetricsComponent<TestElement> oneThird = componentWithVisibilityPercentage(33);
MetricsComponent<TestElement> half = componentWithVisibilityPercentage(50);
MetricsComponent<TestElement> twoThirds = componentWithVisibilityPercentage(66);
MetricsComponent<TestElement> full = componentWithVisibilityPercentage(100);

VisibilityMetrics metrics = ArchitectureMetrics.visibilityMetrics(MetricsComponents.of(oneThird, half, twoThirds, full), visibleIfNameContainsIsVisible);

assertThat(metrics.getAverageRelativeVisibility()).isCloseTo(0.62, offset(0.01));
}

@Test
public void global_relative_visibility_is_calculated_as_relation_of_visible_elements_to_all_elements_across_all_components() {
MetricsComponent<TestElement> first = componentWithVisibilityDistribution(1, 3);
MetricsComponent<TestElement> second = componentWithVisibilityDistribution(900, 1);
MetricsComponent<TestElement> third = componentWithVisibilityDistribution(1, 67);

VisibilityMetrics metrics = ArchitectureMetrics.visibilityMetrics(MetricsComponents.of(first, second, third), visibleIfNameContainsIsVisible);

assertThat(metrics.getGlobalRelativeVisibility()).isCloseTo(0.93, offset(0.01));
}

@Test
public void calculates_visibility_metrics_for_Java_classes_according_to_their_modifier() {
JavaClasses classes = new ClassFileImporter().importPackagesOf(VisibleOne.class, VisibleTwo.class);
JavaPackage packageOne = classes.getPackage(VisibleOne.class.getPackage().getName());
JavaPackage packageTwo = classes.getPackage(VisibleTwo.class.getPackage().getName());

VisibilityMetrics metrics = ArchitectureMetrics.visibilityMetrics(MetricsComponents.fromPackages(ImmutableSet.of(packageOne, packageTwo)));

assertThat(metrics.getRelativeVisibility(packageOne.getName())).isEqualTo(0.5);
assertThat(metrics.getRelativeVisibility(packageTwo.getName())).isEqualTo(1.0);
assertThat(metrics.getAverageRelativeVisibility()).isEqualTo(0.75);
assertThat(metrics.getGlobalRelativeVisibility()).isCloseTo(0.66, offset(0.01));
}

private MetricsComponent<TestElement> componentWithVisibilityPercentage(int percentage) {
checkArgument(percentage >= 0 && percentage <= 100);
return componentWithVisibilityDistribution(percentage, 100 - percentage);
}

private MetricsComponent<TestElement> componentWithVisibilityDistribution(int numberOfVisibleElements, int numberOfInvisibleElements) {
Set<TestElement> elements = new HashSet<>();
for (int i = 0; i < numberOfVisibleElements; i++) {
elements.add(new TestElement("isVisible"));
}
for (int i = 0; i < numberOfInvisibleElements; i++) {
elements.add(new TestElement("isNotVisible"));
}

return MetricsComponent.of("Visible(" + numberOfVisibleElements + ")/Invisible(" + numberOfInvisibleElements + ")", elements);
}

private static final Predicate<TestElement> visibleIfNameContainsIsVisible = new Predicate<TestElement>() {
@Override
public boolean apply(TestElement input) {
return input.getName().contains("isVisible");
}
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.tngtech.archunit.library.metrics.testobjects.visibility.one;

@SuppressWarnings("unused")
class InvisibleOne {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.tngtech.archunit.library.metrics.testobjects.visibility.one;

@SuppressWarnings("unused")
public class VisibleOne {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.tngtech.archunit.library.metrics.testobjects.visibility.two;

@SuppressWarnings("unused")
public class VisibleTwo {
}

0 comments on commit c8ec061

Please sign in to comment.