Denormalising a database for speed – is it an anti-pattern

I have a database with 1:m relationship.

I have to display a list of parents to the user rapidly on a home screen at startup. The parent shows a single piece of information that is a SUM of a particular child field for that parent.

I dont want the expense of making large queries to the child table (essentially doing lists of calculations on the entire child table) – in order to show the parents. I also feel its important to show the SUM to the user on the home screen.

I have therefore denormalised the SUM of all children for a particular parent and added it as a field within the parent table. Each time a CRUD operation is done within the child table (with an ID that matches a particular parent), i recalculate and reinsert the new value.

Is this an anti-pattern and therefore ‘bad’ practice? I felt i was doing the right thing by prioritising performance for the UI.

design – CQRS: Is it an antipattern if the Command invokes a database interface which contains business logic?

Martin Fowler states that,

Command module executes validations and consequential logic

which aligns with every CQRS demo app that I’ve studied.

That is to say: validation — does this Jedi exist? — and consequential logic — if not, create it — are all responsibilities of the command(s). The logic is not encapsulated within an interface of a database context. Implementations of CQRS seems to exercise Fowler’s opinion on this by having Commands and Queries that contain all the business logic while directly invoking a relatively flat and simple service or database context. As an example,

public async Task<Guid> Handle(GetOrCreateJedi request, CancellationToken cancellationToken) {
    var entity = _context.Jedi.FirstOrDefault(j => j.FirstName == request.FirstName
        && j.LastName == request.LastName);
    if (entity == null) {
        entity = new Jedi()
        {
            Id = Guid.NewGuid(),
            FirstName = request.FirstName,
            LastName = request.LastName
         };
         
         _context.Jedi.Add(entity);

         await _context.SaveChangesAsync(cancellationToken);
    }
    return entity.Id;
}

// the controller
public async Task<ActionResult> GetOrCreate((FromQuery) GetOrCreateJedi command)
{
    var id = await Mediator.Send(command);

    return Ok(id);
}

The more traditional MVC approach seems to boil down to a controller invoking a context where the interface either abstracts:

  1. the underlying business logic: “If the Jedi exists, return it – else, create it and then return it”, or
  2. direct calls to the database.

This allows for much simpler mocking.

