Now, say that generateY() is expensive, we can save time in client.func(A) when its parameter "a" is of type 2 by not generate Y.
I will now try to split the logic in A.foo() into 2 separate classes with a common abstract subclass:
But now I am stuck, I don't know how I should modify client class to use these two classes without break some abstraction between class A and class Client because class Client should not have access to a.type and class A should invoke Client.GenerateY()
How do I refactor this piece of code cleanly?
Joined: Aug 25, 2006
P.S. I realize that lazy evaluation will get the performance improvement I needed, but I am looking for some structural improvement.
Start with renaming. Because names like x and y don't say anything. Methods should begin with a lowercase character.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Joined: Aug 25, 2006
Wouter Oet wrote:Start with renaming. Because names like x and y don't say anything. Methods should begin with a lowercase character.
Sorry if I wasn't clear enough but they are named like this to present a generic problem. This was not what the code actually look like.
Also sorry about the method name because I was looking at a piece of C sharp code and forgot to change the coding convention back.
There, I have changed all my function names to lower case but I am not able to change x and y because of my earlier point.
Let's not make this into a debate of coding conventions. I am simply asking if there is a pattern of solving this problem.
It's impossible to provide specific recommendations when we aren't told what the code is supposed to be doing. It's even worse when we're presented with methods named foo. So we really have no idea what the problem with that code is, except for a vague comment about something being "expensive".
Bottom line here - you don't want to generate Y unless you know that you need it.
The problem right now - Y is generated in Client class, but class A the one who knows should it be use or not.
so solutions that should work without knowing details of what code does and changing any dependencies are the following, for anything more elegant you have to give more insight.
1. Give class C a knowledge is Y needed or not. For example you can add "isYRequird" method to A and pass null if it is not required.
2. Generate X and Y inside A class. So you will have something like: