Is this a violation of the Single Responsibility Principle? - oop

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.

Related

Chain of Responsibility Design Pattern

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();

Can a class that tracks time be immutable?

Let's say I have a simple class in Java that stores a time stamp:
public final class Timestamp {
private final long value;
public Timestamp(final long value) {
this.value = value;
}
public long getValue() {
return value;
}
}
That's immutable. But what if instead of getValue() I write a method called getProgress()?
public final class Timestamp {
private final long value;
public Timestamp(final long value) {
this.value = value;
}
public float getProgress() {
return (SomeExternalPlace.getTimestamp() - value) / SomeFloatConstant;
}
}
The object's state never changes, but the value from getProgress() does change over time.
Is the latter class considered immutable? Why or why not?
It is immutable, because its state (the value field) cannot change once an instance of Timestamp has been created. The timestamp represents a certain point in time, and that cannot be changed.
Data returned from the methods doesn't necessarily need to be always the same.
Additionally, Timestamp exhibits all the properties you'd expect from an immutable object (e.g., thread-safety).
Here's another "weird" example of immutability:
class LazyList<T>
{
private readonly T _head;
private LazyList<T> _tail;
private readonly Func<LazyList<T>> _tailDelegate;
private bool _created;
public LazyList(T head, Func<LazyList<T>> tailDelegate)
{
_head = head;
_tailDelegate = tailDelegate;
_created = false;
}
public T GetHead()
{
return _head;
}
public LazyList<T> GetTail()
{
if(! _created)
{
_tail = _tailDelegate();
_created = true;
}
return _tail;
}
}
As you can see, the _tail isn't really immutable - it's null when LazyList<T> is instantiated, and is assigned only when the client calls GetTail(). But that really doesn't matter. Once the tail is created, it doesn't change; and before that, the tail still "exists", it just hasn't been realized yet.
This is actually how Scala's immutable Streams are implemented.

What are "watches" in IntelliJ and how to use them?

