블로그

Automatically Adding a Private Constructor with Sensei

December 14, 2020
앨런 리처드슨

Automatically Adding a Private Constructor with Sensei


In a utility class, when the fields and methods are static,  there is no obvious reason why I would ever instantiate it.

e.g. UtilityClass utility = new UtilityClass();

The code below is a simple implementation of a Utility class.

public class UtilityClass {
    public static final Boolean ULTIMATE_TRUTH = true;
    public static boolean getTrue(){
        return ULTIMATE_TRUTH;
    }
}


This is the type of coding pattern that Static Analysis tools can pick up, but they often don't supply the ability to fix the issue.

I can use Sensei to identify the coding pattern, and automatically generate a private constructor to make it impossible for me to instantiate the class.

Searching for the Class

I will add a new recipe on the Utility class called:

  •  Static Classes: create private constructor.


General Settings For Static Classes


And initially, I'll create a simple matcher to search for a class.

search:

  class: {}


This will match any class, which is good enough to let me get started writing a Quick Fix. Once I have a Quick Fix that works, I'll refine the search to make it highlight when there is more likely to be a class that requires a private constructor.

Quick Fix

For the Quick Fix, I will want to generate a private constructor.

In the example class this would look like:

   private UtilityClass(){}

To add the above code to my class, my Quick Fix will add a Method, and the name of the method will be a Mustache template that uses the name of the class.

availableFixes:

- name: "add private constructor"
  actions:
  - addMethod:
      method: "private {{{ name }}}(){}"


In the GUI Editor, I use the Show Variables to create the Mustache template and then edit the field to add the private modifier, brackets, and braces to make it syntactically correct.

Add Private Constructor

This would now allow me to add a private constructor to any class.

The QuickFix preview helps me because I can see the generated code as I write the Mustache template.

Utility Class Add Private Constructor

Now that I know I can fix the problem. I'll refine the search conditions to show the recipe when it is most appropriate.

Search for Missing Constructors

Ideally, I don't want to create a recipe that flags an error against every class. So I'll add some additional conditions in the search so that we only match on classes that do not have a constructor.

search:

  class:
    without:
      child:
        method:
          constructor: true


The YAML is slightly different from the GUI.

In the GUI I configure it to look for a class without a child method which is a constructor 'yes'. We use 'yes' in the GUI instead of 'true' to make the GUI a little more human friendly.


Search for class in code


This recipe will now only reveal itself for any class without a constructor.

Narrow Search for Likely Culprits

So I might want to go further and look for the presence of static methods or fields.

I look for any class without a constructor and which has either all public static fields or all public static methods.

search:

  class:
    with:
      anyOf:
      - child:
          method:
            allOf:
            - modifier: "public"
            - modifier: "static"
      - child:
          field:
            allOf:
            - modifier: "static"
            - modifier: "public"
    without:
      child:
        method:
          constructor: true


Since Sensei is used to help me, as a  programmer, in the IDE, rather than to statically analyze the code and report all errors, this filter is good enough to rule out most classes in my code base where I might have a good reason to have a default public constructor.

In some projects, this might be a step too far because the utility classes could have private methods, so I might choose to look for the presence of 'any' public static methods, rather than 'all'.

       - child:
           field:
              anyOf:
                - modifier: "static"
                - modifier: "public"


Hints

Sensei is not designed to replace a Static Analysis tool. Sensei can augment a Static Analysis tool for common issues associated with your coding process, or technology. By replicating enough of the matching to highlight an issue, and supporting the development process by generating the QuickFix code.

What I'm trying to do is create a simple enough recipe that includes all the situations I need it, but filter it so that it doesn't get suggested in every class.

When working on recipes I try to de-risk them, in this case, I wasn't sure if I could create the private constructor so I created the QuickFix first. Then refactored the search conditions to make them more specific.

Sometimes when working on recipes I'm not sure how to perform the search, so I work on that first.

I find recipes easier to create when I build them incrementally, switching between refactoring of the QuickFix and the search.

---


