Skip to content

Simplify code by using DuplicateRecordFields and NamedFieldPuns #206

Open
@zhujinxuan

Description

@zhujinxuan

Recently I am working on #205, and I find that I have to manually add _ everywhere for adding position infomation. And we can see quite a lot repetitive code like (in Validation.hs)

-- | Get the selection set for an operation.
getSelectionSet :: Operation value -> SelectionSetByType value
getSelectionSet (Query _ _ ss) = ss
getSelectionSet (Mutation _ _ ss) = ss

However, we can simplify them with DuplicateRecordFields and NamedFieldPuns. For example, we can have the following code in Validation.hs that:

{-# DuplicateRecordFields #-}

data Operation value
  = Query {
       _ss :: VariableDefinitions
      , _dv :: (Directives value) 
      , getSelectionSet :: (SelectionSetByType value)
  | Mutation {
      _ss :: VariableDefinitions 
      , _dv :: (Directives value)
      , getSelectionSet :: (SelectionSetByType value)
   } deriving (Eq, Show)

Furthermore, with {-# NamedFieldPuns #-}, we can simplify some other code from

    splitOps (AST.Query node@(AST.Node maybeName _ _ _ _) _) = Right (maybeName, (Query, node))

to

{-# NamedFieldPuns #-}
    splitOps AST.Query {_node = node@AST.Node {_name = maybeName}}  = Right (maybeName, (Query, node))

Personally, I think by that we can make code easier to write without carefully counting the number of _s, and take advantage with other language extensions of Records when developing with graphql.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions