If-Methods 35
if (Character.isLetter(ch) && identCharCount > MIN_IDENT_LEN) {
currentToken.append(ch);
}
if (Character.isWhitespace(char ch) {
tokens.add(new Token(tokenBuffer.toString(), TokenType.IDENT));
currentToken = new StringBuilder();
}
The list of ifs went on and on. Each of them did something distinct and I wanted to break the method down into a set of meaningful sub-methods, but how? The typical pattern to use is to extract the bodies of the if-statements into separate methods, provided you can find good names for them. However, when I imagined what the code would look like after that refactoring, I didn’t really like it. It was still rather wordy:
if (Character.isLetter(ch) && identCharCount > MIN_IDENT_LEN) {
appendToCurrentToken(ch);
}
if (Character.isWhitespace(char ch) {
addToken(currentToken.toString(), TokenType.IDENT);
}
So, I thought that I’d extract each of the if-statements into its own method:
void onIdentChar(char ch) {
if (Character.isLetter(ch)
&& identCharCount > MIN_IDENT_LEN) {
currentToken.append(ch);
}
}
void onWhitespace(char ch) {
if (Character.isWhitespace(char ch) {
tokens.add(new Token(tokenBuffer.toString(),
TokenType.IDENT));
currentToken = new StringBuilder();
}
}
The calling code would certainly look cleaner:
onIdentChar(ch);
onWhitespace(ch);
The only problem is that the method names are a bit of a lie. When we use an “on” prefix we’re writing in event style. We expect that a method like onWhitespace
is called only when we have whitespace. It shouldn’t have to check for it.
I’ve run into this situation before. How do you name a function which consists of a single if-block? The situation crops up frequently in legacy code. You want to break up a large method into several smaller ones and you’re left with a dilemma: do you extract the entire if-statement or just its body?
Here’s another example.
if (replyFlag == RE_SEND) {
...
// code that sends a mail message
...
}
I once asked a friend what he’d name a method for that if-block if we extracted it and he said “sendEmailIfNeeded.” We both flinched and moved on to other things, but let’s think about that name a bit. Part of it talks about intention and part of it talks about implementation. Maybe we can pull the implementation bit out and concentrate on the condition:
if (needResend()) {
...
// code that sends a mail message
...
}
Better. Now, how about extracting it like this?
ifNeedsResend();
It’s sort of like the event style I wrote about earlier. The method is a handler for a condition and the condition is checked in the method. Violation of the Single-Responsiblity Principle? Perhaps, but I do know that I’m looking at some code now that has been clarified by this idiom.
public List<Token> getTokens() {
onStart();
for (int n = 0; n < text.length(); n++) {
char ch = text.charAt(n);
ifLetter(ch);
ifWhitespace(ch);
ifLeftParen(ch);
ifRightParen(ch);
ifVerticalBar(ch);
ifColon(ch);
ifDigit(ch);
}
onFinish();
return tokens;
}
What do you think?
My first reaction was “use a better language for parsing, like lex/yacc, antlr, etc.” ;)
I’ve used the
doFooIfBar()
and related idioms before. Yea, it’s a bit of an SRP violation, but of course the principles are just that, principles, not laws. The clarity you got at the end is worth it, IMHO.One nit; it looks like only one
if
block will get used, so calling all the methods for all chars seems wasteful, or is that premature optimization and hence evil? It would certainly require the finalgetTokens
to be a little more complicated.if
block into a an object. Each object an instance ofRule
implementing two methods:isSatisfied(char ch)
andapply(char ch)
. Stick theRule
objects in a list/array and you’re down a loop.I’m thinking most people would have called it handleWhitespace(ch) w/out a second thought.
I can’t see this as an improvement.
When I see
I can only wonder
How does this make the code clearer?
I agree with Micah here and would like to add some.
I’ve tried programming without using If’s. Just to see how far you can take it. In fact I created a smaller application without any conditionals at all.
It’s not something I can recommend for production but it was a fun and mind expanding experience.
I ended up more than one time with solutions similar to Micah’s suggestion. The rules become very clear that way. The implementation as well.
No SRP-violations and you sort of ‘configure’ in new behavior by putting new Rules into a list/map. Easily testable and very flexible.
How about naming them….
whenLetter(ch);
.... etc. ?
This would imply an action would be taken with the parameter when the condition is met. The ifLetter() does not necessarily connote an action will be taken.
I’m with Jeffery. We do this and we also address Deans desire for short-circuiting and add error handling on top of that by returning a boolean from our handleXxx() routines:
I’m with Micah.
Once you get a collection of objects, then iterating through them is easy. Micah is left with just one ‘if’ and you don’t even have to have that inside the for loop.
Now the for loop is closed to modification of the collection – bingo, OCP!
When programming in Forth, this pattern occurs all the time. I demonstrate this in my “Over The Shoulder” video (see the torrent http://archive.forthworks.com/ots/ots-01.mpg?torrent .
To summarize, Forth programmers can, and I argue should, abstract multi-path branches in a more linguistically natural mechanism. For example:
: character ( ch—) eitherLetter orWhitespace orLeftParen …. lexerException ;
Then, we define each choice as a guard on some action, through careful manipulation of the return stack. For example:
: eitherLetter dup isLetter? if handle-it-here r> drop then ;
Interestingly, reading about how Haskell compilers implements some of its optimizations, the use of “structured returns” isn’t novel—Haskell’s been optimizing like this for some time.
I like ‘handle’ and it works in this case, but I keep thinking about the generic problem of naming a method extracted around an if-block.
The thing about ‘handle’ is illustrated by the other example: we could call the method ‘handleResend’, but I wonder if I’m alone in feeling that it sounds so noncommittal.. sort of like you say “handle this” to an object and it replies “Okeh, whatever..” :-)
Rick: I think your objection is very interesting. Yes, if we say ifWhiteSpace() people are bound to say “then WHAT?” but I wonder.. why don’t we have the same reaction to onWhitespace? Why don’t we say “On whitespace WHAT?” I think it’s just because we’re used to the idiom.
DeanW, Micah: the thing that is missing here is that this is an odd lexer with very weird indentation behavior. Doesn’t feel worth trying to find a tool that will handle it well (no pun intended). Also, a class for each of those methods would be fine, except that they fiddle with the state of the class. Not wanting to break it out yet.
Samuel: Have to check that out. Thanks!
The Rules approach is the best I can think of. But I would improve it with anonymous inline classes (like callbacks).
final char ch = ’ ’; final StringBuilder sb = new StringBuilder();
List rules = new ArrayList(); rules.add(new Rule() { public boolean isSatisfied() { return ; } });
// add several rules ...
for(Rule rule in rules) { if(rule.isSatisfied()) rule.apply(); }
—-
Also, sometimes I just create local boolean variables as conditions:
boolean isLetter = Character.isLetter(ch); // bunch of boolean variables
if (isLetter) { // do something }
if (anoterBooleanVariable) { // do one more thing }
Cheers
The thing I don’t like about handle is that you aren’t really handling anything. I would expect it to be a chain of responsibility, where the first match stops the execution.
I thought also about what Micah mentions of turning each if into an object. But it’s the same thing – we don’t really need to go through each rule (or maybe we do).
I almost want to say something like:
Or:
With the former just deferring the action to somewhere else, and the latter using polymorphism to determine the handler to create. Bonus points for the latter that you could dynamically wire up new handlers and conditions.
What if you had an if-else if-else if…-else situation instead of just the ifs?
I see the chain of responsability here. Still, if that’s not doable, I’d go for handleIfSpace, handleIfLetter, etc. Just the ifSpace, ifLetter leaves me hanging on the implied but unanswered then-part of the if.
I agree with the previous comments that
ifLetter
,ifWhitespace
need an associated action. If letter then what?I like the suggestion of a table-based loop, with predicates (
isLetter
,isWhitespace
) and corresponding actions.As you originally mentioned,
onFoo
is an event idiom: the code raising the event callsonFoo
, and somewhere there is a function that handles the event. In this case you still ask the question “on foo then what?”, but the answer is “do what the listener wants”. Hopefully the listener has a sensibly-named function. I don’t like the handlers for button click events to be called “onClick
”, I prefer “addUser
”, “deleteFile
”, “closeWindow
”, “saveDocument
”. If your framework requires that the button handler is called “onClick
” then a simpleworks wonders for clarity.
This doesn’t work with your
ifLetter
scheme since the whole point of these functions as you’ve got them is to perform the test and the action.handleLetter
works a bit better, since it says “handle the case that this is a letter”. I’ve usedhandleFoo
before, but “handle” is a bit generic.“Why don’t we say “On whitespace WHAT?” I think it’s just because we’re used to the idiom.”
I don’t think this question is asked much, because it’s usually a framework that’s calling onEvent not your “own” code. So when people read though, they may see onEvent registered somewhere, and then read declarative code saying onEvent { do this; do that; }
I liked Micah’s approach, but I think I’d prefer using a list of tuples with a boolean predicate and an action:
or something similar. The “parse” function would, for each character in the text, simply iterate over all tuples, and whenever a predicate is true, perform the associated action.
This solution allows you to capture both the intent of the predicate, as well as the intent of the action, and avoids coupling the two unnecessarily. I think it’s this coupling between predicate and action that is the source of all the unease with the proposed solutions so far.
Michael, you were heading towards an event style notation, but shied away from it. What’s wrong with an event notation? You just needed to separate the event from the action, as in the above example.
Ultimately, I suspect a Finite State Machine would be one of the most appropriate representations of the intent of this part of the code. You could use the example above as an intermediate step to refactor towards a full FSM implementation, by adding states and state transitions to the rules later. Of course, this application might not require a full FSM, but I can’t judge that based on the information given.
I would agree with Cory seems chain o’ reponsibility would apply here. My only concern would be introducing the complexities of a pattern in a stable area of the code.
Rick is perfectly right. The method doesn’t “if” but it generates a token from character if the character matches a certain pattern so I’d rather opt for:
The general problem here is that the methods do two distinct things so the right name would be something like “scanLetterIfItsALetter” which is rather strange. In the long run, I’d go with Micah. You can extend the isSatisfied method with a context parameter that propagates state and/or apply weighted rules to make the mechanism smarter.
I think it’s a language flaw. If the language supports pattern matching, then there will be a beautiful result.
now supplying the latest white iphone 4 conversion kit to make your iphone 4 different from others. As a fashion fans like you will surely love it.
I agree with Micah here and would like to add some.
I’ve tried programming without using If’s. Just to see how far you can take it. In fact I created a smaller application without any conditionals at all.accounting services
useful informative article. Thanks
internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.
Many this the industry superb e-commerce, over the internet wanting, precisely what MBT footwear? I’ t convinced you choosed conduct. Plus the release with e-commerce team obtained a on-line shopping for. Always be with all this mbt lami boots and shoes plus boot footwear and even lots of people over the internet hunting Masai boots and shoes plus boot footwear could be a wonderful liking.Christian Louboutin Rouges chaud Make sure you execute could be a site into the stay, Christian Louboutin Bottessports book odds your person’ vertisements working out and also journal to look for and also MBT boots low-priced and also seek MBT boots out there. North Face Apex Bionic Kvinder JakkerType in getting some keyword phrase, similar to an example is definitely the following MBT Masai boots and shoes plus boot footwear ideal for lists pertaining to recommendations boots and shoes plus boot footwear and also web-site may might seem when while in front of any one, and then motivateNorth Face Denali Jakker Kvinder hoodie, to illustrate, a person’s sensible Web pages should do,
canada goose will likely be MBT footwear providing could great final decision. Then you could well anticipation any one not any specs of your webpage acceptable this mbt baridi boots and shoes plus boot footwear in the united kindom normally often be subject material, you will get you wantcanada goose outlet.
Ugg Italia , Step un paio di: Sentirsi quel contatto-(da sinistra di un individuo) Una volta sentito il contatto dal difensore pendente a sinistra, lato posteriore, mentre i dribbling di basket particolare utilizzando la tua offerta giusta, si renderà il vostro riposizionare: Spin, semplicemente piantando insieme spingendo utilizzando il piede sinistro ogni volta che rapidamente perno con l’arto inferiore destro, e modificare i dribbling a tutti i tuoi offer.As lasciato un perno singolo, mettere il ginocchio destro in modo che la parte posteriore sulla destra tricipiti / bicipiti può semplicemente un massaggio poco dal retro del difensore, che contribuirà a creare spazio a Voi relativi in più, il difensore, poi terminare la “rotazione” intorno a tutte le vostre part.As destra si lascia il backspin, l’avversario al momento essere l’alimentazione voi come si sta cercando proprio all’interno del baskeball canestro. (da destra) Se si potrebbe essere stato un dribbling di basket fino al lato più adatto, la cottura con il palmo della mano sinistra, attendere significato per contatto attraverso il difensore sul proprio terzino destro-side.While si sente un contatto, spin semplicemente piantando insieme spingendo utilizzando il piede destro ogni volta che rapidamente perno con l’arto inferiore sinistro, e modificare i dribbling a tutte le vostre destra offer.As uno spin individuale, messo il ginocchio sinistro in modo la schiena sul lato sinistro tricipiti / bicipiti può semplicemente un massaggio poco dal retro del difensore, che contribuirà a creare spazio a Voi relativi in più, il difensore, poi andare a girare intorno per il bordo sinistro.
o jordan release dates 2011 take care of Chen Wan-sheng of the burden falls on the shoulders of the old jordan 8 father. jordan 14 jordan retro 7 Manage space jam jordans outs…
This article is GREAT it can be EXCELLENT JOB and what a great tool!
This is excellent postCheap Beats By Dre Dr Dre Headphones Cheap Monster Beats Headphones Beats By Dr Dre Cheap Monster Dr Dre Beats Headphones Monster Beats Pro Headphones Cheap Monster Beats Solo Monster Dr Dre Beats Solo HD Headphones Justbeats Solo Headphones Monster Beats By Dr Dre In Ear Headphones beats by dre beats by dre australia beats by dre outlet dre beats Beats By Dre Studio Headphones Discount Beats By Dr Dre Pro Discount Beats By Dre Solo Discount Beats By Dre Solo HD Monster Beats By Dre Discount Beats By Dre Beats By Dre Headphones dr dre headphones beats by dre uk Discount Beats by dr dre pro Dicount Beats By Dr Dre Studio Beats By Dr Dre Solo Beats By Dr Dre Solo HD headphones Dr Dre Justbeats headphones beats by dre headphones beats by dre canada beats headphones dr dre canada outlet Monster Beats by Dr Dre headphones Beats By Dr Dre Pro heaphones Beats By Dr Dre Studio headphones Beats By Dr Dre solo headphones Monster Beats By Dr Dre solo HD Monster Beats by Dr Dre headphones Auriculares Beats Beats by Dre Dr Dre Beats Auriculares Monster Beats Monster Beats by Dr Dre Studio Monster Beats by Dr Dre Pro Monster Beats by Dr Dre Solo Monster Beats by Dr Dre Solo HD Beats By Dr Dre Dr Dre Kopfhörer Beats By Dre Kopfhörer Monster Beats Kopfhörer justbeats Kopfhörer beats studio Kopfhörer beats pro Kopfhörer Monster Beats By Dr Dre pro Kopfhörer monster beats solo Monster Beats By Dr Dre solo Kopfhörer monster beats solo hd beats solo hd Kopfhörer Beats By Dre Cheap Monster Beats Beats Headphones Cheap Dre Beats Dr Dre Outlet Monster Beats By Dre Studio Monster Beats By Dre Pro Monster Beats By Dre Solo Monster Beats By Dr Dre Solo HD Beats By Dr Dre Beats By Dre Australia Cheap Beats By Dre Beats By Dre Store Cheap Beats By Dr Dre Studio Cheap Beats By Dr Dre Pro Cheap Beats By Dr Dre Solo Cheap Beats By Dr Dre Solo HD Cheap Dr Dre Justbeats Headphones Beats By Dre Australia Beats By Dr Dre Dr Dre Beats Dr Dre Headphones Beats By Dr Dre Studio Beats By Dr Dre Pro Beats By Dr Dre Sol Beats By Dr Dre Solo HD Beats By Dr Dre Headphones casque beats by dre casque dr dre monster beats by dr dre casque monster beats beats by dre france Casque Beats by dre Studio Casque Beats by dr dre Pro casque beats by dr dre solo Beats by dr dre Solo HD Casque Dr Dre Justbeats Beats By Dr Dre Beats By Dre Canad Cheap Beats By Dre Beats By Dre Headphones Cheap Beats By Dre Stduio Cheap Beats By Dre Pro Cheap Beats By Dre Solo Cheap Beats By Dre Solo HD Auriculares beats by dre Auriculares monster beats by dre Auriculares dr dre beats dre Beats by Dr Dre Pro Beats by Dr Dre Solo Beats by Dr Dre Solo HD Monster Beats Studio beats by dre casque casque dre dre beats sortie casque monster beats casque beats studio dr dre Casque Beats by dre Pro Casque Beats by dre Solo Casque Beats Solo HD Casque Dr Dre Justbeats Casque Beats By Dre Casque Dr Dre écouteurs Beats écouteurs Beats By Dre Beats By Dr Dre beats pro casqus dr dre pro casque beats solo HD casqus dr dre solo HD casqus beats studio casque dr dre studio casque Monster beats Monster beats dre Beats by dre australia beats by dre dr dre headphones Monster beats by dre studio Monster beats by dre pro Monster beats by dre solo headphones Monster beats by dre solo hd Beats By Dre headphones Beats By Dre Australia Beats By Dre Studio dr dre beats headphones beats studio beats pro beats solo hd pro headphones music Official store Monster Beats By Dre Pro Monster Beats By Dre solo Monster Beats By Dre solo HD Justbeats Headphones Signature Monster Beats By Dr Dre Studio
Louis Vuitton (Louis Vuitton), il est l’un des louis vuitton sacs plus remarquables de l’histoire fran?aise gourou de conception en cuir, a ouvert la boutique première valise en leur nom propre à Paris en 1854. louis vuitton pas cher Un siècle plus tard, Louis Vuitton est devenu l’un des meilleurs marques de bagages et de maroquinerie domaine, et est devenu un symbole de vuitton sac 2012 la haute société. Aujourd’hui, Louis Vuitton, la marque ne se limite pas à la conception et la vente d’articles de maroquinerie haut de gamme et des bagages, mais à s’impliquer dans le domaine de la mode, accessoires, sac louis vuitton chaussures, sacs, bijoux, montres, des médias, de vin et d’autres méga-tendances des indicateurs. De LV valise début et maintenant chaque année, sacs louis vuitton bagages le stade T à Paris, l’évolution constante LV défilé de mode, LV (Louis Vuitton) a pu avoir été debout dans l’industrie de la mode internationale, la position supérieure, la fierté dans le classement de la liste des marques de luxe dans son propre ADN de la marque unique.
Australia Beats By Dre Studio dr dre beats headphones beats studio beats pro beats solo hd pro headphones music Official store Monster Beats By Dre Pro
The monster beats headphons are semi-open in design
However, the headphone industry is greeted with far less unanimity. dr dre headphons targeted toward audiophiles are often considered weak or thin sounding by the general consumer. Despite a price tag worth more than 5 times the amount of the monster beats dre studio headphones they are used to, the consumer may not be inclined to agree with the more expensive headphone’s proclaimed superiority. In order to please both the consumer and audiophile demographics, headphone companies must either exhaust their R&D departments and often come up short, discover some magic voodoo potion, or simply give up! I know for certain that in the case of the Beats By Dr Dre Solo, V-Moda did not subscribe to the latter.The beats headphons headphones themselves are semi-open in design and allow sound to leak into the outside. For this reason, the Beats By Dr Dre may not be the ideal headphone choice for some listening environments.
Some may inquire as to why Beyerdynamic would choose to create an open-back headphone. The reason as specified by many manufacturers that design open-back New Style Beats By Dr Dre headphones is that it is easie.House of Marley has consistently surprised us with their uniquely designed monster beats dre studio headphones. The House of Marley Trenchtown Rock Destiny is their latest offering, a noise cancelling headphone which competes with many similarly-priced noise cancelling monster beats dre studio headphones and ‘rapper monster beats dre studio headphones’. Overall I felt that the Destiny is a good choice for a listener who likes great style, active noise cancellation and up-front forward bass.The noise-cancelling ability of these cheap beats by dre studio headphones is pretty good, however there may be better options at this price point if Active Noise Cancellation is more important to you than the aesthetics of the cans. I do however have two quibbles with regard to the way the feature is implemented. One is that in order to hear music, you must use the noise cancelling feature.
This means that your batteries better not run out, or you should be prepared with extra batteries (two triple A). While it is not uncommon for noise cancelling Beats By Dr Dre Pro to require the noise cancelling feature to be activated in order to hear music, several new models are coming out that will still output sound when batteries are dead, or noise cancelling is in passive mode. The second is the louder than average thump sound which one hears when switching the noise cancellation on while the monster beats dre studio headphones are on the head.Listening to Maroon Five’s “Moves Like Jagger” I was very impressed with the immersive quality this headphone had. If you want a headphone that makes you dance, these Destiny monster beats dre studio headphones may very well be your destiny.With regard to accessories, beats dre studio do not offer much. The cable itself is built into the headphone (Y-split style) and is not user replaceable. The cable itself is very sturdy, extra thick and may benefit from a Beats By Dr Dre Solo headphone extension cable if one is going to be more than 4 feet from their source.
dr dre headphons,beats headphons,New Style Beats By Dr Dre,cheap beats by dre studio,Beats By Dr Dre Pro,Beats By Dr Dre Solo
office 2010 ist eine Office-Suite für Microsoft Windows und ist der Nachfolger von Office 2007.
Then an agency appeared to be inspired to build a video clip boasting the shoe with the NFL’s Extremely Dish. No trouble. Market associations baseball caps also brought about the NFL’s Buccaneers to use Mutt within February as the Bucs’ marketing and advertising agency of document, due to the task of creating your team’s graphic locally.
I think although bel canto, sex, delicious are different things, and touch is also different sense organs, but having a bit is with. cheap dr dre beats, beats by dre outlet.
Can bring cheerful, good psychological feeling and enjoy. beats outlet. In some cases, the aesthetic feeling of strong impact, dr dre beats outlet,can even make the person produces excited, thriller, climax…... Of course,dre beats outlet, most of the time, we just need the quietly enjoy that brings the aesthetic feeling heart cheerful. monster beats outlet.This mind the sense of joy and satisfaction, I think is that the bel canto, sex, delicious this series of several things up. beats outlet, dr dre beats cheap.
For example, now I am through Italy CC Admonitor horn appreciate a beautiful art trio of performance Clara schumann’s piano trio works monster beats outlet(schumann wife works, hardly one to hear). dr dre beats outlet,Wonderful piano, violin, cello acoustic sound, so that I vaguely recall today enjoy lunch-the "top" near wujiaochang Thai restaurant food. beats by dre outlet, beats outlet.Delicious and bel canto, also bring me a cheerful, enjoy, beats for cheap,satisfaction, although only meet different sense organs. dre beats for cheap, cheap beats, cheap beats by dre.