When I debug an app, in the debug tool window there is a Watches window. I have read this manual over and over, but cannot find any practicle usage of Watches.
Somehow, I think this is a cool and useful tool and I lack from not using it.
Can someone explain when should I use it and give a few samples? Ideally, the description will be bound to a concrete (imaginary) situation so that I better apply it in my work.
This section allows you to define expressions which you'd like to see how they evolve/change with every step of your debug process, without manually inspecting all the available objects and their properties. Let's take the following simple sample which intentionally throws a NullPointerException (NPE):
public class WatchSample {
static class Student {
public static final int CREDITS_REQUIRED_FOR_GRADUATION = 10;
private String name;
private Integer credits;
public Student(String name, Integer credits) {
this.name = name;
this.credits = credits;
}
String getName() {
return name;
}
public boolean hasGraduated() {
return credits >= CREDITS_REQUIRED_FOR_GRADUATION;
}
public Integer getCredits() {
return credits;
}
}
public static void main(String[] args) throws Exception {
List<Student> students = simulateReadingFromDB();
for (Student student : students) {
if (student.hasGraduated()) {
System.out.println("Student [" + student.getName() + "] has graduated with [" + student.getCredits() + "] credits");
}
}
}
private static List<Student> simulateReadingFromDB() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("S1", 15));
students.add(new Student("S2", null)); // <- simulate some mistake
students.add(new Student("S3", 10));
return students;
}
}
At some point in time you may wonder how come you get a NPE and what needs fixing. So just set a breakpoint, add a few watches and carefully step through the lines. Eventually you'll end up with the troublemaker in sight:
Of course this is a basic example and should be taken as such. Within a regular app you'll probably have more complex scenarios and expressions you'd like to inspect, and this will make more sense, for example: if (((position > 0 && position < MAX) || (position < 0 && position > MIN) && (players(currentPlayer).isNotDead() && move.isAllowed()) && time.notUp())..... In this case you can evaluate the sub-expressions to see which one returns false
**Note**: You could also make the breakpoint conditional so that the program will pause only when that specific event occurs:

Refactoring code using Strategy Pattern

I have a GiftCouponPayment class. It has a business strategy logic which can change frequently - GetCouponValue(). At present the logic is “The coupon value should be considered as zero when the Coupon Number is less than 2000”. In a future business strategy it may change as “The coupon value should be considered as zero when the Coupon Issued Date is less than 1/1/2000”. It can change to any such strategies based on the managing department of the company.
How can we refactor the GiftCouponPayment class using Strategy pattern so that the class need not be changed when the strategy for GetCouponValue method?
UPDATE: After analyzing the responsibilities, I feel, "GiftCoupon" will be a better name for "GiftCouponPayment" class.
C# CODE
public int GetCouponValue()
{
int effectiveValue = -1;
if (CouponNumber < 2000)
{
effectiveValue = 0;
}
else
{
effectiveValue = CouponValue;
}
return effectiveValue;
}
READING
Strategy Pattern - multiple return types/values
GiftCouponPayment class should pass GiftCoupon to different strategy classes. So your strategy interface (CouponValueStrategy) should contain a method:
int getCouponValue(GiftCoupon giftCoupon)
Since each Concrete strategy implementing CouponValueStrategy has access to GiftCoupon, each can implement an algorithm based on Coupon number or Coupon date etc.
You can inject a "coupon value policy" into the coupon object itself and call upon it to compute the coupon value. In such cases, it is acceptable to pass this into the policy so that the policy can ask the coupon for its required attributes (such as coupon number):
public interface ICouponValuePolicy
{
int ComputeCouponValue(GiftCouponPayment couponPayment);
}
public class GiftCouponPayment
{
public ICouponValuePolicy CouponValuePolicy {
get;
set;
}
public int GetCouponValue()
{
return CouponValuePolicy.ComputeCouponValue(this);
}
}
Also, it seems like your GiftCouponPayment is really responsible for two things (the payment and the gift coupon). It might make sense to extract a GiftCoupon class that contains CouponNumber, CouponValue and GetCouponValue(), and refer to this from the GiftCouponPayment.
When your business - logic changes, it's quite natural that your code will have to change as well.
You could perhaps opt to move the expiration-detection logic into a specification class:
public class CouponIsExpiredBasedOnNumber : ICouponIsExpiredSpecification
{
public bool IsExpired( Coupon c )
{
if( c.CouponNumber < 2000 )
return true;
else
return false;
}
}
public class CouponIsExpiredBasedOnDate : ICouponIsExpiredSpecification
{
public readonly DateTime expirationDate = new DateTime (2000, 1, 1);
public bool IsExpired( Coupon c )
{
if( c.Date < expirationDate )
return true;
else
return false;
}
}
public class Coupon
{
public int GetCouponValue()
{
ICouponIsExpiredSpecification expirationRule = GetExpirationRule();
if( expirationRule.IsExpired(this) )
return 0;
else
return this.Value;
}
}
The question you should ask yourself: is it necessary to make it this complex right now ? Can't you make it as simple as possible to satisfy current needs, and refactor it later, when the expiration-rule indeed changes ?
The behavior that you wish to be dynamic is the coupon calculation - which can dependent on any number of things: coupon date, coupon number, etc. I think that a provider pattern would be more appropriate, to inject a service class which calculates the coupon value.
The essence of this is moving the business logic outside of the GiftCouponPayment class, and using a class I'll call "CouponCalculator" to encapsulate the business logic. This class uses an interface.
interface ICouponCalculator
{
int Calculate (GiftCouponPayment payment);
}
public class CouponCalculator : ICouponCalculator
{
public int Calculate (GiftCouponPayment payment)
{
if (payment.CouponNumber < 2000)
{
return 0;
}
else
{
return payment.CouponValue;
}
}
}
Now that you have this interface and class, add a property to the GiftCouponPayment class, then modify your original GetCouponValue() method:
public class GiftCouponPayment
{
public int CouponNumber;
public int CouponValue;
public ICouponCalculator Calculator { get; set; }
public int GetCouponValue()
{
return Calculator.Calculate(this);
}
}
When you construct the GiftCouponPayment class, you will assign the Calculator property:
var payment = new GiftCouponPayment() { Calculator = new CouponCalculator(); }
var val = payment.GetCouponValue(); // uses CouponCalculator class to get value
If this seems like a lot of work just to move the calculation logic outside of the GiftCouponPayment class, well, it is! But if this is your requirement, it does provide several things:
1. You won't need to change the GiftCouponPayment class to adjust the calculation logic.
2. You could create additional classes that implement ICalculator, and a factory pattern to decide which class to inject into GiftCouponPayment when it is constructed. This speaks more to your original desire for a "strategy" pattern - as this would be useful if the logic becomes very complex.

How can I use Lucene's PriorityQueue when I don't know the max size at create time?

I built a custom collector for Lucene.Net, but I can't figure out how to order (or page) the results. Everytime Collect gets called, I can add the result to an internal PriorityQueue, which I understand is the correct way to do this.
I extended the PriorityQueue, but it requires a size parameter on creation. You have to call Initialize in the constructor and pass in the max size.
However, in a collector, the searcher just calls Collect when it gets a new result, so I don't know how many results I have when I create the PriorityQueue. Based on this, I can't figure out how to make the PriorityQueue work.
I realize I'm probably missing something simple here...
PriorityQueue is not SortedList or SortedDictionary.
It is a kind of sorting implementation where it returns the top M results(your PriorityQueue's size) of N elements. You can add with InsertWithOverflow as many items as you want, but it will only hold only the top M elements.
Suppose your search resulted in 1000000 hits. Would you return all of the results to user?
A better way would be to return the top 10 elements to the user(using PriorityQueue(10)) and
if the user requests for the next 10 result, you can make a new search with PriorityQueue(20) and return the next 10 elements and so on.
This is the trick most search engines like google uses.
Everytime Commit gets called, I can add the result to an internal PriorityQueue.
I can not undestand the relationship between Commit and search, Therefore I will append a sample usage of PriorityQueue:
public class CustomQueue : Lucene.Net.Util.PriorityQueue<Document>
{
public CustomQueue(int maxSize): base()
{
Initialize(maxSize);
}
public override bool LessThan(Document a, Document b)
{
//a.GetField("field1")
//b.GetField("field2");
return //compare a & b
}
}
public class MyCollector : Lucene.Net.Search.Collector
{
CustomQueue _queue = null;
IndexReader _currentReader;
public MyCollector(int maxSize)
{
_queue = new CustomQueue(maxSize);
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
public override void Collect(int doc)
{
_queue.InsertWithOverflow(_currentReader.Document(doc));
}
public override void SetNextReader(IndexReader reader, int docBase)
{
_currentReader = reader;
}
public override void SetScorer(Scorer scorer)
{
}
}
searcher.Search(query,new MyCollector(10)) //First page.
searcher.Search(query,new MyCollector(20)) //2nd page.
searcher.Search(query,new MyCollector(30)) //3rd page.
EDIT for #nokturnal
public class MyPriorityQueue<TObj, TComp> : Lucene.Net.Util.PriorityQueue<TObj>
where TComp : IComparable<TComp>
{
Func<TObj, TComp> _KeySelector;
public MyPriorityQueue(int size, Func<TObj, TComp> keySelector) : base()
{
_KeySelector = keySelector;
Initialize(size);
}
public override bool LessThan(TObj a, TObj b)
{
return _KeySelector(a).CompareTo(_KeySelector(b)) < 0;
}
public IEnumerable<TObj> Items
{
get
{
int size = Size();
for (int i = 0; i < size; i++)
yield return Pop();
}
}
}
var pq = new MyPriorityQueue<Document, string>(3, doc => doc.GetField("SomeField").StringValue);
foreach (var item in pq.Items)
{
}
The reason Lucene's Priority Queue is size limited is because it uses a fixed size implementation that is very fast.
Think about what is the reasonable maximum number of results to get back at a time and use that number, the "waste" for when the results are few is not that bad for the benefit it gains.
On the other hand, if you have such a huge number of results that you cannot hold them, then how are you going to be serving/displaying them? Keep in mind that this is for "top" hits so as you iterate through the results you will be hitting less and less relevant ones anyway.