Chain of Responsibility Design Pattern - oop

I want to get an intuitive feeling for Chain of Responsibility pattern. I guess a good way to get that would be to learn about some real world examples. Can you guys share such examples?
One of the things about this pattern is that if the chain has many stages, lets say more than 10, implementation gets quite ugly. What do you guys do about that?

I think the Servlet filters are a good example. The chain is built for you and you can decide to call the next one. However the construction/wiring is done for you here.
If the 10 is hairy you can simplify with a builder:
interface ChainElement {
void setNext(ChainElement next);
void doSomething();
}
class ChainBuilder {
private ChainElement first;
private ChainElement current;
public ChainBuilder then(ChainElement next) {
if (current == null) {
first = current = next;
} else {
current.setNext(next);
current = next;
}
return this;
}
public ChainElement get() {
return first;
}
}
Then at construction:
ChainElement chain = new ChainBuilder()
.then(new FirstElement())
.then(new SecondElement())
.then(new ThirdElement())
.get();
chain.doSomething();

Related

Is this a violation of the Single Responsibility Principle?

I'm reading The Pragmatic Programmer, 20th Anniversary Edition and I'm thinking about whether or not this code snippet violates the Single Responsibility Principle:
class Line {
private double length;
private Point start;
private Point end;
public Line(Point start, Point end) {
this.start = start;
this.end = end;
calculateLength();
}
void setStart(Point p) {
this.start = p;
calculateLength();
}
private void calculateLength() {
this.length = start.distanceTo(end);
}
}
In detail, the method setStart() both sets the start position and calculates the updated length. I think this is a violation.
I think calls to calculateLength should be avoided before they are needed. Since it's a private method it can be called when the need arises, not every time the start/end change. This applies to both the setStart and init methods. So the answer is, yes, it is a violation, and not the only one. An example with a single call to the length might not need the calculation method at all:
class Line {
private Point start;
private Point end;
public Line(Point start, Point end) {
this.start = start;
this.end = end;
}
void setStart(Point p) {
this.start = p;
}
double getLength() {
return start.distanceTo(end);
}
}
Would examples with more calls need a pre-calculated value? Unless it's called a million times, maybe not. So the length attribute is also unnecessary.

Is the decorator pattern the correct pattern to be used on this situation

I would like to ask if the decorator pattern suits my needs and is another way to make my software design much better?
Previously I have a device which is always on all the time. On the code below, that is the Device class. Now, to conserve some battery life, I need to turn it off then On again. I created a DeviceWithOnOffDecorator class. I used decorator pattern which I think helped a lot in avoiding modifications on the Device class. But having On and Off on every operation, I feel that the code doesn't conform to DRY principle.
namespace Decorator
{
interface IDevice
{
byte[] GetData();
void SendData();
}
class Device : IDevice
{
public byte[] GetData() {return new byte[] {1,2,3 }; }
public void SendData() {Console.WriteLine("Sending Data"); }
}
// new requirement, the device needs to be turned on and turned off
// after each operation to save some Battery Power
class DeviceWithOnOffDecorator:IDevice
{
IDevice mIdevice;
public DeviceWithOnOffDecorator(IDevice d)
{
this.mIdevice = d;
Off();
}
void Off() { Console.WriteLine("Off");}
void On() { Console.WriteLine("On"); }
public byte[] GetData()
{
On();
var b = mIdevice.GetData();
Off();
return b;
}
public void SendData()
{
On();
mIdevice.SendData();
Off();
}
}
class Program
{
static void Main(string[] args)
{
Device device = new Device();
DeviceWithOnOffDecorator devicewithOnOff = new DeviceWithOnOffDecorator(device);
IDevice iDevice = devicewithOnOff;
var data = iDevice.GetData();
iDevice.SendData();
}
}
}
On this example: I just have two operations only GetData and SendData, but on the actual software there are lots of operations involved and I need to do enclose each operations with On and Off,
void AnotherOperation1()
{
On();
// do all stuffs here
Off();
}
byte AnotherOperation2()
{
On();
byte b;
// do all stuffs here
Off();
return b;
}
I feel that enclosing each function with On and Off is repetitive and is there a way to improve this?
Edit: Also, the original code is in C++. I just wrote it in C# here to be able to show the problem clearer.
Decorator won't suite this purpose, since you are not adding the responsibility dynamically. To me what you need to do is intercept the request and execute on() and off() methods before and after the actual invocation. For that purpose write a Proxy that wraps the underlying instance and do the interception there while leaving your original type as it is.

Looking for best practice to handle conditional logic inside controller actions in asp.net mvc