public async Task<ActionResult> GetOrCreate(string firstName, string lastName) {
    var id = await _jediDbContext.GetJedi(id);

    if (id == null) {
        id = await _jediDbContext.CreateAndSaveJediAsync(

    return Ok(id);
}

//mock
_mockContext.Setup(c => c.Jedi.GetJedi(It.IsAny<Guid>).Returns(... whatever ...);

In the above example, we don’t need to worry about mocking everything inside the GetJedi() method. If we had to, we’d find ourselves challenged with trying to mock non-extensible methods like that in _context.Jedi.FirstOrDefault(). I’d like to create interfaces for these database contexts because I would like to construct unit tests with mocking but…

Is it an antipattern in CQRS to create database interfaces that contain business logic?

Are dynamic menus an anti-pattern?

I’m analyzing the menu of construction management software. I don’t know if I don’t have the same user mental models and what was the research behind those decisions, but I wonder based on HCI and usability research, are those antipatterns?

Procore

Project 2 Home Screen
enter image description here

Switch Project
enter image description here

Project tools "local links of the project"
enter image description here

Customizing Menu
enter image description here

Fieldwire

Photos
enter image description here

Plans
enter image description here

Switch Project
enter image description here

python – Are user-callable recursive functions an anti-pattern?

I have a function in python that calls itself recursively, and has some internal variables
passed down the recursion using keyword arguments (that are not listed in the docstring)

Is it a problem to have this exposed to an user instead of defining another private recursive function that is called by a public function. Where the public function would be a wrapper around the recursive function.

I cannot think of any downsides of the first approach compared to the second.

terminology – General term to describe the anti-pattern where the same concept is described in different ways?

Our codebase is old and very large. Over the years, many developers have worked on the code and frequently refered to the same concept inconsistently.

For example, we have a “number that uniquely identifies the study” or “Study ID”. This is refered to as studyNum, examId, Exam, StudyNo, StudyID, the odd StudyUID or just ID…the full list of variations, including variations in capitalisation, is tediously long! This makes searching difficult and the software harder to modify.

Is there a general software engineering term for this inconsistency/term creepage and the maintenance challenges that result?

(PS: Along with normal development work, I’m applying “Clean Code” (aka Robert Martin) principles to slowly tidy these up!)

Is putting general-use functions in a “helpers” file an anti-pattern or code smell?

Is it an anti-pattern or code smell to put “general use” functions (examples below) into a catch-all file named “helpers” or “utils”?

It’s a pattern I’ve seen quite a lot in the JavaScript world, which I’ve also seen with other languages.

By “general use” functions, I mean functions which abstract away some common, shared functionality used in an application/library and make them available for use in a general way. Some examples I’ve seen include returning a copy of an object with some keys omitted, transforming all null-ish values in a JavaScript object (eg. "", null, {}, ()) to undefined, constructing a URL from a struct of parameters, transforming strings in some fashion, etc, etc.

I often come across applications or libraries with one (or more!) util.js or helpers.ts files which just seem to be, in my opinion, a dumping ground for unrelated functions. In my opinion, code is more readable and discoverable if it’s named semantically.

If working with the examples above, I’d place them all in their own files (omit.js, null-to-undefined.js, url-builder.ts, etc), or if they are related functionality, group them (eg, deepClone, withoutKeys, shallowClone, in clone.js or similar).

I struggle to articulate why this seems like a code smell or anti-pattern to me. I think there are various things at play: creating the wrong abstraction or abstracting at the wrong time (YAGNI) meaning code is just dumped “somewhere”, lack of foresight for future maintainability.

On the other hand, I’ve seen proponents of this pattern argue that it’s a well-used pattern, and thus it has merit simply because it’s well-used. Does this argument stand?

Interesting in anyone’s thoughts on this, whether you think it’s good or bad, and if you can explain the pros/cons better than I can!

architecture – Microservice Design – Many microservices reading from a DB. Antipattern?

I’m working on a system design and feel like I’m doing it wrong.

Situation

I have two services and they each have a bunch of data they each need. Much is overlapping data from overlapping tables. Also, I believe these services will be the sole users of these tables.

Let’s say Service A needs T1, T2, T3, T4, and Service B needs T2, T3, T4.

It’s been suggested I make 4 microservices who sole purpose is to read those 4 tables. That feels like a “too many microservices” anti-pattern.

My Thoughts

All four tables are roughly in the same business domain, and I’d imagine Service A and Service B would be the sole users of all four tables. So I’m thinking we make a single microservice which gets called for any of the T* data. I think everything can scale happily: the services, microservice, and db.

Is there some tradeoff I’m not seeing? Or reason I should use 4 services? I don’t think the query logic will be complex for any of the reads, so the source code could be small even for the single microservice solution.

What am I missing?

code smell – How to tackle a ‘branched’ arrow head anti-pattern?

user61852 has a pretty good answer solving the general problem of simplifying nested conditionals. However, I was intrigued with your proposed state machine-like solution, and wanted to illustrate how that can sometimes be preferable to a set of binary flags.

It all depends on the sequence of obtaining the flags’ values and how many combinations are valid. If you have n flags, you have 2n states. For 4 flags, that’s 16 states, and as you observed, only 3 of them may have any useful meaning. In situations like that, using a state variable instead can simplify things greatly.

Let’s say you have a lock that will open if 4 keys are pressed in the right order. If you press any key incorrectly, it immediately resets back to the start of the sequence. A very na├»ve way to implement a keypress handler using binary flags is:

void key_pressed(char key)
{
   if (!key1correct)
   {
      if (key == pin(0))
      {
         key1correct = true;
      }
   }
   else if (!key2correct)
   {
       if (key == pin(1))
       {
           key2correct = true;
       }
       else
       {
           key1correct = false;
       }
   }
   else if (!key3correct)
   {
       if (key == pin(2))
       {
           key3correct = true;
       }
       else
       {
           key1correct = false;
           key2correct = false;
       }
   }
   else
   {
       if (key == pin(3))
       {
           key4correct = true;
       }
       else
       {
           key1correct = false;
           key2correct = false;
           key3correct = false;
       }
   }

   if (key1correct && key2correct && key3correct && key4correct)
   {
       open_lock();
       key1correct = false;
       key2correct = false;
       key3correct = false;
       key4correct = false;
   }
}

A simplified, flattened version using binary flags (like user61852’s answer) looks like this:

void key_pressed(char key)
{
    if (!key1correct && key == pin(0))
    {
        key1correct = true;
        return;
    }

    if (key1correct && !key2correct && key == pin(1))
    {
        key2correct = true;
        return;
    }

    if (key1correct && key2correct && !key3correct && key == pin(2))
    {
        key3correct = true;
        return;
    }

    if (key1correct && key2correct && key3correct && key == pin(3))
    {
        open_lock();
        key1correct = false;
        key2correct = false;
        key3correct = false;
        return;
    }

    key1correct = false;
    key2correct = false;
    key3correct = false;
}

That’s a lot easier to read, but still in both of these solutions you have states like key2correct && !key1correct that are completely invalid and unused. Whereas using a state variable num_correct_keys instead of the binary flags looks like this:

void key_pressed(char key)
{
    if (key == pin(num_correct_keys))
        ++num_correct_keys;
    else
        num_correct_keys = 0;

    if (num_correct_keys == 4)
    {
        open_lock();
        num_correct_keys = 0;
    }
}

Granted, this is a contrived example, but people often write code like the first version in less obvious situations, sometimes spread across multiple files. Using a state variable often greatly simplifies code, especially when the flags represent a sequence of events.

spring – Are these Unit tests OK or am I implementing an antipattern or not following best practices

I am testing a Spring boot service using JUnit 5 and Mockito. I haven’t spent much time on unit testing in the past so I’m not sure if I’m accidentally implementing an anti-pattern or not following best practices.

I read multiple times that it’s good practice to have one assertion per test, I have one assertion but I also have a few verify assertions that check if the method I’m testing called the correct methods with the correct input based on the conditional branch I’m testing as well as the input to the method I’m testing, is this OK/acceptable or should I split it up into one assertion/verify assertion per test? It feels like that would require a lot of code duplication… Below are four tests I wrote and the method I’m testing. For clarity I’ll also add the code that sets up and handles my test application context.

Any ideas/advice would be much appreciated.

The method I am testing:

@Transactional
    override fun startSession(msisdn: String, origConnID: String, configSetName: String): StartSessionResponseDTO {
        val txId = generateTxID()
        val ss = sessionStatus(msisdn)

        eventService.logEvent(EventType.StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))

        if (ss == null) {
            throw ApplicationException(type = ApplicationException.Type.client_error, message = "Concurrent Access Detected: ${msisdn}")
        } else {
            if (ss.sessionId == null || ss.ip == null) {
                //create new Nuance session
                nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName)).let {
                    updateSession(msisdn = msisdn, sessionId = it.sessionId, ip = it.ip, origConnID = origConnID)
                }
            } else {
                //check if the sessionId is still valid
                if (!nuanceService.isSessionValid(txId = txId, msisdn = msisdn, sessionId = ss.sessionId, host = ss.ip, configSetName = configSetName)) {
                    nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName)).let {
                        updateSession(msisdn = msisdn, sessionId = it.sessionId, ip = it.ip, origConnID = origConnID)
                    }
                }
            }
        }

        eventService.logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
        return StartSessionResponseDTO(msisdn)
    }

