开发者

Change Code Behaviour depending on Context

I have a class that can be called either from a GUI or form a Non-Graphical Environment (Batch mode)

What is the most convenient an best practice way to "tell" the GUI-related parts of the code NOT to execute when executed in batch mode.

I think of something like

    public MyMethod()
    {            
        [@TAG: DOTHIS_ONLY_IF_GUIMODE]
        ShowPanels();
        ....
    }

And the GUI_MODE_ACTIVATED would be set to true or false on runtime somewhere, depending on where the program is called from

I want to avoid the ugly tracing if/else stuff scattered all over my code.

My little thumb tells me AOP is the way to go (but if I manage to find a simpler alternative I'll go for it)

So, what is the SIMPLEST and most straightforward way to do this ?

Update: As most contributors pointed out, separating GUI Code from Business code is a rule of thumb, But I am still interested in knowing ways to do this even if NO GUI is involved (ie, two different BATCH modes for two diff开发者_JAVA百科erent environments, for example)


I think your best bet is to take the GUI-specific code out of the class and implement events triggered at key times in the class's processing. When called by the GUI, the GUI code subscribes to those events and 'does the right thing.' The batch-code ignores the events and all is well.


What is the most convenient an best practice way to "tell" the GUI-related parts of the code NOT to execute when executed in batch mode.

This is why you separate business logic concerns from UI concerns.

So, what is the SIMPLEST and most straightforward way to do this ?

Separate business logic concerns from UI concerns.


The simplest and most straightforward way is to use an if statement.

A less straightforward, but more structured, way would be to make the ShowPanels method abstract, then derive two classes: one for GUI mode and one for batch mode.


Add Aspects to Object Using Dynamic Decorator .

Your classs should concern only business logic not presentation (GUI or Batch, etc.). At runtime, you can attach presentation (GUI or non-GUI) code to objects of the class as needed.

No need to have the ugly attribute code in your class definition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