Skip to Content

Sorry Singleton I don’t love you anymore.

image

Q: Where have all the global variables gone?

A: They became singletons.

Some Background.

Recently I am having the privilege of being involved in an EhP5 “upgrade” project at a leading  international entertainment and media company. Given that 6 or so years ago I was putting in an ITS version of ESS at this same company (which has survived pretty much unchanged until now) it was probably high time that they did consider “upgrading”.

As many will know, one of the main “attractions” in the HCM side of  EhP5 or Business Suite Innovations 2010 is the change over from a Web Dynpro Java (WDJ) Employee Self Service (ESS) to a Web Dynpro ABAP (WDA) solution. This gives us some real flexibility in enhancing the standard services to meet the specific needs of each implementation. Whilst at a code level SAP have mainly just replaced the WDJ service with WDA ones which do pretty much the same thing, there have been a few changes.

One of the most significant changes has been the switch over from a function group/function module based coding approach (necessitated by using RFC enabled function modules to interact with WDJ) to a more class based approach. (Some of the functionality was already very OO based, but it’s even more so now.)

OO so good.

I have to say I applaud this change.  Using classes and a more object orientated approach is a good thing. For a start, type checking is much better, and as of 7.02 I can build my beloved Law of Demeter defying train-wrecks. There are so many benefits to designing in an OO sense, that I’m not going to try to cover them all here. Let’s just pretend to agree that OO programming is a good thing. If you don’t agree, that’s fine, I accept that you may have a point in one microscopically small instance that exists for something approaching Plank time.

 

Patterns of little singletons

Patterns everywhere.

But there is one little change that has crept up on me and I am seeing more and more of it in standard SAP code. This is the singleton class pattern. The basic idea of a singleton is that it is an object instance that should exist only once in memory. So for those things that should only every have one instance at a time. You know, like global variables… Perhaps this is some internal SAP thought – in a recent discussion with Thomas Jung he has some very favourable remarks about the use of singletons as a memory efficient means of sharing data between WDA components.

In a world of change, some things are constant?

Sometimes SAP developers are accused of moving slowly, and I can understand why. When you look at the features of the ABAP language that are only just starting to get explored by developers and some of the developers out there who still have no idea about what OO is about, but yet have little difficulty in finding work, it makes me sad. Still you think we could turn this to our advantage, as we’d have plenty of time to learn from the non-SAP world about good and bad practice?

I recently sent a less than 140 character message to a really clever man I know (recent winner of SAP Tech Ed Las Vegas Demo Jam, “the real one” according to Ed Herrmann) :

” alisdair73: A Singleton class pattern is effectively a complex global variable. Global variables are bad. Discuss… “

Discussion ensued and Alisdair Templeton set me on the path to understanding a little more about singletons. It was only the start of a discovery about how the rest of the world hates the singleton pattern. Thoughts vary from Singletons being evil, to stupid, to depressing. It seems hardly anyone has a good thing to say about them.

“Singletons are Evil”

Why is this? I’ll try to summarise for the sake of all those of us out there who look at SAP standard coding and use it as the basis for our next project.  (Perhaps I’m learning, perhaps not.)

Firstly a singleton can be a type of global variable – why don’t we like global variables? The problem with global variables is that you never know what bit of code is going to modify it. You cannot code a unit test for your own code without first setting the state of an external value and then hoping like mad it doesn’t change. A singleton has global state, which not only means that my code has to run in circles to handle what it could be doing, it also could be changed in the middle of my code and I’d never know about it. Imagine the fun you’d have debugging that one!

Secondly, you cannot have, by very definition, two singleton instances. It is a very, very, rare case that you will only ever want to have one instance. If you build it so you can only have one, there will come a time in the future when you will want to have more and you will be stuffed (technical term oft used in Australia.)

And in particular:

Getting back to my EhP5 ESS implementation, the one particularly irksome singleton that has arrived on the scene is to do with the currently selected employee. This is used throughout the code. I can select an employee and start a new application, and that application can find out what employee I selected – wonderful. But I could also change the selection, what happens then? Well there is some logic to apply a “handle” to the singleton to ensure you get the one you want… But it’s still a singleton. If I call some method in my code, there is certainly no guarantee that the globally accessible state of the singleton will not have changed. Goodbye to the idea of test driven development…  It will be a challenge when I’m asked to display two employees side by side in the same application using “standard” code.

Why do this to me?

Given that the singleton is required to be able to construct itself from a given database handle (as a new application could fire off in a different app server) why not just make it a non-singleton and pass it around? Perhaps there are reasons that are deeper than I understand from my brief exposure to the code. Using this particular pattern seems to occur more in the EhP5 code (especially in sharing data between WDA components and/or WDA assistance classes). Even though it is being used more a brief web search reveals that it doesn’t just seem to be me that is adverse to this pattern for use in any circumstances.

STOP, Think, would you really use a global variable?

To summarise (again).

  • Just because it says it’s a pattern and because it is supposedly OO does not mean it is good.

If you are tempted to use a singleton, stop! Think. Would you code the same thing with global variables? If you would, well, nothing I’m going to say would stop you, go ahead, because we all want ” Singletons over carefully reasoned, loosely coupled design” don’t we? (I hope not!) If the term “global variable” actually does give you a little concern, please, please reconsider that singleton pattern you were thinking of using.

 

Disclaimer: you shouldn’t listen to anything I say. It’s likely to be wrong, misleading, confusing and unrepresentative, and in no way reflects the opinions of my employer or most sane people. Any perception of a deeper understanding is probably just an optical illusion and you should be very careful in interpreting it otherwise.

P.S. all the little drawings of singleton code men (yes that is what they are supposed to be, that’s why there is a 1 on his/her front) are badly drawn by me 🙂 Hope you like them.

To report this post you need to login first.

33 Comments