My test class:

@ExtendWith(SpringExtension::class)
@ContextConfiguration()
class  VBServiceTests() {

    @TestConfiguration
    class testConfig {
        @Bean
        fun jdbcTemplate(): NamedParameterJdbcTemplate {
            return mock<NamedParameterJdbcTemplate>()
        }

        @Bean
        fun nuanceService(): NuanceService {
            return mock<NuanceService>()
        }

        @Bean
        fun appConfigProps(): AppConfigProps {
            return mock<AppConfigProps>()
        }

        @Bean
        fun eventService(): EventServiceImp {
            return mock<EventServiceImp>()
        }

        @Bean
        fun audioTrimService(): AudioTrimService {
            return mock<AudioTrimService>()
        }

        @Bean
        fun vbNuanceStagingDeletionService(): VbNuanceStagingDeletionsService {
            return mock<VbNuanceStagingDeletionsService>()
        }
    }

    @MockBean
    lateinit var nuanceService: NuanceService

    @MockBean
    lateinit var eventService: EventServiceImp

    @SpyBean
    lateinit var vbServiceSpy: VbServiceImp

    val msisdn = "0821234567"
    val origConnID = "o123"
    val sessionId = "0821234567"
    val ip = "127.0.0.1"
    val txId = "1234-5678"
    val configSetName = "LoIvrPhraIvrHdr"