Currently I am looking for best practice in handling conditions inside the controller actions in asp.net mvc. For example -
public ActionResult Edit(int Id = 0)
{
var Item = _todoListItemsRepository.Find(Id);
**if (Item == null)
return View("NotFound");
if (!Item.IsAuthorized())
return View("NotValidOwner");**
return View("Edit", Item);
}
The above two conditions marked in bold is used in other actions inside the controller. So, in order not to repeat these conditions in all the actions. I have used the below approach.
[HttpGet]
[Authorize]
[ModelStatusActionFilter]
public ActionResult Edit(int Id = 0)
{
var Item = _todoListItemsRepository.Find(Id);
return View("Edit", Item);
}
public class ModelStatusActionFilterAttribute : ActionFilterAttribute
{
private readonly ITodoListItemsRepository _todoListItemsRepository;
public ModelStatusActionFilterAttribute()
: this(new TodoListItemsRepository())
{
}
public ModelStatusActionFilterAttribute(ITodoListItemsRepository todoListItemsRepository)
{
_todoListItemsRepository = todoListItemsRepository;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
var Id = Convert.ToInt32(filterContext.RouteData.Values["Id"]);
var Item = _todoListItemsRepository.Find(Id);
if (Item == null)
{
filterContext.Result = new ViewResult() { ViewName = "NotFound" };
}
else if (!Item.IsAuthorized())
{
filterContext.Result = new ViewResult() { ViewName = "NotValidOwner" };
}
}
catch
{
}
}
}
I am unsure if this is the best practice in handling such scenarios. So, could someone please advise ?
Regards,
Ram
usually you don't use action filter for so-called business logic of your web application - this is what the controllers are for. Action filter are rather for the whole stuff which is external to the actual logic - common case is logging, performance measurement, checking if user is authenticated / authorized (I don't think this is your case, although you call IsAuthorized method on the "Item").
Reducing code is generally good thing but in this case, I don't think putting the logic to action is a good way, because you;ve actually made it a bit unreadable, and unreadable code is in my opinon much worse than repeated code.
Also, specifically in your case, for all valid items you actually call the _todoListItemsRepository.Find() twice (for each valid item), which might be costly if this is some webservice call or db lookup.
If the code is just repeated throughout the actions, make a method out of it like:
private View ValidateItem(Item) {
if (Item == null)
return View("NotFound");
if (!Item.IsAuthorized())
return View("NotValidOwner");
return null; }

Java: change variable from outside while looping through a while queque

I am a Java Beginner and have a little question.
I have got 2 Classes:
the first one is a java formular, the important code is:
#Override
public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
if(key == 17) {
System.out.println("STRG");
if(roboter.running == true) {
roboter.running = false;
}
}
}
the second one is a class (called robot) which main part is the for loop:
public class Roboter {
public boolean running = false;
public void myFunction() {
for(...;...;...) {
for(...;...;...) {
if(!running)
break;
// DO SOMETHING IMPORTANT
}
}
}
Well, this doesn't work. I think it is because I can't change the value of running while my for loop. I have no idea how to slove this problem. Maybe there is an other solution? My aim is to stop the robots myFunction if an user press a key.I hope you can help me
I am sorry for my english, if you don't undestand me I will try to rewrite the question.
The class that handles the keyboard input should run in a separate Thread.

Is there a DRY way to reuse a forloop?

Say I have a slightly complicated for loop, being used in different situations. Is there a way to extract that forloop and still keep the code readable?
For example:
private function bar(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingA();
}
}
}
private function foo(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingB();
}
}
}
The way I would do this/answer the question is to write something like this:
private function loopFunction(callback:Function){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
callback();
}
}
}
private function bar(){
loopFunction(doSomethingA);
}
private function foo(){
loopFunction(doSomethingB);
}
However I find this approach makes the code rather unreadable at times, as you aren't quite sure who is doing what when. Especially if the function passed in comes from another class. Is there a better way to do this?
Another reason why this sollution may not work is if you need to pass in different parameters to the callback function. For example.
private function bar(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingA(arrayA);
}
}
}
private function foo(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingB(i);
}
}
}
As others have pointed out, higher-order functions such as map, fold, and filter provide this kind of functionality. Of course, the precise implementation will vary by language.
Here's a sample in C#:
var foobarList = arrayA.Where(x => x.someVar == foobar).ToList();
foobarList.ForEach(x => doSomethingA());
foobarList.ForEach(x => doSomethingB());
And VB.NET:
Dim foobarList = arrayA.Where(Function(x) x.someVar = foobar).ToList()
foobarList.ForEach(Function(x) doSomethingA())
foobarList.ForEach(Function(x) doSomethingB())
And Javascript:
var foobarList = arrayA.filter(function(x) { return x.someVar == foobar });
foobarList.forEach(function(x) { doSomethingA(); });
foobarList.forEach(function(x) { doSomethingB(); });
You should stop abstracting when it is making your code worse :)
Many languages have higher level constructs built in to deal with common iteration patterns. C++11 has range-based for loops to make iterating over data structures less tedious. Functional languages often have map, fold and filter.