You must be Logged on to comment or reply to a post.

  1. Thomas Jung
    If I follow your train of thought in this blog, then all usages of Shared Memory Objects would be wrong as well? 

    You bring up valid points about how Singletons can be designed incorrectly, but I think there are some valid use cases.  Keep in mind as well, that in ABAP Singletons are per user session; which does give them slightly less scope than in some other programming languages.

    Your main arguing point in this blog seems to be about access control and testing.  However if you design your singleton class without any public attributes so that all access must come via methods, it seems like you still retain a proper level of control. That is how I’ve used it in the past – as a controlled way of having some shared data between loosely coupled components (GUIBB Feeder Classes mostly).

    (0) 
    1. Chris Paine
      Hi Thomas,

      perhaps my train of thought is misleading then…

      A shared memory object is addressed by a particular handle – in effect an instance reference to the object. Yes anything can update the object outside of the method I’m trying to unit test – but in order to do that it must have a reference to the instance. If I’m sharing that instance reference around in a global variable, or a singleton class, then yes they would be equivalent, otherwise, not really…

      Oops – realised have team meeting – will reply to rest when I’m back!

      (0) 
      1. Chris Paine
        Back again…

        Yes, given that we are talking about a single user memory session there is less scope for the abuse of global variables, but they are still, in my opinion, a suboptimal solution to just taking the time to pass a reference to a data sharing instance between your classes/methods.

        One particularly confusing point for support when you are using a singleton pattern is that it is not obvious when looking at a method call how on earth the data is being transported. I found this rather confusing when first looking at the EhP5 ESS services. Even BAdI calls are made without explicitly passing the personnel number that is being dealt with. The person enhancing the solution is expected to know that if they want to retrieve any details of the currently selected employee, they need to reference the singleton. This sort of approach is (again, my opinion) quite counter-intuitive. If instead a reference to the data sharing class could be passed in the call, it would be very obvious what was happening.

        Ensuring that data in the singleton can only be accessed via getter and setter methods is, I think a good idea, as it allows a better encapsulation of the working logic of your implementation. But it doesn’t prevent any of the issues about a global state meaning that unit test cases have to take into consideration the global state of the singleton and attempt to produce tests cases that can handle it.
        Perhaps if the setter methods triggered an event of the class that I could subscribe to, it would be better – I could then at least handle the impacts of an unexpected state change.

        Overall, however, I think that using events to pass data sharing references between UIBBs would be a better approach. It is loosely coupled, but also explicit – you know exactly what is passed. it’s easy(er) for a support person to follow what is going on. This also allows you the freedom to have multiple of these instances. When I’m considering something as generic as a selected employee, it is clear that the potential use case goes well past just having one at a time. Rather than face an awkward retrofit/reimplementation in the future, as more of these situations occur, I would like that people consider if the pattern really does make sense, or are they just being a little lazy in not passing a data sharing reference in their class methods.

        I’d also argue that a singleton pattern cannot by definition be a “controlled” way of sharing data, as anything can get a reference to it. It could open up what perhaps should be a relatively encapsulated means of data sharing to a much more public interface.

        Thanks for your comments. Good to see someone other than AT was reading this. Hopefully I’ve not pitched at too high a level for most people to understand.

        Cheers,
        Crhis

        (0) 
    2. Alisdair Templeton
      Hi Chris and Tom.

      (Chris, I wrote this up earlier and have just seen your response to Thomas – looks like were on the same page re Events).

      Firstly, Chris, really enjoyed the Blog – nice job!

      I just wanted to follow up on Tom comments.

      Is using Shared Memory Objects wrong – It really depends on how your using it…IMHO, if your using it as nothing more than a Global Variable then yes, I think this is wrong. Personally I see Shared Memory as a powerful way to add an in-memory strategy to your Persistance Layer (Caching). Of course you can do the same thing with Singletons, except the scope of the Cache is reduced to the current user session. This all comes down to where in you architecture you use this type of technique – personally I feel SMO is a bottom of the stack type of approach…

      I’ve only seen one “valid” use case in recent times in SAP for the use of the Singleton – sharing data between WD Components in the FPM. As Thomas quite rightly pointed out, it facilitates the transfer of data between two UIBBs etc. The trouble with this is that it changes our loosely coupled components to more tightly coupled components through the dependence on the Singleton Class. The Singleton, being mutable (and this doesn’t really matter if its via Public attributes of public mutator methods), brings in all the issues that Chris has described.

      So whats the alternative? I think the answer is to look at how the components would work in isolation and then extrapolate from there. A list of Employees as a stand alone component would probably just raise an “Employee Selected” event to anyone thats listening. An Employee Detail screen would just need to know the Employee Id to use when its opened. Can the 2 be linked together via the FPM Event model? I think so. The Composite App that is mashing these components together is responsible for translating between the 2 components – It holds all the dependencies, meaning the used components stay autonomous and unaware of each others existance…highly cohesive but loosely coupled, and no global state – or atleast thats the idea… 😉

      AT

      (0) 
      1. Thomas Jung
        Don’t get me wrong, I’m no great defender of Singleton. I’ve seen it abused as you describe. But my point was that I’ve also seen it used to good effect. I agree it would be cleaner to pass around an object reference, but sometimes that just isn’t a possibility without extending the higher level framework (in the case of FPM). It certainly is a better option than shared data components because of the cost of cross component context binding (memory duplication for each component usage).  Perhaps to be a better design, the singleton should only be used to facilitate the passing of an object reference. It would allow multiple instances of an object to be managed, but do you really have been encapsulation then?

        >I think the answer is to look at how the components would work in isolation and then extrapolate from there.

        That might produce a more elegant design, but a higher cost to performance? Do you repeat database selections in order to completely decouple UIBBs? Where do you draw the line between design, resuability and performance? That’s the problem with an argument that works in extreme right or wrong.

        >Can the 2 be linked together via the FPM Event model?

        Ultimately that is where FPM is headed (but not quite there yet).  If we look to the future of BOL as the underlying business logic and data persistence layer and perform the connection to both Freestyle UIBBs and Generic UIBBs via FPM wiring we have much more decoupling (thanks to wiring to an interface instead of dependence upon a singleton class).  You also get an event based model, but without complete isolation and reimplemenation of the business logic in each UIBB.

        (0) 
        1. Chris Paine
          Just an aside, I have used the FPM event model to pass references to shared data instances between UIBBs. Perhaps the way I’ve done this isn’t very good (more times around the FPM event loop for every UIBB on startup) but it certainly is currently (7.01) possible (and without resorting to any wdr_* hacks).
          I did this because I found I had a tightly coupled solution that I wanted to use in a different application. By instead eventing out the reference to the shared data, I could easily integrate it where-ever I wanted, and also as many times as I wanted (this was a design consideration which meant the singleton pattern was not appropriate).
          If I had though a little in the first place, I can see that this should have been my initial design.
          I can see how some framework enhancements (for example to be able to see easily which UIBB raised an event would be nice) could help with this, but I don’t think it’s out of the realms of possibility to start thinking about using this approach today.
          (0) 
        2. Alisdair Templeton
          Great Discussion – we should have had a panel discussions like this at Mastering!

          The easy answer is yes, the components are autonomous, and by defintion must work in their own right. They are responsible for getting their own data. Performance is gained via Caching etc. But there is more to it than this…

          There are some other more interesting architectural concerns at play – for example, it’s likely the list and detail won’t use the same query, or even the same query service. As an example, the Employee List is just a view of employee data delivered via SQL and an internal table, while the details component may need an “Employee” object to work with – or, maybe, the Employee isn’t even instantiated until some behavour is done – eg, if the user just looks at the Employees details, why instantate the object at all? It’s unlikely that a list of Employees to select from will contain all the details that are needed to maintain the Employee – there will be a need to enrich this data, so a visit to the repository will most likely be necessary anyway.

          This is where Separation of Concerns comes in – each component has a specific job to do, and this guides our development, leading us down the path of loosely coupled software. I’ve we look at each component independently we don’t end up with code that may break the list component when we adjust the query for the details component.

          It’s possible that the list and detail component can share the same data verbatum, but most likely it’s implicit coupling that has crept in during the build. This coupling makes change difficult later in the SDLC.

          I guess I drank the cool-aid!

          (0) 
          1. Thomas Jung
            >It’s possible that the list and detail component can share the same data verbatum, but most likely it’s implicit coupling that has crept in during the build.

            I’m going to get us slightly off topic here, but there seems to be a side question of how deeply coupled should UIBBs within the FPM be.  Interestingly enough, I’ve noticed that standard SAP UIBBs are becoming increasingly tightly coupled. It seems like FPM and UIBBs will be tightly coupled with a shared business object layer of some sort and Page Builder and CHIPs will be the solution for more loosely coupled components. CHIP based components within the Page Builder by design are more isloated and already rely upon an eventing model for communication. CHIPs have to be designed to stand on their own and in the future will even have aschronous loading.

            (0) 
            1. Chris Paine
              When you go off topic – that’s when the rest of us sit up and start listening harder!
              Thanks for the heads ups about the design direction.

              I guess for the majority of people not on a 7.02 system, using CHIPs as loosely coupled components is still out of our reach, but FPM UIBBs are available and if we want to build something reusable, it’s still one of our best options (in my opinion).

              Going further off topic – it will be interesting to see how blurred the line becomes between using the FPM and Page Builder – especially when there is CHIP based functionality that users are going to want integrated into FPM applications.
              I’m sure if there isn’t already we will see GUIBB wrappers for CHIPs and CHIP wrappers for UIBBs.

              Thanks for all your comments Thomas – discussion is always more informative than just reading a single viewpoint.

              (0) 
              1. Thomas Jung
                >I’m sure if there isn’t already we will see GUIBB wrappers for CHIPs and CHIP wrappers for UIBBs.

                Actually we are planning a GUIBB for the Page Builder itself.  That is how you will embed CHIPs within FPM, not directly as GUIBB CHIPs.  This is planned for the next enhancement package. 

                Today you can kind of do this already, but it is somewhat cumbersome. You have to create a Freestyle UIBB WD Component.  From within there you can embed the Page Builder as a component usage.

                (0) 
                1. Chris Paine
                  >Actually we are planning a GUIBB for the Page Builder itself. That is how you will embed CHIPs within FPM, not directly as GUIBB CHIPs. This is planned for the next enhancement package.

                  Very interesting – will you be able to wire the embedded CHIPs into any exposed UIBB?

                  And slightly relevant for the blog – will we be able to have more than one instance of this Page Builder GUIBB? it’s not going to be running with a singleton data access is it? 😉

                  (0) 
                  1. Thomas Jung
                    >will you be able to wire the embedded CHIPs into any exposed UIBB?

                    Since this is functionality still in development, I haven’t had a chance to try it out yet.  I’m not really sure what options there will be for passing data and events through the Page Builder GUIBB into the inner CHIPs.  The current CHIP eventing model is design for inter-CHIP communication only.

                    > will we be able to have more than one instance of this Page Builder GUIBB? it’s not going to be running with a singleton data access is it?

                    Yes. From the design documents I do believe this is will be possible.

                    (0) 
                    1. Chris Paine
                      Sounds very cool!

                      I hope someone will present something on this at TechEd! I might have finally got my head around the OVR Floorplan, using CHIPs and how the standard ESS WDA implementation works by that time.

                      Thanks for glimpse into the future!

                      (0) 
          2. Chris Paine
            Kool-aid? Double coffee shot more likely, thanks Al, as always a very informed discussion.

            And thanks for prompting me to write this blog in the first place – I wouldn’t have done it without some of the links you sent me!

            I’m very happy that the discussion is happening – I just hope that we don’t accidentally raise it to a level where no-one else follows. Ala Robbo’s comment in his blog about Inside Track Sydney when we were discussing the merits/otherwise of OData.

            Back to content –  found another corker of a singleton in EhP5 ESS – it transfers data about an employee that has been selected in the leave request/approval app. Full of setter and getter methods, although more RET_blah and SET_blah.
            It occurs to me – especially after reading Thomas’s comment, that really this class should actually be very tightly coupled to the implementation (it’s clear that if you tried to do anything with it other than it’s current use within the standard application it is going to fall over.) I still think it shouldn’t be a singleton, but perhaps because that promises a greater level of autonomy and (overly) loose coupling than the design of the solution allows for.

            A tight coupling to a business object layer (however that is implemented) is not necessarily such a bad thing – it just means we cannot leverage SAP development in custom scenarios.

            But singletons that could be imagined to be used in a non-“Highlander” manner, that’s just sloppy code/architecture. (Ever thought I might want to compare the leave patterns of two employees?) We all do sloppy code (well, perhaps not you and Thomas, but the rest of us anyway) from time to time, the important part is recognizing it as being less than ideal and doing better next time.

            We should all aspire to be architects no? 🙂

            (0) 
        3. Michael Bennett
          Hi Thomas,

          I ask if the comment regarding “If we look to the future of BOL as the underlying business logic and data persistence layer” refers to the BOL layer as implemented in CRM? does this mean a similar concept will be introduced to ERP? If so can I assume the difference would be that WDA would be generated on top of it instead of the equivalent CRM BSP? Even though that the BSP framework seems to now now appear in ERP, at least after Ehp5 is introduced. 

          Thanks & Regards, Michael

          (0) 
          1. Thomas Jung
            Yes I am referring to the same BOL that has its origins in CRM.  BOL is now being used in other components of the Business Suite, but without CRMUI/BSP on top of it. Already in 7.02 we begin extending the FPM framework to allow wiring to the BOL and some special Feeder Class integration for the BOL. This development will continue as a major goal for FPM to be more tightly integrated with the BOL.
            (0) 
    3. Jason Scott

      Hi Thomas… Just looking at your intiial post: “That is how I’ve used it in the past – as a controlled way of having some shared data between loosely coupled components (GUIBB Feeder Classes mostly).”

      >> by using the singleton to share data you no longer have loosely couple components though do you.. Tricky situation and there’s always pro’s and con’s to whichever method you choose.

      (0) 
  2. Graham Robinson
    Whoa – headspin! 🙂

    Great subject and a great discussion – my 2 cents worth is that I am not a huge fan of the Singleton design pattern and use it very rarely.

    (0) 
  3. Timo John
    Thanks for your Blog an the nice drwaings!

    So often during coding you have to decide between bad and evil. I think with singletons  it is pretty much the same.

    1. I agree that it “can be” confusing right in the middle of some code to fetch a new instance with “new inforamtion” for that piece of code => EVIL

    2. Passing an object reference in 25 method calls because you need it in the very last is also bad especially in the case you forgot the second reference => BAD

    I have used some singletons to ensure several modul pool and function groups are working with the same instances in the same user session. This works pretty well AND you save the good old INIT Function module where you change the interface x times.

    I would not agree that singletons are always evil, but there is still outstanding the discussion why not using static methods/attributes? But I think here ABAP leads us the way as they can not be redefined in sub classes.

    Thanks for Blog an discussion!

    (0) 
  4. Lakshminarayanan V
    Glad to see a OOPS (or should I say oops!)discussion in SDN. But sad to see the old singleton pattern being debated. Most of us, atleast outside the SAP world, know when to really use it and when not( or am I overestimating? alteast I know many who clearly understand it). I am with Chris Paine on the usage of singleton. It has its use case (such as the engine class of a server/framework!, holding read only data) but not inside session to pass data. I thought references were well known & trusted. I may be wrong, however this knowledge is from my peers with whom I have worked, they are extermely good at using design patterns on several languages (Java, C# …).

    For more disussion on singleton have a look at this, it is Java oreinted, but for a good programmer language doesnt matter

    http://java.sun.com/developer/technicalArticles/Programming/singletons/

    PS: Sorry if I was caustic in writing this it is because I love SAP but dont like certain aspects of it. Guess we should learn more from the world outside SAP when it comes to programming languages; in my opinion we are a little slow in adopting language standards. Thats why I dont wish to program in ABAP atleast for now 🙂

    (0) 
    1. Chris Paine
      LV, thanks for your points.
      Many of us have been coding ABAP for years and years with very little outside of that (perhaps some Java and the occasional Flex) (and some C to control remote controlled helicopters (but, again, that’s another blog)). Your observation that this discussion is “dated” is a fair one. As I wrote ABAP developers are often seen as behind the times. I would argue that the language itself is not _that_ far behind and has some very powerful features (yet another blog) – so don’t be afraid of coding in ABAP – just be afraid of all the grey haired (or no hair in my case) developers.

      In my research for this blog (please do follow all those links scatter through the text up above, some are quite amusing as well as informative) it became very obvious to me that outside SAP the singleton pattern is given a wide berth. My gripe – and the inspiration for this blog, was that in standard SAP code I am finding this pattern more and more. I just wanted to enlighten people to the received wisdom of other programming areas which have rejected this pattern, and try to explain why.

      Given that the majority of developments I see at client sites tend to start off with the SAP standard approach and “evolve” it. (This isn’t my code by the way 😉 I thought it a good idea to at least give people a heads-up that they should consider if what they are doing is good design.

      I am sure there are valid use cases for the pattern. But I just think that many of the use cases I am seeing in standard SAP code would not meet my criteria for this. But I’m a right picky sod. 😉

      Thanks for giving us a non-ABAP view!

      (0) 
      1. Lakshminarayanan V
        Hi

        Thanks, it is so refreshing to see some one drawing ideas from several languages in the SAP community. This is what will make our community a powerful one and this is what has made the Java & C# communities powerful.

        There was a wonderful coincidence that happened yesterday. After I commented on your blog, I found this: One of my customer had a big issue in his production systems, guess what? End users seeing each others data. Yes the culprit was “bad/evil usage” of global variables. Some of the ABAP programmers had used it to keep user specific data not knowing that shared memory belongs to all 🙂

        You nailed the point: dont be afraid of ABAP but be of people who misuse it. I agree.

        Regards

        LNV

        (0) 
        1. Thomas Jung
          > Yes the culprit was “bad/evil usage” of global variables.

          You do realize that Singletons in ABAP are not global.  Singletons are per user session not at the VM/app server level (as in several other languages).

          (0) 
          1. Lakshminarayanan V
            Yes I realise the singleton/session concept in ABAP. But what I dint get was the need for it. I tried to co-relate with the languages I know well. If I need a single instance of a class inside a user session I dont implement a singleton class at all. Normal check on the the object reference to see if its instantiated or not would do. Then passing of reference is enough.

            For e.g. Many classes inside a user session are instantiated only once but they are not really called singletons. Controlling instance inside a single session is easy.

            The same “instance checking” technique on the VM level would fail due to failure of “syncronisation during multi threading (esp java)”. The singleton pattern (if it can be called a pattern) has its usecase(Engine, address so on) for having one instance per VM in Java or C#.

            May be there is a case to have it session based in ABAP that I dont know/understand.

            (0) 
  5. Michelle Crapo
    Well – I don’t hate singleton.  But like many posted comments here – I rarely use it.   I think like many things, I just have to understand it better.   You have a great point, overuse of anything is bad.   You have to really start to think about what you are using, why you are using it, and does it make sense for future maintenance?  How it is designed is always a great help, but we all have some moments of brain freeze when it comes to a good design.  Plus lack of time in project timelines can drive the wrong technical design.

    I think there are 10,000 ways to do one thing.  It’s just a matter of picking one of them that will work, and makes sense.  However, at some point in the future,  (Maybe the near future) I may look at that code, and think “yuck, who wrote that?  Oh yeah!  It was me.”.  I should have done it a different way.   I have an issue with hard and fast rules as they rarely work.  At least so far for me!  It seems to be a case by case thing.  Which means I gather as much information as possible as often as I can.

    This blog and these comments contain some great information.

    By the way:
    I love the pictures.

    I love the disclaimer.  I may steal it for my blogs:

    “Disclaimer: you shouldn’t listen to anything I say. It’s likely to be wrong, misleading, confusing and unrepresentative, and in no way reflects the opinions of my employer or most sane people. Any perception of a deeper understanding is probably just an optical illusion and you should be very careful in interpreting it otherwise.”

    (0) 
  6. Federico Blarasin
    I’m at work, reading a very interesting and informative blog. It’s good to update my poor ABAP knowledge and try to understand what could be be the better techniques.
    But because of the drawings everyone wondering around my screen thinks I’m just wasting my time on the internet… 🙁
    (0) 
    1. Chris Paine
      Federico,

      Hope I didn’t get you into too much trouble, the drawings were supposed to lighten what is otherwise a quite heavy/deep topic. Glad you appreciated the content and the amazing discussion it has so far generated.

      I will try to be a little more “corporate” the next time I try to add pictures to a blog 😉

      (0) 
  7. Christopher Solomon
    Loved the blog. As my area is often HCM and moreso, ESS/MSS, I feel your pain over the years and anticipated joy with Ehp5…which apparently led to more of the usual “You darn SAP…why are you doing it this way?!?!” discoveries. the blog is great! I equally loved the art….new mascott? And lastly, the comments here are as valuable and informative as the blog itself. You achieved what I think many blogs should…start as the framework for an informed and interesting collaborative discussion (*note: I was seeing how many buzzwords I could use in that last sentence haha). Thanks again!
    (0) 
  8. Jason Scott

    What a great blog and discussion. I especically like the disclaimer! Can’t believe I’ve only just found this a year late. I have similar predicaments about passing data around inside FPM apps and when to use fpm or pagebuilder.

    (and I was just about to use a sngleton to pass data around too.)   😉

    (0) 
  9. Jim Ward

    It’s great to read a blog and discussion about core technical issues.  This is why I use SCN.

    I liked the pictures also.

    (0) 
  10. Adam Krawczyk

    Hi Chris,

    Good to see another point of view about singleton pattern. I was trying to find out why people think “singletons are evil” and I found explanation here, thank you for sharing your thoughts.

    Personally I do not agree with statement that singleton is bad. It is design pattern and like any other – requires situation where it should be used and where it suits best. It may be bad if wrongly used, like for keeping global attributes without control.

    I do not think that below statement is true:

    It is a very, very, rare case that you will only ever want to have one instance

    Let me present simplest example that I use very often – singleton with Data Access Object (DAO). I delegate database queries to separate class, to split logic and database layer. My business logic calls database through DAO object, single point of access that I can easily replace in Unit Tests (only one instance at time). Why I need new separated objects created to query database? One is enough. It would be only waste of memory and time if I created many objects for that.

    Performance is not a problem here, as actually in ABAP each user has own instance of singleton, so it is not shared (I am not talking about shared memory object but standard class with singleton pattern). ABAP singleton works only per user session – I do not need more objects that are designed only for one purpose. In addition all steps are processed in sequence, so there is nothing against keeping utility methods in singleton class, like database queries in single DAO (per business domain of course). Only parallel programming could make it more complex with singleton, but that is another story.

    Singleton is useful when you want to make class with static methods, but you also want to inherit that class for testing purposes (change some methods behavior, you cannot inherit static methods). It is easy to use if class has no state but utility methods – no global variables trap.

    Regards 🙂

    Adam

    (0) 
    1. Chris Paine

      Thanks Adam, glad you got some value out of the blog. 😎

      I think you are right in that there are some use cases for singletons. The DAO is one that I’ve seen used extensively within SAP standard code (especially as it gives the possibility to “trial” data writes before committing them). I’m guessing you even have an interface on your DAO that allows you to mock it for your test cases! However, and I’m playing devil’s advocate here, what if you had a situation where you had two sets of data that you wanted to trial writing/updating to the database to see what the end result would be, and then only choose the one that caused the least number of updates? (quite honestly I struggle to think of why you might want to do this). If the DAO wasn’t singleton, you could potentially do that, as a singleton you can’t. (you’d probably have to have some sort of singleton logic in there anyway to ensure that two instances of the DAO weren’t both allowed to write at the same time 😉 )

      So yes, I can imagine use cases where singleton is useful and I like the test of “no state” as then something being a singleton really shouldn’t matter! 🙂   (although I have seen utility methods that were supposed to be stateless but accidentally picked up state through some coding errors. It’s always a trade off, when you know that you’re not going to be maintaining/updating the code in the future.) But in general I find singletons (as I mention in the blog) being used to transport global variables, and that I think is not good. And I think you agree with me on that one.

      Were only all ABAP programmers as knowledgeable as you appear to be, then I wouldn’t have even needed to write this blog 😉

      Thanks for adding some new life to (what is now) a pretty old blog.

      Cheers!

      Chris

      (0) 

Leave a Reply