    @Test
    fun `startSession | When method is called with valid input a StartSessionDTO is returned, if no Nuance session exists a new Nuance session will be created and persisted`() {
        doNothing().whenever(vbServiceSpy).updateSession(msisdn, origConnID, sessionId, ip)
        doReturn(txId).whenever(vbServiceSpy).generateTxID()
        doReturn(SessionStatus(msisdn, origConnID, null, null)).whenever(vbServiceSpy).sessionStatus(msisdn)

        given(nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))).willReturn(NuanceStartSessionRespDto(txId, sessionId, ip))

        assertThat(vbServiceSpy.startSession(msisdn, origConnID, configSetName), Is(StartSessionResponseDTO(msisdn)))
        verify(vbServiceSpy).generateTxID()
        verify(vbServiceSpy).sessionStatus(msisdn)
        verify(eventService).logEvent(StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
        verify(nuanceService).startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))
        verify(vbServiceSpy).updateSession(msisdn = msisdn, sessionId = sessionId, ip = ip, origConnID = origConnID)
        verify(eventService).logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
    }

    @Test
    fun `startSession | When method is called with valid input a StartSessionDTO is returned, if existing valid Nuance session exists the existing session will be used`() {
        doNothing().whenever(vbServiceSpy).updateSession(msisdn, origConnID, sessionId, ip)
        doReturn(txId).whenever(vbServiceSpy).generateTxID()
        doReturn(SessionStatus(msisdn, origConnID, sessionId, ip)).whenever(vbServiceSpy).sessionStatus(msisdn)

        given(nuanceService.isSessionValid(txId, msisdn, sessionId, ip, configSetName)).willReturn(true)

        assertThat(vbServiceSpy.startSession(msisdn, origConnID, configSetName), Is(StartSessionResponseDTO(msisdn)))
        verify(vbServiceSpy).generateTxID()
        verify(vbServiceSpy).sessionStatus(msisdn)
        verify(eventService).logEvent(StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
        verify(eventService).logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
    }

    @Test
    fun `startSession | When method is called with valid input a StartSessionDTO is returned, if existing invalid Nuance session exists a new session will be created and the existing session record will be updated`() {
        doNothing().whenever(vbServiceSpy).updateSession(msisdn, origConnID, sessionId, ip)
        doReturn(txId).whenever(vbServiceSpy).generateTxID()
        doReturn(SessionStatus(msisdn, origConnID, sessionId, ip)).whenever(vbServiceSpy).sessionStatus(msisdn)

        given(nuanceService.isSessionValid(txId, msisdn, sessionId, ip, configSetName)).willReturn(false)
        given(nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))).willReturn(NuanceStartSessionRespDto(txId, sessionId, ip))

        assertThat(vbServiceSpy.startSession(msisdn, origConnID, configSetName), Is(StartSessionResponseDTO(msisdn)))
        verify(vbServiceSpy).generateTxID()
        verify(vbServiceSpy).sessionStatus(msisdn)
        verify(eventService).logEvent(StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
        verify(nuanceService).startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))
        verify(vbServiceSpy).updateSession(msisdn = msisdn, sessionId = sessionId, ip = ip, origConnID = origConnID)
        verify(eventService).logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
    }

    @Test()
    fun `startSession - When method is called with valid input when sessionStatus returns null concurrent access is detected and an ApplicationException gets thrown`() {
        doReturn(txId).whenever(vbServiceSpy).generateTxID()
        doReturn(null).whenever(vbServiceSpy).sessionStatus(msisdn)

        val exception = Assertions.assertThrows(ApplicationException::class.java) {
            vbServiceSpy.startSession(msisdn, origConnID, configSetName)
        }

        assertThat(exception.message, Is("Concurrent Access Detected: ${msisdn}"))


        verify(vbServiceSpy).generateTxID()
        verify(vbServiceSpy).sessionStatus(msisdn)
    }


}

