Hacker Newsnew | past | comments | ask | show | jobs | submit | chamilto's commentslogin

> When you're designing a function, you may be tempted to add a flag. Don't do this. Here, let me show you an example: Suppose you have a messaging system and you have a function that returns all the messages to an user, called getUserMessages. But there is a case where you need to return a summary of each message (say, the first paragraph) or the full message. So you add a flag/Boolean parameter called retrieveFullMessage. Again, don't do that.'Cause anyone reading your code will see getUserMessage(userId, true) and wonder what the heck that true means.

What about in languages with named parameters? I think keyword arguments solve this issue pretty well.


Another option is to use an enum, so it looks like getUserMessage(userId, MessageResultOption.FullMeesage). Even if there's only two options, it's more readable than a boolean.

I'd question this specific case in a different way, though: summary vs detail sounds like different object types, which means different return types and so there should be two different methods (eg: getUserMessageSummaries(userId) and getUserMessageDetail(userId) ). It's perhaps a bit more work up front, but when consuming this you don't end up with a bunch of properties that may or may not be null depending on how you called this (instead, they're just not there on the summary response), and in a typed language it will simply fail to compile (making your mistake very obvious).


Similarly: over time almost every boolean becomes an enum. I'm a bit surprised the article doesn't mention enum parameters as a possible alternative to booleans.

In this example the call-site could instead look like `getUserMessages(userId, MessageStyle.SUMMARY)`. Naming the enum is always harder than naming the boolean but that's kinda the point.


Perhaps another way to word it is: "Adding a boolean parameter is a strong indication that you're about to cross the single-responsibility threshold. Try to think of different ways to structure the code in which the bool isn't needed."


This one's definitely a weakness I still have. I read that and thought "yeah, I do this in a lot of places and often end up regretting it."

I think named parameters don't actually help, because the underlying problem with the boolean (aside from the mystery about what it means when looking at code calling it) is that it implies a potential separate "mode" of operation for the function. That the single function might actually serve two different purposes. It doesn't always imply that I imagine, but it's pretty likely.

I'm guilty of this in my code, and I know that my code quality has suffered for it - for some reason, the way he put it in this article gave me a moment of introspection there, and it's something I'm going to try and take away from it and improve my own code with in the future.


However, using multiple names can create a combinatorial explosion. If you have 3 Boolean parameters, then you need up to 8 functions. I think named parameters are probably a better option.


Only if you really need all combinations of those options. The flip-side is true as well - multiple booleans creates a combinatorial explosion of corner cases that you have to test for. I have definitely been guilty of adding flags to functions that really should have been separate functions, and being bit by permutations that were not tested. Some of which we couldn't even decide what the proper behavior ought to be when we went back to fix the function.


Wouldn't those same combos need to be tested regardless of which interface technique is used? If there are 8 variations then there are 8 variations regardless of the name-centric or flag-centric approach.

Note that sometimes I add an optional boolean parameter to avoid breaking existing method calls. The default of the new optional flag is the original behavior. It's a case being backward compatible versus changing more code in order to fit a revamped interface.


I agree. The only problem I see with “boolfixes” (as an old colleague called them) is the call site readability issue that the author pointed out. If you have the purpose of the bool right there at the call site, as with mandatory keyword arguments in Python, that issue goes away.


Everyone that works in project A uses properly configured IDE, so when you take a look at code you'll actually see something like that: `getClient(liveMode: true)` instead of just `getClient(true)`.

Is there really a point in creating Enum or writing more complex internal logic if you use proper IDE?

Only benefit I can see is doing CR's via Github like system - but still, I do not believe in CR without actually pulling, viewing, and testing code on own computer.


Even as a person who adores my properly-configured IDE with that feature, I vehemently support the idea of IDE-independence for even internal projects. Requiring developers to use a particular IDE evokes the dark days of Java projects based on Eclipse's build system. Developers are happy and productive with their pet tools, and discontented and resentful when forced to use tools they hate. The choice of editor/IDE is one of the most personal that a professional developer makes. Let's ship code that stands on its own (with an independent build system for heaven's sake) and not even implicitly force the use of particular IDEs.


I see your point, however, function parameter lookup is present in all IDEs I've tried/worked with (VSC, Atom, Jetbrains').