You can install Sensei from within IntelliJ using "Preferences \ Plugins" (Mac) or "Settings \ Plugins" (Windows)  then just search for "sensei secure code"


The source code and recipes for this can be found in the `sensei-blog-examples` repository in the Secure Code Warrior GitHub account, in the `pojoexamples` module.

https://github.com/securecodewarrior/sensei-blog-examples

‍

태그라인

배포 전 AI 기반 개발 거버넌스 확보

AI 기반 위험을 측정하고, 커밋 시점에 보안 코딩 정책을 적용하며, SDLC 전반에 걸쳐 안전한 소프트웨어 제공 속도를 높이세요.

데모 예약하기
리소스 라이브러리

더 많은 블로그 살펴보기

보안 코딩, AI 거버넌스, 소프트웨어 리스크 관리에 관한 전문가 콘텐츠를 확인해 보세요.

전체 보기
사례 연구
필터 라벨
div 블록 내부의 텍스트입니다.

Supercharged Security Awareness: How Tournaments are Inspiring Developers at Erste Group

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. Duis cursus, mi quis viverra ornare, eros dolor interdum nulla, ut commodo diam libero vitae erat. Aenean faucibus nibh et justo cursus id rutrum lorem imperdiet. Nunc ut sem vitae risus tristique posuere.

더 알아보기
사례 연구
필터 라벨
div 블록 내부의 텍스트입니다.

Security as culture: How Blue Prism cultivates world-class secure developers

Learn how Blue Prism, the global leader in intelligent automation for the enterprise, used Secure Code Warrior's agile learning platform to create a security-first culture with their developers, achieve their business goals, and ship secure code at speed

더 알아보기
사례 연구
필터 라벨
div 블록 내부의 텍스트입니다.

하나의 보안 문화: Sage는 어떻게 챔피언 프로그램을 구축했는가

Sage가 유연하고 관계 중심적인 접근 방식을 통해 보안을 강화하고, 200명 이상의 보안 챔피언을 양성하며 실질적인 위험 감소를 달성한 사례를 확인해 보세요.

더 알아보기
블로그
필터 라벨
div 블록 내부의 텍스트입니다.

2026년 사이버 보안 인식의 달: 기업 방어의 핵심, AI 보안 이해하기

주요 AI 기업 대부분이 안전 가이드라인이 마련될 때까지 AI 개발 속도를 전 세계적으로 늦춰야 한다고 공개적으로 촉구하는 시점에 이르렀지만, 사실 심각한 보안 문제는 이미 현실화되었습니다. 이로 인해 AI 도입에 따른 금전적 비용과 위험 부담이 계속 쌓이면서 수많은 보안 책임자와 경영진이 절박한 상황에 놓였습니다.

더 알아보기
블로그
필터 라벨
div 블록 내부의 텍스트입니다.

인에이블러 8: 프로그램 브랜딩

성공적인 보안 코딩 프로그램을 위해서는 훌륭한 콘텐츠 그 이상의 것이 필요합니다. 인에이블러 8에서는 브랜딩을 통해 참여를 누구나 선망하는 위상 중심의 경험으로 바꾸는 방법을 알아봅니다.

더 알아보기
블로그
필터 라벨
div 블록 내부의 텍스트입니다.

이제 모든 직원이 AI 사이버 보안의 최전선에 있습니다

엔터프라이즈 기술 환경은 너무 늦기 전까지는 아무도 예상하지 못한 속도로 변화하고 있습니다. 우리는 공식적으로 사람이 직접 작성한 코드와 기본적인 코파일럿 지원의 시대를 지나 '에이전트 기반 개발 수명 주기(ADLC)'의 시대로 진입했습니다. 자율형 AI 에이전트는 여러 기능 전반에 걸쳐 전례 없는 효율성을 약속하지만, 동시에 완전히 새로운 차원의 보안 및 규제 위험을 야기합니다.

더 알아보기

배포 전 AI 기반 개발 보안 확보

소프트웨어 개발 수명 주기 전반에서 개발자 리스크를 파악하고, 정책을 시행하며, 취약점을 예방하세요.

데모 예약하기
항목이 없습니다.