javascript – Is there a term or pattern / anti-pattern related to explicitly returning an object within a constructor?

Is this design choice good or bad? Interested in any patterns / anti-patterns involved in writing code like this.

Let’s say I’ve written an Element class that helps me flesh out DOM elements and behavior dynamically and I want to define an instance of Element in its own separate file for code organization purposes.

Let’s say the following call would have more properties than I care to have written out in the current file:

new Element({
    // complex object structure
})

So instead I have a use method to pass the necessary data to a wrapper class written elsewhere, like so:

const Publisher = require("../manifest/classes/publisher.js")
const ElementsPanel = require("../manifest/components/elements-panel.js")
let publisher = new Publisher()
module.exports = class {
  constructor(env) {
    this.publisher = publisher
    new ElementsPanel().use({
      traits: {
        publisher,
        env
      },
      actions: {
        select: self => {}
      },
      ready: (
        self => {
          console.log("ready triggered")
        }
      )
    }).appendTo(document.body)
  }
}

Where ElementsPanel is a class that contains the settings to generate the desired instance of Element. I could use a function, but createElementsPanel() looks a little less object-oriented to me than new ElementsPanel() and I’m trying to follow an object-oriented design approach. Instead of doThings() I want thing = new Thing(), thing.getDone().

Alternatively requiring the instance itself as an export forces either the instance of Element to be created immediately, or a require call to be used further into the code, and I like to keep my require calls at the top. So this is a style choice.

ElementsPanel:

const Element = require("../../element.js")
module.exports = class {
  constructor() {
    return new Element("div", {
      id: "elements-panel",
      classes: ("hidden"),
      actions: {
        update: (self, voxel) => {
          console.log("elements panel updating with spawned voxel:", voxel)
          if (!self.traits.elements(voxel.element)) {
            self.traits.elements(voxel.element) = {
                // ...
            }
          }
        }
      },
      ready: (
        self => {
          let tickCount = 0
          self.traits.elements = {}
          self.traits.publisher.on("spawn", voxel => {
            self.actions.update(voxel)
          })
        }
      )
    })
  }
}

I like how this looks better than the alternatives I’ve considered, but it uses a class without that class being stateful, and I believe the rule of thumb is to use classes when your object needs to be stateful. The class instead is used here as a syntax style mechanism.

So I’m asking whether what I’m doing here is associated with a common term, pattern, or anti-pattern so I can change it now if necessary before someone sees my code one day and banishes me to developer h*ll.