Is boolean flags antipattern? Well, this all depends on the workflow. I follow ideology of making thing work first, then making it perfect. If introducing flag saves me two hours that I can spent to deliver on time - hell - why not - knowing that everyone who works with me uses some modern text editor / IDE - they will know immediately what's the parameter is doing. Also, what I've observed is that most of the people do have a habit of `fn + click` into function they've never seen before - so they will learn about parameters one way or another.

Cheers


If the name is mandatory, as it is in Smalltalk, then this basically solves the issue.

If the name is optional, as it usually is in eg. Python, then there is a temptation for the writer to omit it, which means the reader won't know what "True" or "False" stands for.

Are there languages besides Smalltalk and its descendants with mandatorily-named parameters?


In Python 2, if you need to, you can force people to use kwargs by defining the function in the form of

  def f(*args, **kwargs):
and then making sure any params you use in the function come from kwargs, and raising an error if args is non-empty.

Python 3 has a nicer way of doing the same thing, that I can’t remember.

(Sourced from the book “Effective Python: 59 Specific Ways to Write Better Python”.)


In Python 3 at least, anything after the * args is a required keyword-only argument:

    >>> def a(b, *args, c): print(c)
    >>> a()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: a() missing 1 required positional argument: 'b'
    >>> a(3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: a() missing 1 required keyword-only argument: 'c'
    >>> a(3, c=5)
    5
It's also valid to define it this way, if you don't need the * args:

    >>> def a(b, *, c): print(c)


Please tell me you have not been coding in Python for the last five years.


Huh? Why?


In javascript you can use an object, and then use destructuring to automatically convert the properties into local variables within the function.

Which is super useful and easy to read.

getUserMessag({userId:1234, retriveFullMessage:true})

https://codeburst.io/es6-destructuring-the-complete-guide-7f...


> You’d be surprised by the number of candidates who say they are “senior software engineer” or “10 years experience as a lead developer” who still can’t do FizzBuzz. Or the ones who can do it but takes them 100 lines of code.

I see comments similar to this one all the time. Are folks literally referring to the 'FizzBuzz' problem, or is that just an alias for a problem they subjectively find easy?


I love my leopold fc660c


First of all, zzzeek, thanks for your great software. While working on SQLAlchemy, have you ever run into situations where you really missed static typing? Do you ever see yourself wanting to introduce Python's static typing behavior into that project, and why or why not?


I did nothing but Java from around 1998 to 2002 and then again around 2006-2008, and there is definitely a deep satisfaction when you have built your giant statically typed castle and compile it and then it runs the first time. In Java though, obviously the verbosity that implies, particularly when I was using it pre-generics, most certainly erased any productivity gains and made for code that was very difficult for new people to understand, tests were in particular extremely hard to write. So at least with Java's widely criticized model, it was sort of nice-ish but hard to say it was worth it.

What Python is doing with typing I think is going to be amazing though. Just not sure if I'll have time to embrace it fully within my own projects.


The most common issue I run into is with datetime objects, but there are well documented workarounds. For more complex objects such as ORM objects, I think a lot of people use Marshmallow. That being said, I don't have a lot of experience, so I could be missing something obvious. What issues have you had with Python JSON serialization?


I wouldn't say I've had issues, I just don't think it's really been easier/quicker in Python than most other languages I've used except for the simplest use cases (when Flask jsonify does everything you need because your data is all just strings, numbers, and booleans already)


> If web developers don't already all know this then what knowledge do they have nowadays?

Read the article's title. This article is clearly aimed at people who are starting to learn web development. It is not aimed at experienced web developers.

> ...these were all skills I had mastered before even attempting to define what type of development I wanted to do

Many people learn how to program by working on projects they want to work on, and a lot of people want to build web applications.


You casually read literature written in Latin?


You don't need to casually read it. Reading it side by side with the translation, however, definitely gives you a much deeper comprehension of the original and its subtleties. I read bilingual texts (particularly latin, or poetry) as much as possible for languages I can't read casually.


That is exactly what it is. I'm really surprised other folks aren't able to sense this.


I absolutely relate to this. But hey, knowing that there are other engineers out there feeling the same thing when they read HN makes me feel better. So, thanks.


I love you.


Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: